{"id":4426,"date":"2023-03-02T14:31:16","date_gmt":"2023-03-02T14:31:16","guid":{"rendered":"https:\/\/decentro.tech\/blog\/?p=4426"},"modified":"2024-06-12T12:12:35","modified_gmt":"2024-06-12T12:12:35","slug":"jspdf","status":"publish","type":"post","link":"https:\/\/decentro.tech\/blog\/jspdf\/","title":{"rendered":"JsPDF: What Is It &#038; How To Use It To Generate PDF from HTML"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large featured-post-img\"><img loading=\"lazy\" width=\"854\" height=\"854\" src=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/JsPDF-What-Is-It-How-To-Use-It-To-Generate-PDF-from-HTML.jpg\" alt=\"\" class=\"wp-image-6297\"\/><\/figure>\n\n\n\n<p><strong><em>It&#8217;s a PDF world, and we are just living in it.&nbsp;<\/em><\/strong><\/p>\n\n\n\n<p>The ask for this PDF format is universal.&nbsp;And today, we bring you a breakdown of an effective way to convert an HTML Document to a PDF and download it. <\/p>\n\n\n\n<p>No. No! We aren&#8217;t talking about the <em><strong>Right-click &gt; Save as PDF<\/strong><\/em> option.<\/p>\n\n\n\n<p>This one is much more nuanced.&nbsp;<\/p>\n\n\n\n<p>So let\u2019s dive in!<\/p>\n\n\n\n<p>First things first,<\/p>\n\n\n\n<p>Where did this need to convert an HTML document to a PDF come from?&nbsp;<\/p>\n\n\n\n<p>Most web-based projects or applications need report generation to show relevant data, including PDF conversion. In such cases, generating PDFs with different visibility rules specific to a particular user requires&nbsp;a flexible solution, such as JsPDF.<\/p>\n\n\n\n<p><strong>JSPDF<\/strong> is a JavaScript library that allows you to generate PDF files directly from your web pages. It is a powerful tool for web developers to create and generate PDFs on the fly, making it ideal for businesses, schools, and other organizations that require a way to produce professional and polished PDFs quickly and easily.<\/p>\n\n\n\n<p>Riding on the back of an open-source library and the promise of flexibility,&nbsp; JSPDF allows you to generate PDFs from various sources, including HTML content, images, and even existing PDFs. Being an open-source library, it makes it free to use, modify and accommodate any specific need.<br><br>This makes it an ideal choice for developers who need a flexible and cost-effective solution for generating PDFs from their web applications.<br><br>Today, we will use jsPDF to download an HTML file as a PDF, images, colors &amp; backgrounds.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p><em>PS: Stay tuned for the bonus section towards the end of the blog,<\/em> <em>which touches upon a presumably difficult use case killing two birds with one stone &lt;PDF edition&gt;.<\/em><\/p><\/blockquote>\n\n\n\n<p>Let us show you exactly how.<br><br>First, let\u2019s set up some basic things to serve our images on the template we will build to implement jsPDF. We will be using AWS S3 Buckets for it.<br><strong>Setting up an AWS Bucket&nbsp;<\/strong><\/p>\n\n\n\n<p>This bucket will hold our assets (preferably images) used in our HTML template.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"2770\" height=\"422\" src=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/decentro-public-icons-bucket_blurred.png\" alt=\"\" class=\"wp-image-4457\"\/><\/figure>\n\n\n\n<p>Here we have our images ready to use now.<br><\/p>\n\n\n\n<p><strong>Configuring the Bucket to handle CORS<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"2650\" height=\"1088\" src=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/CORS-setting-image-buckets_blurred.png\" alt=\"\" class=\"wp-image-4458\"\/><\/figure>\n\n\n\n<p>Wait! What just happened there? <\/p>\n\n\n\n<p>Let me explain!<\/p>\n\n\n\n<p>Since we at Decentro use AWS as our superpower, we have created an S3 Bucket and uploaded all the images we will use in our template.<br>Then under bucket permissions, we have dumped some CORS policy rules to allow cross-origin requests to our images in the bucket<\/p>\n\n\n\n<p>Now onto setting up the template<br><br><strong>HTML Template<\/strong><br>We will build a basic HTML template with some sections holding data, background colors, a couple of images &amp; a download button.<br><br>Use the code snippet below to build a basic HTML structure.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/vipulyadav150\/108e3e959510bb475177351b934b2790.js\"><\/script>\n\n\n\n<p><br><br><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"2256\" height=\"1316\" src=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/html-template-blurred.jpg\" alt=\"\" class=\"wp-image-4460\"\/><\/figure>\n\n\n\n<p>Above shown is the output of the template. Now comes the star of the show, jsPDF part<br><strong>First, Set up jsPDF<\/strong><br>To use jsPDF, you need to include the library in your HTML file. You can either download the library and include it locally, or you can include it directly from a CDN.<br><br>Here we will use the CDN to import the library, so let\u2019s first add a couple of libraries at the head part of our template.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/vipulyadav150\/800bedee77861e31b071fd07b3cb1836.js\"><\/script>\n\n\n\n<p><strong>Then, we move on to attaching the onClick to Download Button<\/strong><br>Now, Attach an onClick event with the Download button<br><\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/vipulyadav150\/f5296bfea80d18d4895685f19a416d58.js\"><\/script>\n\n\n\n<p><br>The download button is linked with an onClick event which calls the downloadPDF function.<br><strong>Finally, Download the HTML as a PDF<\/strong><br>We will be creating a new jsPDF object. This can be done by calling the jsPDF constructor.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/vipulyadav150\/75fb90488ce64c4f9d8064e9462b8a46.js\"><\/script>\n\n\n\n<p>The constructor function of the jsPDF class takes an object as a parameter with the following three properties:<\/p>\n\n\n\n<p><strong>Orientation<\/strong> &#8211; Defines the orientation of the PDF document. In this case, it is set to &#8220;portrait&#8221; &#8211; \u2018p\u2019<\/p>\n\n\n\n<p><strong>Unit<\/strong> &#8211; Sets the unit of measurement for the document. It is set to points (&#8220;pt&#8221;) in this case.&nbsp;<\/p>\n\n\n\n<p><strong>Format<\/strong> &#8211; Sets the size of the document. It takes an array with two values: the width and height of the unit specified in the unit property. In this case, we have set it to a standard A4-size document.<br>Now, we will be adding content to the PDF object &amp; try downloading the PDF<br>&lt;Code here will be linked using Github Gist link &#8211; while editing the blog on wordpress&gt;<br><br>The addHTML method of the PDF object is called, passing in the following parameters:&nbsp;<\/p>\n\n\n\n<ol><li>$(&#8220;#mainContainer&#8221;) &#8211; a jQuery object representing the HTML element to be added to the PDF.&nbsp;<\/li><li>0 &#8211; the horizontal position (in millimeters) to place the element. In this case, it is positioned at the leftmost edge of the page.&nbsp;<\/li><li>-20 &#8211; the vertical position (in millimeters) to place the element. In this case, it is shifted by 20 millimeters to accommodate margins or headers.&nbsp;<\/li><li>{ allowTaint: false, useCORS: true, page split: false } &#8211; an optional object containing settings for rendering the HTML element.<br>The <strong>allowTaint<\/strong> property controls whether to allow the browser to taint the canvas when rendering images.<br>The <strong>useCORS<\/strong> property controls whether to use CORS (Cross-Origin Resource Sharing) when rendering images.<br>The <strong>pagesplit<\/strong> property controls whether to split the PDF into multiple pages if the HTML element overflows the current page.&nbsp;<\/li><li>A callback function is executed after adding the HTML to the PDF. In this case, the save method of the PDF object is called to save the PDF file with the name {{downloaded_file_name}}.pdf.<br><\/li><\/ol>\n\n\n\n<p>Then, the &#8220;hidden&#8221; attribute of the HTML button with the ID &#8220;button-pdf&#8221; is removed to display the PDF download button.<br><br><strong>Uploading the HTML file in the bucket<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"2702\" height=\"286\" src=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/bucket-creation_blurred-1.png\" alt=\"\" class=\"wp-image-4465\"\/><\/figure>\n\n\n\n<p>Created an S3 bucket again in AWS &amp; uploaded the template in an object.<br>Copy the Object URL because this is where the template is rendered now.<br>Now as we open the link and <strong>HIT Download<\/strong>\u2026.<br><br><strong>FINAL REVEAL IN 3..2\u2026.1<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"1394\" height=\"1188\" src=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/pdf-blurred.jpg\" alt=\"\" class=\"wp-image-4461\"\/><\/figure>\n\n\n\n<p><br><strong>Picture-perfect PDF is what I like to call it.<\/strong><br><img loading=\"lazy\" width=\"480\" height=\"195\" src=\"https:\/\/lh4.googleusercontent.com\/sZbLYPUiimueXBsjeKy9gIFKXADe-YaX8gzmvI4Ngzm5GoawvnmOAfAyn6WJSHSM_OrYFjthcswxijqB1dfdezLXM_pgNVHkc1LRHWqe90ukZ12Ncsy37JXb1Zi4mnFkTys1fOSf-MFsdVewTzi4yRk\"><br><\/p>\n\n\n\n<h2>Now for the BONUS CONTENT<\/h2>\n\n\n\n<p>Hold on! Hold on! We have got some <strong>BONUS <\/strong>content for you. As mentioned earlier, the idea here is to emulate the killing of two birds with the one-stone analogy. Let us show you how<br>Say I have a screening report link too in the template, which, when clicked, opens in a new tab and holds a screening report PDF.&nbsp;<\/p>\n\n\n\n<p>The idea is to download both these reports simultaneously by clicking the download button once.&nbsp;<\/p>\n\n\n\n<p>Can this be done?&nbsp;<\/p>\n\n\n\n<p>Well, of course, YES!<br>To achieve this, let\u2019s add more &lt;CODE&gt; to the existing one.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/vipulyadav150\/2cf4586447d860fbdec6a0570eb2361b.js\"><\/script>\n\n\n\n<p><br>Now as we can see, If we click the link directly, it opens up in a new tab and displays a PDF file<br><br><strong>Downloading both PDFs simultaneously<\/strong><br>Let\u2019s update our js code to the below code snippet to achieve both reports being downloaded on a single download button click<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/vipulyadav150\/1a574e10ddc8d2e0d79699b8a7c91d9d.js\"><\/script>\n\n\n\n<p><br>The downloadFile function downloads a PDF file from the specified URL using the fetch API and creates an anchor element with the download attribute to save the file.<br>Within the downloadFile function:&nbsp;<\/p>\n\n\n\n<ol><li>fetch(url, { method: &#8216;get&#8217;, mode: &#8216;no-cors&#8217;, referrerPolicy: &#8216;no-referrer&#8217; }) fetches the PDF file from the specified URL using the GET method and the &#8220;no-cors&#8221; mode.&nbsp;<\/li><li>.then(res =&gt; res.blob()) converts the response to a Blob object.&nbsp;<\/li><li>.then(res =&gt; {&#8230;}) creates an anchor element with the download attribute, sets the href attribute to the URL of the Blob object, and simulates a click on the anchor element to download the file.&nbsp;<\/li><li>URL.revokeObjectURL(href) releases the Blob object URL.<br><br>That\u2019s it; we have achieved what we set out to do: generate and download a PDF file using an HTML template.<\/li><\/ol>\n\n\n\n<p><strong>So the ever-pertinent question must be addressed at the end of such deployments.&nbsp;<\/strong><\/p>\n\n\n\n<h3><strong>What\u2019s next?<\/strong><\/h3>\n\n\n\n<p>Since we can see the two PDFs, one being generated from HTML &amp; one downloaded via an URL, are downloaded separately, we are now working towards downloading them in a single ZIP file as a wrapper to be shipped to customers.<\/p>\n\n\n\n<p>More on that later.&nbsp;<\/p>\n\n\n\n<p>Till then, feel free to indulge in the other works of the developers at <a href=\"https:\/\/decentro.tech\/\" target=\"_blank\" rel=\"noreferrer noopener\">Decentro<\/a>, who are incessantly working on getting their subject matter expertise to you via these technical write-ups. Feel free to check out our blogs on multiple topics like <a href=\"https:\/\/decentro.tech\/blog\/why-next-js\/\">NextJS<\/a>, <a href=\"https:\/\/decentro.tech\/blog\/jest-unit-testing-framework\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jest<\/a>, <a href=\"https:\/\/decentro.tech\/blog\/usage-of-metabase-for-making-a-data-driven-product\/?utm_campaign=india-data_tables-november-2022&amp;utm_medium=content&amp;utm_source=blog&amp;utm_term=&amp;utm_content=\">Metabase<\/a>, and <a href=\"https:\/\/decentro.tech\/blog\/engineering-and-apis\/\" target=\"_blank\" rel=\"noreferrer noopener\">more<\/a>.<br><br>That\u2019s all with this blog. Until then, Keep snacking and keep learning!<br>Also, if you wish to connect with us, please drop us a line.<\/p>\n\n\n\n<p><a class=\"decentro-homepage-signup\" href=\"https:\/\/decentro.tech\/signup?\" target=\"_blank\" rel=\"noreferrer noopener\">Let&#8217;s Connect<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here\u2019s an in-depth guide where we break down JsPDF, an open source solution that can help you quickly generate high quality PDFs from HTML.<\/p>\n","protected":false},"author":9,"featured_media":4427,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[23],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v15.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>JsPDF: What Is It &amp; How To Use It To Generate PDF from HTML - Decentro<\/title>\n<meta name=\"description\" content=\"Here\u2019s an in-depth guide where we break down JsPDF, an open source solution that can help you quickly generate high quality PDFs from HTML.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/decentro.tech\/blog\/jspdf\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JsPDF: What Is It &amp; How To Use It To Generate PDF from HTML - Decentro\" \/>\n<meta property=\"og:description\" content=\"Here\u2019s an in-depth guide where we break down JsPDF, an open source solution that can help you quickly generate high quality PDFs from HTML.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/decentro.tech\/blog\/jspdf\/\" \/>\n<meta property=\"og:site_name\" content=\"Decentro\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/decentrotech\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-02T14:31:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-06-12T12:12:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/JsPDF-Tech-Blog.jpeg\" \/>\n\t<meta property=\"og:image:width\" content=\"1700\" \/>\n\t<meta property=\"og:image:height\" content=\"854\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DecentroTech\" \/>\n<meta name=\"twitter:site\" content=\"@DecentroTech\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"8 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/decentro.tech\/blog\/#website\",\"url\":\"https:\/\/decentro.tech\/blog\/\",\"name\":\"Decentro\",\"description\":\"API platform for banking integrations\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/decentro.tech\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/decentro.tech\/blog\/jspdf\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/decentro.tech\/blog\/wp-content\/uploads\/JsPDF-Tech-Blog.jpeg\",\"width\":1700,\"height\":854},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/decentro.tech\/blog\/jspdf\/#webpage\",\"url\":\"https:\/\/decentro.tech\/blog\/jspdf\/\",\"name\":\"JsPDF: What Is It & How To Use It To Generate PDF from HTML - Decentro\",\"isPartOf\":{\"@id\":\"https:\/\/decentro.tech\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/decentro.tech\/blog\/jspdf\/#primaryimage\"},\"datePublished\":\"2023-03-02T14:31:16+00:00\",\"dateModified\":\"2024-06-12T12:12:35+00:00\",\"author\":{\"@id\":\"https:\/\/decentro.tech\/blog\/#\/schema\/person\/1e492471bd12dac8e7d0cd75afc04d12\"},\"description\":\"Here\\u2019s an in-depth guide where we break down JsPDF, an open source solution that can help you quickly generate high quality PDFs from HTML.\",\"breadcrumb\":{\"@id\":\"https:\/\/decentro.tech\/blog\/jspdf\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/decentro.tech\/blog\/jspdf\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/decentro.tech\/blog\/jspdf\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/decentro.tech\/blog\/\",\"url\":\"https:\/\/decentro.tech\/blog\/\",\"name\":\"Blog\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/decentro.tech\/blog\/engineering-and-apis\/\",\"url\":\"https:\/\/decentro.tech\/blog\/engineering-and-apis\/\",\"name\":\"Engineering &amp; APIs\"}},{\"@type\":\"ListItem\",\"position\":3,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/decentro.tech\/blog\/jspdf\/\",\"url\":\"https:\/\/decentro.tech\/blog\/jspdf\/\",\"name\":\"JsPDF: What Is It &#038; How To Use It To Generate PDF from HTML\"}}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/decentro.tech\/blog\/#\/schema\/person\/1e492471bd12dac8e7d0cd75afc04d12\",\"name\":\"Vipul Yadav\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/decentro.tech\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/15ae0833d0dc2d5dee67ec7e21195a32?s=96&d=mm&r=g\",\"caption\":\"Vipul Yadav\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/posts\/4426"}],"collection":[{"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/comments?post=4426"}],"version-history":[{"count":27,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/posts\/4426\/revisions"}],"predecessor-version":[{"id":6595,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/posts\/4426\/revisions\/6595"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/media\/4427"}],"wp:attachment":[{"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/media?parent=4426"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/categories?post=4426"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/decentro.tech\/blog\/wp-json\/wp\/v2\/tags?post=4426"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}