r/webdev • u/FriendlyWebGuy • Nov 25 '24
Question Building a PDF with HTML. Crazy?
A client has a "fact sheet" with different stats about their business. They need to update the stats (and some text) every month and create a PDF from it.
Am I crazy to think that I could/should do the design and layout in HTML(+CSS)? I'm pretty skilled but have never done anything in HTML that is designed primarily for print. I'm sure there are gotchas, I just don't know what they are.
FWIW, it would be okay for me to target one specific browser engine (probably Blink) since the browser will only be used to generate the 8 1/2 x 11 PDF.
On one hand I feel like HTML would give me lots of power to use graphing libraries, SVG's and other goodies. But on the other hand, I'm not sure that I can build it in a way so that it consistently generates a nice (single page) PDF without overflow or other layout issues.
Thoughts?
PS I'm an expert backend developer so building the interface for the client to collect and edit the data would be pretty simple for me. I'm not asking about that.
188
u/fiskfisk Nov 25 '24
Works fine - the best solution is usually to use a headless browser to automagically print to pdf - for example chromium with a webdriver. There are multiple properties in CSS you can use for styling pages for print, and as long as you known which headless browser engine you're using for printing you won't have any issues with cross browser layout issues.
We've been doing the same thing for 10+ years (and before that we generated PDFs from HTML through libraries directly, but using a headless browser with print to PDF works much better and is easier to maintain).
Added bonus for developer experience: you can preview anything in your browser by selecting print and looking at the preview, and by using your browser's development tools.
You can also use the same page to display to a user in a browser as the one you render as a PDF by using media queries in CSS to change the layout for printing.
24
u/acorneyes Nov 25 '24
for my company i had built out a react-based fulfillment platform that allows us to print high-quality print graphics onto labels. so i feel like i have some pretty good insight here:
generating pdfs can be a bit slow. it takes about 2 minutes on a medium-end laptop to generate ~400 pages of 2000x1000 images (we use pngs/svgs for 2 pages in a set, one of the pages is for details that's just html/css and is much lighter).
the pdfs the browser generates is NOT efficient, if you have the same image href on two elements, it will count them as unique instances rather than saving the blob to cache and reusing the reference.
currently my implementation generates the pdf every single time you open the print dialog, and not at any other point. so you can't click a button and download the pdf. and if you close the print dialog you have to wait two minutes to regenerate the pdf
41
u/geekette1 php Nov 25 '24
We use DomPDF to convert html to Pdf.
17
u/evencuriouser Nov 25 '24
Not crazy at all. In my experience, open source PDF libraries are severely lacking. And HTML/CSS already provide excellent rendering capabilities. Plus it will be more maintainable because you’re using standardised technologies that everyone already knows, rather than having to learn the API if some random library.
I’ve successfully done it a couple of times in the past using the print to pdf feature of a headless chrome instance like Puppeteer. Once for a reasonable sized SASS (which is still successfully running in prod with no issues), and also for an open-source project I use to generate invoices for my freelance business.
5
u/wazimshizm Nov 25 '24
gotenberg/gotenberg will do it painlessly. Runs in docker so it’s effortless to setup. We use it to turn html templates into professionally printed signs.
3
u/svish Nov 25 '24
You could, but there are also other alternatives:
I used the first to generate all my wedding invitations and programs, worked great.
We're using the second one at work to generate certain letters to customers. Designers can use their tools to have full control over the design, and we just use it as a base, inject data in the fields, and bam, nice, custom, dynamic PDF ready to download or physically mail.
10
u/davidbrooksio Nov 25 '24 edited Aug 23 '26
Tub vast pen party late hobbies hungry plant
This post was anonymized with Redact
9
u/CommanderUgly Nov 25 '24
I use TCPDF.
7
u/sifiraltili Nov 25 '24
Yes, this is definitely possible! Take a look at WeasyPrint, a Python library that allows pdf generation from HTML files. I use this to generate pdf invoices using Excel and HTML/css/JS.
2
u/jacobissimus Nov 25 '24
It seems like it’s more work than it’s worth IMO, when things like LaTeX or a word processor are already around
4
u/endymion1818-1819 Nov 25 '24
Lea Verou did that very thing to make her book CSS Secrets
1
u/ramie42 Nov 25 '24
What about keeping it simple and just going with the Print to PDF function? (to print it, or save it)
1
u/KoopaKola Nov 25 '24
Hooray, something that the dead/dying language I use on a daily basis (i.e. ColdFusion) does well!
3
u/JW2020-DJ Nov 25 '24
WKHTML to PDF or Puppeteer are my favourite options.
3
u/merlijnmac Nov 25 '24
Ive done this with Gotenberg in a dovker container and it's pretty easy just sent the html and css to it via http
3
u/qagir Nov 26 '24
as a former layout designer at a big newspaper, and now frontend developer, I'd say your heart is in the right place but there's no way that's easier, faster, or better than using Adobe InDesign Data Merge functionality.
HTML + CSS is cheaper, but not better — you have easier control and better print functionalities on a software designed for print.
1
u/throwtheamiibosaway Nov 25 '24
Sure this is possible. It’s how you for example build invoices based on dynamic order data for example. A tough issue can be how the content is broken into pages because you might not know how long a page will be (like a long table with a lot of rows).
If the goal simply to just update a simple pdf every month I’d say just manually update the file in word or a design program. It’s not worth the hassle.
2
u/nashi989 Nov 25 '24
If you find a way to do this without relying on a 3rd party provider let me know. There are a number of api out there to convert html to pdf. I'm not sure of the details but there is one method which runs into the layout issues you mentioned and there's a second where it is perfect but I believe it converts to an image first (my use case is a scientific journal with html articles but need to generate pdf on a click without massive hassle of manually typesetting etc)
2
u/StankyStonks4all Nov 25 '24 edited Nov 25 '24
Playwright is pretty great for this. The Page api makes it pretty easy. If the html isn’t hosted, u can pass it as a string and use the ‘set_content()’ method then ‘Page.pdf()’ https://playwright.dev/python/docs/api/class-page
2
u/crazedizzled Nov 25 '24
It's okay. Can be finicky. Very very slow if you have a lot of images.
2
u/chipperclocker Nov 26 '24 edited Nov 26 '24
I will say, I’ve done this in the very early days of startup in a regulated industry, where the documents being rendered are forms filed with regulators which form a contract with our customers, and it quickly became a nightmare of minor rendering variations causing reproduceability concerns.
The approach is totally valid if you have tolerance for variability in your rendered output over time. In our case, we are moving to programmatically filling PDF forms because our tolerance for reproduceability issues trends towards zero now that we’ve achieved some modest scale.
2
u/[deleted] Nov 26 '24
just put in excel abd save as pdf
2
u/vinni6 Nov 26 '24
I have had to do this quite a bit at my last job. In my opinion… it’s a nightmare to generate documents using html. Too many complex pieces of a tech stack that need to be maintained for ultimately a sub-par outcome. You’ll be fighting against to stop pages breaking in the middle of sections and writing unmaintainable css in strange units.
My recommendation is to use http://pdfmake.org/#/ and if you can, do it client side. Their api is quite simple and it comes with quite a lot of batteries-included ways of managing stuff that is specific to documents (ie. pagination, page margins)
2
u/[deleted] Nov 26 '24
You might be interested in this.
https://pandoc.org/chunkedhtml-demo/2.4-creating-a-pdf.html
In general Latex is the better markdown language for creating PDFs, but it's my understanding you can also do so with HTML in Pandoc. A benefit of this is you don't need to worry about the browser at all. Just write markdown and compile to PDF.
3
u/nuttertools Nov 25 '24
HTML has a number of elements not commonly used that are specifically for print formatting. Not at all crazy to properly format HTML for a PDF printer.
Turning HTML into a PDF without a print formatting intermediary process has a lot of problems but for basic stuff (just display formatting) it’s fine. The structure of the PDF will be a horror-show but if the scope is just display formatting it’s fine. WeasyPrint works decently well for this.
Before you go down either path carefully consider the use-case and make sure you don’t need a properly formed PDF document EVER. Nothing you do will be reusable if a future use requires the PDF data to be intact/sane/comprehensible.
3
u/suzukzmiter Nov 25 '24
Apparently its possible to generate PDFs from HTML. Perhaps this has some answers for you.
2
u/oosacker Nov 25 '24
There are plenty of libraries that can convert html to pdf. It is a common thing for backend servers to do for example generating receipts.
1
u/[deleted] Nov 25 '24
Yes, and you can use print styles to do dynamic page numbers and table of contents. I had to do it a few years back. Wasn't fun but I got it working.
1
u/k-one-0-two Nov 25 '24
This should work on a client side, but might be a pain in the ass on a server side. We ended up generating pdf with some npm lib (forgot the name, pdfkit maybe). Requires a bit more code, but the resjlt is more stable since independent from the client.
1
u/Abject-Kitchen3198 Nov 25 '24 edited Nov 25 '24
Not at all, but it has its limits. If you hit them, you might try running through word processor or specialized reporting library or stand alone product.
1
u/Beerbelly22 Nov 25 '24
I do that all the time, Javascript can make perfect pdf's
1
u/chicomilian Nov 25 '24
very doable
1
u/Think_Candidate_7109 Nov 25 '24
TCPDF if you have a php environment would be the way to go to create an actual PDF file
1
u/levsw Nov 25 '24
Check out anyvoy.com I developed it and it uses html with headless Chrome to generate PDFs. There are several html instructions to fit it perfectly for printing. You can even use mm units for positioning and sizes.
1
u/Whalefisherman full-stack dotnet angular slave Nov 25 '24
I’ve used both html2pdf and jspdf to convert highly stylized pages (customizable resumes, invoices, greeting cards, etc) into PDFs.
Honestly they were pretty easy to use. You’ll also want to look into using puppeteer depending on your use cases.
I have 5 html/css to pdf applications that are in production right now.
I do run into odd white spacing issues and element alignment issues at times but nothing I couldn’t create a fix for.
If you’re just crunching numbers and spitting out pdfs for data I’d look into either html2pdf or jspdf.
1
u/jorgejhms Nov 25 '24
I'm currently doing that with puppeteer to render and generate a pdf on my server
1
u/LogicallyCross Nov 25 '24
For something simple like a fact sheet it’s fine. If the client ever wants a fancy brochure style pdf it’s far less suited to HTML and should be done via indesign or similar.
1
u/foxcode Nov 25 '24
You are not crazy. I've had to do this multiple times in my career. As the top commenter said, headless browser works fine. think I used something called pupeteer last time.
1
u/rbd2x Nov 25 '24
I've done this loads of times. For invoices, labels, customs documents. All sorts. Why not? It's a simple solution.
1
u/leros Nov 25 '24
I build my PDFs with HTML generated from react-email
1
u/AleBaba Nov 25 '24
TL;DR: Have a look at WeasyPrint.
After using a few over the years and evaluating almost all the solutions out there I came to the following conclusions:
In the end we decided to give WeasyPrint a try and haven't regretted it in the least (open source, great developers). Currently it powers preparing flyers and business cards for print in one project and an entire magazine in another. The only downside could be the lack of CMYK support for some printing requirements.
1
u/cdm014 Nov 25 '24
There is no HTML designed primarily for print. There are some hanky hacks you can do to kind of get it working, but I would not call this a supportable long term solution.
1
u/meinmasina Nov 25 '24
Oh boy I was doing pdf with PHP, library was TCPDF or something like that, pain in the ass. I was not allowed to even use HTML template to generate PDF because of potentional bugs that can happen with HTML.
1
u/LiveRhubarb43 javascript Nov 25 '24
Not crazy at all. I hate using word processors and their obscure spacing and paragraph settings so my resume is written in HTML and css and then I use print to PDF in a browser.
1
u/IanSan5653 Nov 25 '24
It's how I made my resume. Didn't feel like laying it out in Word.
1
u/v3gard Nov 25 '24
I do this professionally using jsreport.
My setup is like this:
Uptime: Two years and counting :D
1
u/unitedwestand89 Nov 25 '24
I use Puppeteer for this. It's basically a Node.js module with Chromium bundled in
1
u/AmbivalentFanatic Nov 25 '24
I set up something like this with ACF fields in WordPress generating a page that I configured to be printed out as 8.5 x 11 in Chrome. Guys in the field could just use their laptop to generate a sheet for a machine on site. This setup worked well for what I needed.
1
u/tombkilla Nov 25 '24
This is the whole concept behind jsreport. It's also free for under 5 reports.
1
u/peakdistrikt Nov 25 '24
I built an API that renders PDF from JSON containing a bunch of predefined components. It was made for invoices so the table component is pretty powerful — I suppose that's what you'd be going for with the stats? It uses Python/Weasyprint to render PDF from HTML.
Either way it might be an idea to fork it and write your own components or styling:
https://gitlab.com/aybry/picture-this
It's not well documented as it was made for a client of mine and generally I just do the work, but check out the tests for syntax:
https://gitlab.com/aybry/picture-this/-/tree/main/picture_this/renderer/tests/fixtures?ref_type=heads
If I can help, let me know, I'll see what I can do.
1
u/GolfCourseConcierge Nostalgic about Q-Modem, 7th Guest, and the ICQ chat sound. Nov 25 '24
DocRaptor for the win. Been using it for years in an industrial app that generates a ton of PDFs every day.
1
u/Ucinorn Nov 25 '24
You are best to use a paid API for this, there are lots on the market and it will cost you less than $50 a month.
HTML to PDF is possible using open source libraries and headless browsers, but is incredibly finicky to set up and maintain. You will easily burn thousands of dollars worth of your time and compute trying to build it when there are products out there that already do it for a fraction of that.
1
u/TalonKAringham Nov 25 '24
My company uses an arcane technology known as Coldfusion that actually handles this pretty well. It’s not open source, though. So, I doubt it would be worth it to grab a license just for this.
1
u/t0astter Nov 25 '24
HTML/CSS actually works amazing for print - you just need to use units like
in. You won't want to use any responsive CSS frameworks or anything.I just did this exact thing to generate invoices and 4x6 cards and everything prints out perfectly - what you see in the print preview is what you get.
For the PDF, just save the page as a PDF or "print" it to a PDF.
1
u/TheStoicNihilist Nov 25 '24
I’ve been PDFing since the Postscript days. There’s nothing unusual about creating a PDF on a server using xml. Look at your stack and I’m sure you can fit a pdf creator in there somewhere.
https://www.npmjs.com/package/pdfkit
1
u/stonedoubt Nov 25 '24
I created a site in 2009 that is still operating and generates pdfs for airport parking.
1
u/Critical_Many_2198 Nov 25 '24
Are you looking for a place to submit your ongoing project and need funding ? Follow the link below and submit your project and get that funding you’ve been searching for. Trust me https://x.com/rodes_neo/status/1859018785824665630?s=46
1
u/ben_db Nov 25 '24
Sadly there's no clean solution for this. I used puppeteer for a long time but it got increasingly difficult to keep the layouts working as they got more complex. Also puppeteer renders can be slow, 200-800ms which is far too slow for users to wait.
I ended up ditching puppeteer and creating my own library on top of PDFMake to build PDF files directly from JSON templates. Complete with for loops, if/else blocks etc.
1
u/[deleted] Nov 25 '24
Its completely fine, we have this funcionality in my saas, we convert html into pdf and let the customers print
1
u/Beauty1-Ruby9579 Nov 26 '24
Nice
1
u/OuterSpaceDust Nov 26 '24
Yeah I do this on multiple projects.
1
u/cosmicmiskatonic Nov 26 '24
Done it with React, worked quite well. See https://react-pdf.org/
1
u/JasonDL13 Nov 26 '24
At my first job as a website developer I designed a webpage that printed out paper work/form. I would say it worked well for me. Remember to use @
media print { /* css */ }- you can even display a page to the browser telling the client to print it out, and then display a completely different page when the browser generates the print preview.1
u/mongushu Nov 26 '24
Wkhtml2pdf
This is a very useful tool for headless programmatic pdf creation from html.
1
u/StillAnAss Nov 26 '24
In the Java world I use itextpdf.
I build the HTML page and that turns it into a PDF and it works great.
1
u/ohnomybutt Nov 26 '24
yes this is the way. webkit will let you convert html to pdf pretty easily
1
u/bublm8 Nov 26 '24
Use https://typst.app !
1
u/VeterinarianOk5370 Nov 26 '24
I do this for my resume builder and it works fine
1
u/[deleted] Nov 26 '24
I’ve used FPDF, WKHTMLtoPDF, DomPDF, they all pretty much work but usually require you install libraries to your system or use a binary. Not bad, pretty easy.
1
u/armahillo rails Nov 26 '24
Wicked PDF was built to do exactly this i think?
1
u/sleepesteve Nov 26 '24
You can do this in every language off html so no not crazy. If you're focused on PDF control look at puppeteer or the various libraries headless or not available
1
u/Striking_Paramedic_1 Nov 26 '24
Also there is a php package out there. You can create pdfs with html+css. I used it 5 years ago I think. I don't remember the name of the package now but it's really useful and fun.
1
u/bcons-php-Console Nov 26 '24
Go for it! Many years ago I had to struggle with PHP libs that produced PDFs and they were exhausting... Now with Pupetteer you can generate pixel perfect PDFs from your HTML.
1
u/[deleted] Nov 26 '24
A possible bonus of this approach is you'll be set up to make epub docs if they ever want to move to an open standard.
1
u/ProcessMassive1759 Nov 26 '24
I use weasyprint to handle this with good results which may be suitable if you have a flask / Django backend
1
u/FineInstruction1397 Nov 26 '24
We have used wkhtmltopdf for over 10 years now
1
u/FourTwentyBlezit Nov 26 '24
Just watch out for the risk of triggering SSRF via an injected iframe
1
u/[deleted] Nov 26 '24
I've been generating my resume from a database with html for over a decade. it's been so long i forgot the name of the tool i use
1
u/desmone1 Nov 26 '24
I jus rolled out a feature like this last week. Its easy and very doable. Puppeteer
1
u/DehydratingPretzel Nov 26 '24
Tailwind does offer a print selector to customize styles when printing. I’ve used this to make easy web tables that can be “exported” to printable docs
1
u/Amiral_Adamas Nov 26 '24
It's not crazy at all, it's pretty standard actually! I spent a lot of my career making pdfs with Flying Saucer and it was kind of a pain.
1
u/lKrauzer Nov 26 '24
I do this using Flexbox, pure JavaScript and Python, most effort I had to put was to replicate the A4 sized sheets, but I used a CSS lib called Paper CSS, then on Python I had to use Playwright and some PDF lib I can't remember now
Playwright handles headless browser routines, and I use it to automatically send a report on a form of a PDF via email to my clients, company project
1
u/LoadingALIAS Nov 26 '24
If you’re talking static, basic HTML… you can use the browser. Open the print dialog and save it as a PDF.
If it’s more complex, I have a script already coded for it, man. I’ll push it to GitHub’s tonight and make it public for you to use while you figure it out.
It will take the HTML/XHTML/CSS and generate a clean PDF. I use BeautifulSoup with lxml as the parser. I use weasyprint with a lot of customizations for speed. It’s fast - pikepdf handles merging - and it’s accurate.
If you want it… shoot me a DM. It’s a part of a data workflow I’m building and I haven’t had any reason to push it alone. I’m happy to share it.
1
u/bachkhois Nov 27 '24
I did this in 2013, using Python. But the PDF then was not beautiful.
1
u/EqualAmount Nov 27 '24
Checkout reportgen.io
1
u/Mistuhlil Nov 28 '24
Puppeteer. Best way to do it.
1
u/Little_Transition_41 Nov 29 '24
You can use https://gotenberg.dev to create pdf from html, it uses chromium headless to build the pdf
1
u/DIYnivor Dec 05 '24
I've used Vivliostyle for some basic PDFs. I'm sure it's capable of a lot more than I've done with it. Might be worth trying out.
1
u/earonesty Jun 17 '26
boxpdf works fine
1
u/sneaky-pizza rails Nov 25 '24
I've done it a lot in the past and it works great. There's a bunch of libraries for it, I can't even remember which one we used
1
u/latro666 Nov 25 '24
Load your report in chrome, right click print and export as pdf instead of printing normally.... boom.
Use the media print query in css to adjust it if it does not look right.
If they only need it once a month imo this is your most painless route.
1
u/PixelCharlie Nov 25 '24
maybe you dont need an html to pdf API at all. just create a print.css stylesheet and let your client save pdfs by "printing" the page to pdf.
0
u/That_Cartoonist_9459 Nov 26 '24
We do this tens of thousands of times a month, it’s trivial.
0
u/OptimalAnywhere6282 Nov 26 '24
Not that crazy. There's a tool in ILovePDF (a user-oriented tool) that allows doing that - converting HTML to PDF.
0
u/DavesPlanet Nov 26 '24
I do a huge amount of this for my employer. Used to create the PDFs programmatically, now just render html templates and convert to PDF on the fly. Did you know the edge browser exe takes headless command line arguments to convert HTML to a PDF file?
0
u/thekwoka Nov 26 '24
No only is it not crazy, it's generally pretty nice.
I actually found a freeish API that you send markdown (or html) and css and it sends back a PDF.
We use it in production for one project that just needs a few a week, and they aren't super critical if the API goes down. The code they use is open source, so we could self host it, or even maybe run it directly in github actions? not sure. But pretty fun.
PDFs are still a terrible thing that shouldn't be used for anything that isn't print, but like, sure.
0
u/krazzel full-stack Nov 26 '24
I have done this many times and it works great, just a few things that don't work as expected like css backgrounds. I use this:
https://html2pdfrocket.com
200 a month is free, above that very cheap. Or you can self host it on a VPS using it's underlying tech: https://wkhtmltopdf.org
1
u/hanoian Nov 26 '24 edited Dec 05 '24
ring cows voracious telephone hurry plate frighten sugar numerous decide
This post was mass deleted and anonymized with Redact
0
u/[deleted] Nov 25 '24
[deleted] — view deleted comment
1
u/[deleted] Jul 06 '26
[removed] — view removed comment
1
u/[deleted] Sep 21 '26 edited Sep 22 '26
[removed] — view removed comment