Export PDF từ HTML hoàn hảo nhất

Siêu™
Siêu™
Sep 5, 2018 · 2 min read
Đau đầu vì test cứ bắt fix lỗi 1px trên pdf :v

Khi export PDF từ HTML thì mọi người sẽ nghĩ ngay đên tcpdf hoặc mpdf (base on fpdf và html2pdf). Nhưng 2 thư viện này rất kén thẻ html, css dẫn đến khi view nội dung trên web và file pdf là không giống nhau. Nếu sử dụng 2 thư viện kia thì dev sẽ mất thời gian để chỉnh sửa nội dung html, css cho phù hợp.

Sau khi tham khảo bạn bè + tìm kiếm trên Google thì mình tìm được tài liệu về Chrome Headless (https://developers.google.com/web/updates/2017/04/headless-chrome)

Mình đã chạy thử lệnh

chrome --headless --disable-gpu --print-to-pdf=/tmp/test.pdf https://www.chromestatus.com/

Kết quả không như mong đợi vì ở header và footer có thông tin về ngày tháng, tiêu đề, đường dẫn và số trang. Mình loay hoay mãi nhưng không tài nào tìm được options để bỏ nó.

Sau đó đọc kỹ hơn thì thấy thư viên Puppeteer đáp ứng được yêu cầu.

chuẩn và đẹp

Nếu dự án của bạn chạy hoàn toàn bằng nodejs thì chỉ cần thư viện Puppeteer (https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepdfoptions)

Còn nếu dự án là PHP thì sử dụng thư viện Browsershot (https://github.com/spatie/browsershot#requirements)

Cách cài đặt và triển khai thì ở các tài liệu nói rất rõ. Các bạn cứ làm theo là được.

VNEXT LIFE

Stories from Vnexter

Siêu™

Written by

Siêu™

I am a PHP Developer. And I want to become Superman.

VNEXT LIFE

Stories from Vnexter

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade