Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Generate PDF from HTML with JavaScript and Example

#1
Generate PDF from HTML with JavaScript and Example

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/05/generate-pdf-from-html-with-javascript-and-example.jpg" width="550" height="556" title="" alt="" /></div><div><div class="modified-on" readability="7.047619047619"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on May 12th, 2022.</div>
<p>Generate PDF from HTML in a browser is one of the most wanted utilities. There are many hosted solutions generating PDF online from the posted source.</p>
<p>When using online tools the required features are not available with one tool. The users have to compromise some of their needs when depending on the online tools.</p>
<p>But, developers like us need not compromise. We can create a custom utility to generate PDF from HTML on our own.</p>
<div class="post-section-highlight" readability="47.385221674877">
<h2>Quick solution</h2>
<p>There is a quick solution to generate PDF from an HTML page. The browser’s print wizard has the “Save as PDF” option along with the <a href="https://phppot.com/php/extract-content-using-php-and-preview-like-facebook/">preview panel</a>.</p>
<p>This JavaScript triggers the browser’s print action. Then, it supplies a particular portion of the HTM to print.</p>
<pre class="prettyprint"><code class="language-php">
&lt;div class="outer-content"&gt; &lt;div id="pdf-content"&gt; &lt;h2&gt;PDF Page Title&lt;/h2&gt; &lt;hr&gt; &lt;p&gt; How to generate a pdf from the &lt;i&gt;UI content&lt;/i&gt; is easy. &lt;/p&gt; &lt;p&gt; This describes how to &lt;strong&gt;generate pdf from HTML&lt;/strong&gt; using programming. &lt;/p&gt; &lt;/div&gt; &lt;hr&gt; &lt;button id="btn-generate"&gt;Generate PDF&lt;/button&gt;
&lt;/div&gt;
</code></pre>
<pre class="prettyprint"><code class="language-php">
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;body&gt; &lt;?php require_once __DIR__ . '/template.html'; ?&gt;
&lt;/body&gt;
&lt;script&gt; var buttonElement = document.querySelector("#btn-generate"); buttonElement.addEventListener('click', function() { var pdfContent = document.getElementById("pdf-content").innerHTML; var windowObject = window.open(); windowObject.document.write(pdfContent); windowObject.print(); windowObject.close(); });
&lt;/script&gt;
&lt;/html&gt;
</code></pre>
</div>
<p>I am sure this is not enough to claim that the PDF generation is implemented ?</p>
<p>For creating a full-fledged solution to generate PDF from HTML we have to go for using libraries.</p>
<p>There are popular libraries available in the market to build a PDF generation tool for an application.</p>
<p>In this tutorial, we will see some of the top libraries that support PDF generation. For each library, we will see how-to steps for the integration and development.</p>
<h2>Libraries available to Generate PDF from HTML</h2>
<p>This section listed the libraries used to generate PDF from HTML in this article. It interlinks the appropriate example code below to land you in the right place.</p>
<ol>
<li><a href="https://phppot.com/php/generate-pdf-from-html/#html-to-pdf">HTML to PDF</a></li>
<li><a href="https://phppot.com/php/generate-pdf-from-html/#jspdf">jsPDF</a></li>
<li><a href="https://phppot.com/php/generate-pdf-from-html/#wk-html-to-pdf">wkHTMLtoPDF</a></li>
<li><a href="https://phppot.com/php/generate-pdf-from-html/#pdf-make">pdfmake</a></li>
</ol>
<p>The HTML to pdf and jspdf sections have more than one example. It is to know how to generate PDF from HTML containing <a href="https://phppot.com/jquery/jquery-autocomplete-with-xml-data-source/">complex nodes or containers</a>. Example: HTML tables, image galleries and etc.</p>
<h2 id="html-to-pdf">1. HTML to PDF</h2>
<p>The HTML to pdf library method is a way to generate PDF from HTML. It is a two-step process to get a simple PDF output.</p>
<p>First, get the CDN URL of this library from an authentic source.&nbsp; Then, follow these two steps to get an output PDF file.</p>
<ol>
<li>Instantiate html to pdf library class.</li>
<li>Map HTML content to generate and save PDF.</li>
</ol>
<p>The basic life cycle to generate PDF from HTML using this library is shown in the below flow chart.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-16887" src="https://phppot.com/wp-content/uploads/2022/05/generate-pdf-from-html-life-cycle-550x556.jpg" alt="generate pdf from html life cycle" width="550" height="556" srcset="https://phppot.com/wp-content/uploads/2022/05/generate-pdf-from-html-life-cycle-550x556.jpg 550w, https://phppot.com/wp-content/uploads/20...97x300.jpg 297w, https://phppot.com/wp-content/uploads/20...-cycle.jpg 695w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h3>Example 1: Generate PDF from HTML containing only text.</h3>
<pre class="prettyprint"><code class="language-php">
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;title&gt;Generate PDF from HTML using html to pdf library&lt;/title&gt;
&lt;!-- CDN URL - html2pdf library --&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"&gt;&lt;/script&gt;
&lt;/head&gt; &lt;body&gt; &lt;?php require_once __DIR__ . '/template.html'; ?&gt; &lt;script&gt; var buttonElement = document.querySelector("#btn-generate"); buttonElement.addEventListener('click', function() { var pdfContent = document.querySelector("#pdf-content"); html2pdf().from(pdfContent).save(); }); &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3>Example 2: Supply library options to override defaults</h3>
<p>Unlike the above example, it sends an array of options to generate PDF from HTML. It overrides the default file name, <a href="https://phppot.com/css/image-editor-move-scale-skew-rotate-and-spin-with-css-transform/">margin, orientation and more defaults</a> as specified.</p>
<pre class="prettyprint"><code class="language-php">
var pdfContent = document.querySelector("#pdf-content");
var optionArray = { margin: 10, filename: 'output.pdf', jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
}; // html to pdf generation with the reference of PDF worker object
html2pdf().set(optionArray).from(pdfContent).save(); </code></pre>
<p>In old monolithic method, the html2pdf() accepts the HTML reference and options. To generate PDF from HTML DOM object reference and <a href="https://phppot.com/php/php-json-encode-and-decode/">JSON options</a> are supplied like,</p>
<pre class="prettyprint"><code class="language-php">
html2pdf(pdfContent, optionArray);
</code></pre>
<h2 id="jspdf">2. jsPDF</h2>
<p>To generate PDF from HTML some libraries need document definition of the markup. The jsPDF is popularly known for its feature of getting the HTML input in any format.</p>
<p>For example, it is capable of accepting HTML in the following formats.</p>
<ol>
<li>HTML markup.</li>
<li>HTML file input data.</li>
<li>HTML element object with the reference of selectors.</li>
</ol>
<h3>Example 1: Equivalent alternative solution to generate PDF from HTML</h3>
<p>This example creates a basic usage reference of jsPDF to generate PDF from HTML template.&nbsp; It includes an external template source in the UI container.</p>
<p>The JavaScript maps an event handler to the “Generate PDF” button found in the HTML template.</p>
<p>On clicking the button, the script initiates jsPDF with the appropriate PDF specification. It uses .html() handling of the jsPDF library tp generate PDF from HTML object supplied as an argument.</p>
<p>This hander defines a callback function that executes the HTML to PDF conversion. It saves or opens the generated PDF document in the callback.</p>
<pre class="prettyprint"><code class="language-php">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;jsPDF Example&lt;/title&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt; &lt;?php require_once __DIR__ . '/template.html'; ?&gt; &lt;script&gt; var buttonElement = document.querySelector("#btn-generate"); buttonElement.addEventListener('click', function() { const { jsPDF } = window.jspdf; var doc = new jsPDF("p", "pt", 'a4'); var pdfContent = document.querySelector("#pdf-content"); // Generate PDF from HTML using right id-selector doc.html(pdfContent, { callback: function(doc) { doc.save("download.pdf"); }, x: 10, y: 19 }); }); &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3>Example 2: Generate multipage PDF from HTML page</h3>
<p>The jsPDF library is one of the best libraries used to generate PDF from HTML on the client-side. We have seen more examples in previous articles.</p>
<p>This example is for generating a <a href="https://phppot.com/php/create-zip-file-of-multiple-uploaded-files-using-php/">multipage document</a> from lengthy HTML to PDF format.</p>
<p>It uses the jsPDF’s page handlers like <em>addPage</em>, <em>setPage</em>, <em>insertPage</em> and more.</p>
<p>It calculates the PDF page content height and width and<a href="https://phppot.com/php/php-explode/"> split the HTML source</a> content. It creates chunks of page content from the HTML markup.</p>
<p>It calculates the <a href="https://phppot.com/bootstrap/bootstrap-pagination/">total pages to paginate</a> split chunks of HTML to PDF multi-page document. The <em>addPage()</em>&nbsp;generates a page instance to render the page content chunk into it.</p>
<p>It <a href="https://phppot.com/javascript/for-each-javascript/">loops through the same process</a> to generate PDF from HTML containing long content.</p>
<pre class="prettyprint"><code class="language-php">
&lt;!doctype html&gt;
&lt;HTML&gt;
&lt;HEAD&gt;
&lt;TITLE&gt;Generate multi-page PDF from HTML - jsPDF&lt;/TITLE&gt;
&lt;script src="https://code.jquery.com/jquery-2.1.3.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"&gt;&lt;/script&gt;
&lt;style&gt;
.description { font-size: 2em; line-height: 4;
}
&lt;/style&gt;
&lt;/HEAD&gt;
&lt;BODY&gt; &lt;div class="outer-content"&gt; &lt;div id="pdf-content"&gt; &lt;img src="cherry.jpeg" /&gt; &lt;p class="description"&gt;Donec id leo quis felis vehicula bibendum sit amet ut tellus. Sed sagittis aliquet rhoncus. Pellentesque vulputate nunc ultricies, egestas augue ac, ullamcorper dui. Etiam diam mauris, molestie in purus a, venenatis pretium leo. Sed id metus eleifend, scelerisque neque id, posuere arcu. Nunc cursus et dui quis fringilla. In in turpis feugiat diam porttitor tempus. In hendrerit diam dolor, id pellentesque ante volutpat a. Nam tortor sapien, semper ut justo et, accumsan imperdiet sem. Sed euismod nunc vitae dolor porttitor ullamcorper. Donec sed lacinia dui. Nunc sed suscipit erat. Phasellus euismod ultrices velit, hendrerit tempor diam elementum ut.&lt;/p&gt; &lt;hr&gt; &lt;/div&gt; &lt;button id="btn-generate"&gt;Generate PDF&lt;/button&gt; &lt;/div&gt; &lt;/BODY&gt;
&lt;script&gt;
$(document).ready(function(){ $("#btn-generate").click(function(){ var htmlWidth = $("#pdf-content").width(); var htmlHeight = $("#pdf-content").height(); var pdfWidth = htmlWidth + (15 * 2); var pdfHeight = (pdfWidth * 1.5) + (15 * 2); var doc = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]); var pageCount = Math.ceil(htmlHeight / pdfHeight) - 1; html2canvas($("#pdf-content")[0], { allowTaint: true }).then(function(canvas) { canvas.getContext('2d'); var image = canvas.toDataURL("image/png", 1.0); doc.addImage(image, 'PNG', 15, 15, htmlWidth, htmlHeight); for (var i = 1; i &lt;= pageCount; i++) { doc.addPage(pdfWidth, pdfHeight); doc.addImage(image, 'PNG', 15, -(pdfHeight * i)+15, htmlWidth, htmlHeight); } doc.save("output.pdf"); }); });
});
&lt;/script&gt;
&lt;/HTML&gt;
</code></pre>
<p><img loading="lazy" class="alignnone size-large wp-image-16883" src="https://phppot.com/wp-content/uploads/2022/05/generate-pdf-from-html-output-550x476.jpg" alt="generate pdf from html output" width="550" height="476" srcset="https://phppot.com/wp-content/uploads/2022/05/generate-pdf-from-html-output-550x476.jpg 550w, https://phppot.com/wp-content/uploads/20...00x260.jpg 300w, https://phppot.com/wp-content/uploads/20...68x665.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2 id="wk-html-to-pdf">3. wkHTMLtoPDF</h2>
<p>It is a command-line tool to generate PDFs from HTML. <a href="https://github.com/wkhtmltopdf/packaging/releases" target="_blank" rel="noopener">Find the latest suitable release</a>. Then, install this library before running the command in the terminal.</p>
<p>It requires supplying a <span><strong>sanitized HTML source</strong></span> to create a PDF output.</p>
<p>After installation, add the library path to the system classpath. Then, run the following command.</p>
<pre class="prettyprint"><code class="language-php">
wkhtmltopdf sanitised_html_source_path output.pdf
</code></pre>
<p>The best practice is to read the remote page content and sanitize the HTML. Then write the sanitized content into a local HTML to pass it to the PDF generation command. The <a href="https://phppot.com/php/php-curl-post/">PHP cURL post</a> will be best to read the remote content compared to the file_get_contents().</p>
<p>It provides a C library to get used to it via programming.</p>
<p>If you want to execute the command via a program, the PHP exec() function may help.</p>
<p>There is a third-party interface to generate PDF from HTML using the wkHTMLtoPDF. Visit the <a href="https://github.com/mikehaertl/phpwkhtmltopdf" target="_blank" rel="noopener">Github page</a> to install the PHP library used to content HTML to PDF.</p>
<p>This code shows the command to install this library into your vendor directory.</p>
<pre class="prettyprint"><code class="language-php">
composer require mikehaertl/phpwkhtmltopdf
</code></pre>
<p>This simple usage example may initiate to start with this PHP library to generate PDF from HTML.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
use mikehaertl\wkhtmlto\Pdf; $pdf = new Pdf('html-source-file.html'); if (!$pdf-&gt;saveAs('output.pdf')) { $error = $pdf-&gt;getError(); // return error to the request handler
}
</code></pre>
<h2 id="pdf-make">4. pdfmake</h2>
<p>The <em>pdfmake</em> library has both client-side and <a href="https://phppot.com/php/datatables-server-side-processing-using-php-with-mysql/">server-side integrations</a>. Both methods generate PDF from HTML by accessing the element content from JavaScript.</p>
<h3>Installation</h3>
<p>This example uses pdfmake CDN URL to import dependencies. The documentation has alternate methods of installing and integrating the library.</p>
<p>For example, it gives&nbsp;<em>npm</em> commands to download node_modules with required dependencies.</p>
<h3>Client-side integration</h3>
<p>This example uses the pdfmake’s client-side method to generate PDF from HTML objects.</p>
<p>It accesses HTML element content from JavaScript and prepares the document definition object.</p>
<p>The document definition can supply the following types of content.</p>
<ol>
<li>Text,</li>
<li><a href="https://phppot.com/php/responsive-two-column-html-contact-form-with-php-mailing-support/">Multi-column</a> text,</li>
<li>Styles,</li>
<li>Images</li>
</ol>
<p>The HTML contains a heading, text, and image content. The docDefinition object is built with the content of these HTML elements.</p>
<p>Images will be supplied as encoded binary data. In this example, the JavaScript <code class="language-php">getDataUrl()</code> <a href="https://phppot.com/php/php-compress-image/">converts the image</a> into a binary data URL.</p>
<p>Then the pdfmake.createPDF() handler code generate PDF from HTML. The below code opens the HTML to PDF output in the browser screen. The pdfmake library also allows to print, and download the PDF document.</p>
<pre class="prettyprint"><code class="language-php">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;PDFMake Example&lt;/title&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/pdfmake.min.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/vfs_fonts.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt; &lt;div class="outer-content"&gt; &lt;h2 id="heading"&gt;PDF Page Title&lt;/h2&gt; &lt;div id="pdf-content"&gt;How to generate a pdf from the UI content description and example. &lt;/div&gt; &lt;img src="cherry.jpeg" id="image-preview" /&gt; &lt;hr&gt; &lt;button id="btn-generate"&gt;Generate PDF&lt;/button&gt; &lt;/div&gt; &lt;script&gt; var buttonElement = document.querySelector("#btn-generate"); buttonElement.addEventListener('click', function() { var pdfHeading = document.querySelector("#heading").innerText; var pdfContent = document.querySelector("#pdf-content").innerText; var pdfImage = getDataUrl(document.querySelector("#image-preview")); var docDefinition = { content: [ { text: pdfHeading, style: 'heading' }, { text: pdfContent, style: 'vspace' }, { image: pdfImage } ], styles: { vspace: { lineHeight: 3 }, heading: { fontSize: 18, lineHeight: 2 } } }; pdfMake.createPdf(docDefinition).open(); }); function getDataUrl(imgSource) { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = imgSource.width; canvas.height = imgSource.height; context.drawImage(imgSource, 0, 0); return canvas.toDataURL('image/jpeg'); } &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt; </code></pre>
<h2>Conclusion</h2>
<p>Thus, we have seen various methods to generate PDF from HTML source code or files. I hope the usage examples of the libraries may give choices to enable PDF generation.</p>
<p>Share your thoughts about the PDF generation concept we have seen. Also, share your comments on the example codes to generate PDF from HTML.</p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/generate-pdf-from-html/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/05/...d-example/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016