简体   繁体   中英

Generate PDF from Template using Javascript

The situation is the following: We have a website, that generates (large) contract-JSONs which we now want to export as pdfs using the frontend, so javascript. At the moment, I use pdfmake but i find it very hard to get a layout that stays the same for every contract. I would prefer to have some kind of template which i could fill with the values from the JSON.

Best I can think of at the moment would be to write a pdf template with LaTex and fill it with some template framework and compile it with a LaTex compiler. However I hope there is something simpler you could tell me. It's only important, to get from JSON to the pdf in one click.

I have done some research for a similar scenario. Below are three options that i shortlisted :

  1. HTML-PDF (nodejs module)
  2. WKTHMLTOPDF
  3. PhantomJS (even the first two options uses phantomjs)
  4. jsPDF - can be used at client side

I ended up, using pdfmake. First I understood it wrong, which was the cause for me not being able to edit a pdf. Now I know, that you can layout your document nicely by using lots of columns.

I tried to read a .tex file and fill it using FreeMarker. This worked very well, however not having an online LaTeX compiler, i would have had to force customers to compile the .tex files locally which i did not want.

However, if you have a LaTeX compiler locally, this should work.

After having this solution running for some time, I want to add that changing the document afterwards (add a table for example) is pretty tough in this scenario. If I'd have to do it again, I'd probably try to implement the building blocks of the pdf as latex-templates with placeholders. Like directives in angular. In the document building process I would go through template by template, generate the Latex-Blocks (like tables) using the data I received from the backend and I'd use FreeMarker to fill the generated data into the templates and afterwards put the templates into one complete latex file, holding the whole pdf in latex. Using a js-Latex compiler like texlive, I should be able to generate the pdf from this file.

All of this is in theory and probably more work than what I did, but I like this solution better, since it's cleaner and easier to maintain. Learn from my mistakes :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM