Convert HTML in PDF

Download as pdf
Download as pdf
You are on page 1of 33
3722724, 10:26AM How to convert HTML to PDF using Nodes APITemplate.0 AAPITemplate.io s>x/0tenpaei How to convert HTML to PDF using Node,js. By Manoj Aniewar i Soptember 6,2023(https:/apitemplate.o/2028/03/08/) Most real-world applications encounter the requirement of generating PDFs based on some content. This Includes generating PDFs from custom HTML content or even generating PDFs directly from a website URL, Earlier, we needed to write a lot of custom code to get this done, and it used to take a lot of time. But now, there ‘are many great libraries and tools that can do this with just a few lines of code. In this article, we will look into some approaches that we can take to generate PDFs from HTML using Nodejs. 1. Nodejjs Libraries that Convert HTML to PDF Converting HIM pages to PDF is a common task that developers encounter, whether is for generating reports, invoices, or contracts. n this article, we wil delve into three popular Nodejs libraries for converting HIM to POF: + Puppeteer + ntmi-pat + jsPOF Well explore their features, benefits, and limitations, along with code examples to help you make an informed choice for your next project. $o if you're looking for a reliable way to convert HTMAL to PDF in a Nodejs ‘environment, read on, Prerequisites Before going into the implementations, first make sure that you have @ Nodevs environment ready. I not, you can install NodeJs from the official website nodejs.org/en (https;//nodejs.org/en). Also, we will be sing the apm package manager to handle our dependencies. htlps:fapitemplatelfblogInow-te-convert-htmte-pausing-node-js! 1133 3722124, 10:26 AM How to convert HTML to PDF using Nodes APITemplate.0 2. Puppeteer Puppeteer (hitps://pptrdev/) is a Node library that provides a high-level API to control headless browsers via the DevTools Protocol. It is commonly used for web scraping, automated testing, and generating PDFs or screenshots. It can perform actions such as clicking buttons, filing out forms, and capturing screenshots or POF. Install Puppeteer Generate PDF from a website URL const puopetear = racuire 0p i sync fuction generateobe(ur, outputeath) one orowser = aatt puppeteer louneh) fons page = suas browser nePape() date page por 93 te brower-clse() > owtputbath, foomats "AE D)5 senertePos (nets: //apoplecor’, ‘goopleoet") ‘hen(() => conse, o4( "PD" generates Successtully")) eateh(eor => consle.error(‘Ereongorersting POF:", et) In the above code, if you look at the method gensratePDF, we are doing the following things: |LFirst, we launch Puppeteer, which launches « headless browser. 2.\We create o new page and navigate to our specific 3. Now the important partis page.péF(), which takes the path to the PDF and the format for the POF. 4. Finally, we can close the browser once the PDF is generated. Generate PDF from Custom HTML content const puppeteer = resutre puppeteer"); syne function generatesDrFromameihentCantent, outpuPath) ¢ const browser = avait pupgetear. launch); fens page = aust broweer-naPage() ba page-retcontent(healtatene}: Dott browseereloset); > nse inlContent = ‘chisel Worléc/ntnonthis 4s castan MIML content reveratepoFtromM(henicontent, " console gl'POF generates successtolly')) eateh(enr o> consle.error(‘Erson gerarsting POF:", er) Inthe above code, you can see that in the method generstePDPtomlITML. nitps:/aptemplate ofbloghow-to-conver-himl-to-pdF-using-node-j! 2189 3722124, 10:26 AM How to convert HTML to PDF using Nodes APITemplate.0 |LFirst, we launch a headless browser and create a new page. 2. Now, we only need to set our custom HTML content, which will be used to generate the PF. 3.Finally, we generate the PDF and close the browser. 3. htmI-pdf html-pd¥ (https: //github.con/marcbacheann/node-html-pdf) is a NodeJs library that generates PDFs from HTML sing PhantomJS. Itis @ simple yet powerful tool that allows for easy POF generation from HTML templates. Install htmI-paf Generate PDF from a website URL feast andes = reuire(“aetes'): fons pat = regret ntei-ps’) saync foction neers DOF FromRL (ur, outout fonst response = salt sete. get(or) p.croata¢ntnicontert).20Fae(outpuePat, (ore, res) = 16 re) return console L0g(om)s ensole.20g("90F generated sucessfully, #e8)t bs ) ten (error) ( fenolescrrar(‘Eeror fetching WAL:', errr) , , eneraterortoonit(Hetps://goglescon', “google-pé"); tnmlpdf does not support generating PDFs from website URLs out of the box, which is why we first need to extract the website content using axios. Once we have the content from the webpage, we can then use the himl-pdr library to generate a POF from the website content. Generate PDF from Custom HTML content east put = require htal-pdf function gonerstrortreah (enlcantent,outputPath) por.create(htaContert)toFalefoutQutPathy fern, Fe8) 4 1 (ere) return consie.togterr)s orale. 1op(‘POF generated sucessfully", 102) bs , 1 sage feast mtnlContent « “co>ThSs 4s aston MIML content cp> enerateror comm (tenlcontnt, "euetonps)5 Now, if you look at the code above, we are using the create) method from the library, which takes our custom HTML content and generates a POF file to the output path, nitps:/aptemplate ofbloghow-to-conver-himl-to-pdF-using-node-j! 182 3722124, 10:26 AM How to convert HTML to PDF using Nodes APITemplate.0 4, jsPDF jsPOF (https://github.com/parallax/isPOF) is a JavaScript library that allows you to generate PDF files from HTML programmatically It works in both Nodejs and browser environments. I's highly customizable, allowing you to ‘add text, images, and even vector graphics Install jsPDF Generate PDF from a website URL custo aso8'95 fenst $200" = reulret Sends U(r, out east response = aait axis. get(ordds fenst doc = new JO" oc. save(outputath); feorole,lop( POF generated suceseély"); eaten (error) ¢ fensoleverror(Eeron fetching URL", errors eneratePoFfromL (https: /goagle.con',“goagle-péf"); 45PDF (https'//github.com/parallax/jsPDF) also does not support the generation of PDFs directly from website URIs out of the box. We need to use libraries ike axis to first get the content from the webpage and pass that ‘content to the library function to generate PDFs, One other customization with jsp is that you ean pass ‘coordinates for the elements in the PDF, and then the elements will be rendered to those locations in the PDF. Generate PDF from Custom HTML content const JaP0F = reuiret"Jent) function gonerstror reas (enlcarteat, outputPath) const doc = new 3P960; docctetgnenscontent, 38, 18); doe tove(ourpetraeh) onole log( POF generated sucessfully") , 1 age eneratePorteomMtenicontent, “euston pa )5 Generating a POF from custom HTML content is pretty straightforward with jspdf, similar to generating a PDF from ‘a website URL as we have seen above. nitps:/aptemplate ofbloghow-to-conver-himl-to-pdF-using-node-j! 4139 3722124, 10:26 AM How to convert HTML to PDF using Nodes APITemplate.0 5. Comparison of Puppeteer, html-pdf & jsPDF Each of these libraries has its own set of features, capabilities, and limitations. The comparison table aims to provide a side-by-side overview of these libraries across various dimensions such as speed, capabilities, and dependencies, helping you choose the one that best suits your project requirements. Feature/Aspect Puppeteer htmi-paf | jsPoF Purpose Browser automation and POF HIML tO POF POF generation using Javascript generation conversion Language JavaScript Typeserpt JavaSeriptiNodejs | savaseript Browser Engine | Chromium Phantomis None: Headless Yes Yes Nia Dependencies | Requires Chromium Requires Phantoms. | No‘extra dependencies HTML to PDF ves yes Lmited (HM. supports not native) Vector Graphics | vos imited Yes Text Support excalent 00d excelent (688 Support bxcallent 00d Limited JS Support full Limited No Multi-page yes Yes ves Fonts ‘Any web font Limited Bult-in & TF Image Embedding | ves ves Yes Outputrormat | POF, Screenshot oF POF, mage (via plugins) Platform Nodes, Client-side 1S Noses Nodes, Clent-side JS Page Manipulation | Full control (OOM, 055, 5) Limited (HTmi/css) | No (unoss contentis created manually) Speed Moderate (depends onthe task) | Fast (for simpler | Very Fast (or basi POFS) os) ‘community igh Moderate High support Updates/rixes | Regulor Loss frequent Regular tn conclusion: + Puppetesr is highly versatile and is ideal for projects that require full web features, including JavaScript ‘execution, complex layouts, and CSS styles. It has the best support for modern web technologies but can be slower and has @ heavier dependency (Chromium), + htmi-pat is quicker for simpler tasks and can still convert HTML to POF. However it relies on the deprecated PhantornJS engine, soit might not fully support all modern web features. Its use is generally advised for simpler tasks or legacy projects. + JsPOF is excellent for creating basic to moderately complex POFs directly through JavaSeript. I's fast and lightweight, but its ability to convert HTML and CSS to POF is imited compared to the others. Ideal for ‘generating PDFs that don't require HTML/CSS rendering. nitps:/aptemplate ofbloghow-to-conver-himl-to-pdF-using-node-j! 5133, 3722124, 1026 AM How to convert HTML to POF using Nodes ~ APITemplate‘o Your choice should depend on your specific needs: for full HTML/CSS/JS support, go with Puppeteer; for quick ‘ond simple HTML to PDF conversion, htmi-paf may suffice; and for programmatic POF creation without browser dependencies, jsPDF is a strong choice. 6. Create PDF from HTML using APITemplate.io Above are some examples of how we can use libraries to convert HTML to POF and web pages to POF in NodeJs. However, when it comes to generating PDFs using templates or keeping track of generated PDFs, we need to do allot of extra work to handle everything, We need to have our own PDF generator tracker to keep track of the files generated. If we want to use custom templates such as invoice generators, we also need to create and manage those templates. -APITempiatezio (nttp://apitemplateio/) is an API-based POF generation platform that offers the perfect solution {or all of the above use cases. In addition, APiTemplateio’s POF generation API (hitps;//opitemplateio/pat- ‘generation-apil) uses 0 Chromium-based rendering engine that supports Jovascript, CSS, ond HTML AaPITemplate.io rromen y frchg metourees ~ slog signup Loghn Generate PDFs and images from Reusable tempiates co aad with our Powerful API Generate PDF documents, social media Annual Sales Repor Images, banners from reusable templates with no coding! < ‘Seamless integration with Zapler, Make.com, 'NOn, ora simple REST AP! eo Let's see how we can use APITemplateio (http /apitemplateio/) to generate POF. i. Generate Template-based PDF APITemplateio (nttp:/apitemplateio/) allows you to manage your templates. Go to Manage Templates from the dashboard. nitps:/aptemplate ofbloghow-to-conver-himl-to-pdF-using-node-j! 632 3722724, 10:26AM How to convert HTML to PDF using Nodes APITemplate.0 AAPITemplate.io © (aaa » 4 bastooar f, APLntegation Overview [an overview of your account and subscription "= Welcome to APITemplate lo APrTemplate allows you to generate images or POF documents with a simple API ‘The followings are the steps to create an image template or PDF template 1. On the dashboard, click onthe Manage Templates inthe upper tabs 2 On the Manage Templates, click on the New image Template or New POF Template button to ceste a new template 2. Selecta template then click on Create 4. Newt ect the template by launching the Image or POF Editor. 5. You can preview the image/PDF by clicking the Preview button, Cle here for mote learning resources From Manage Template, you can create your own templates. The following is a sample invoice template. There ‘are many templates available that you can choose from and customize based on your requirements. {ke ter ete 2c teat Otel om ie ocO invoice Emisiccesncam ‘To start using APiTemplate.o (http://apitemplatoio/) APIs, you need to obtain your API Key, which can be obtained from the API Integration tab. htlps:fapitemplatelfblogInow-te-convert-htmte-pausing-node-js! 7133 3722724, 10:26AM How to convert HTML to PDF using Nodes APITemplate.0 AaPrTemplat ° Raa ~ ‘6 astoowe CS Manage Templates APL ieyaton ‘AP canbe used for your custom applications or automation tools such as Zaier, Make.com(ntegromat) o table to access ou services. Toleorn move about REST API integration: REST AP! Reference v2 or REST API Refeence v1 seiKey 96 Ena) Log Request Now that you have your APiTemplate account ready, let’s take some action and integrate it with our application. ‘We will use the template to generate PDFs. east andes = neutre( ‘atte: feast client = axos.ereate(d; yy ser wat fone url = "hetpas//restpit 040 /v2erente-pef?enplate {60718 TEMPLATE. ID"; 1 Payioat sate fonst payload = ¢ Cater "5/08/2022", Sener pane: "255-781-8789", fencasanail: *hellobloges on" recepane: *3493-88-229", fece_anail: *husinessepttemlate. to", Hens [ {een pane: “On, unt: 1, untprice: 168, total: 18), (Gtenpane: “Rice, units 2, ania orice: 28, totals 4), {Ltenpane: "Mangoes", unit: 3, arlt price 988, cota: 988), {ternane: “Clothe, unit: anlt_price: 488, tots 3669), : ‘And it we check the response string , we have the following: ‘ ; 34° YOu TPLATE 3 Inthe above code, it's very easy to use ApiTemplate to convert HTML to POF because we don't need to install any other library. We just need to call one simple API and use our data as a request body, and that’s it You can use the download ust from the response to download or distribute the generated PDF. ntps:apitemlatejvblogmnow-to-convert-himi-to-pa-using-node-je 8133 3722124, 10:26 AM How to convert HTML to PDF using Nodes APITemplate.0 ii. Generate PDF from website URL ApiTemplate also supports generating PDFs from website URLs const anton = reqtre(‘anie') async enction wind) ¢ ranean: “estylereacer, vfoter ( pacing: @ Vingortant; In the above code, we can provide the URL in the request body along with the settings for the PDF. APITemplate will use this request body to generate a PDF and return a download URL for your PDF. ili. Generate PDF from custom HTML content It you want to generate PDFs using your own custom HTML content, ApiTemplate also supports that. const acs = reutre antes"; async fanctlon lng) ( feast data = ¢ Rody: “ hello world {(aane) ", feet “catylensba(ncheround: ed) j

You might also like