Generate PDF from HTML using html to pdf library

Generate PDF from HTML with JavaScript and Example

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.

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.

But, developers like us need not compromise. We can create a custom utility to generate PDF from HTML on our own.

Quick solution

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 preview panel.

This JavaScript triggers the browser’s print action. Then, it supplies a particular portion of the HTM to print.

 

PDF Page Title


How to generate a pdf from the UI content is easy.

This describes how to generate pdf from HTML using programming.


       

I am sure this is not enough to claim that the PDF generation is implemented 🙂

For creating a full-fledged solution to generate PDF from HTML we have to go for using libraries.

There are popular libraries available in the market to build a PDF generation tool for an application.

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.

Libraries available to Generate PDF from HTML

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.

The HTML to pdf and jspdf sections have more than one example. It is to know how to generate PDF from HTML containing complex nodes or containers. Example: HTML tables, image galleries and etc.

1. HTML to PDF

The HTML to pdf library method is a way to generate PDF from HTML. It is a two-step process to get a standard PDF output.

First, get the CDN URL of this library from an authentic source. Then, follow these two steps to get an output PDF file.

The basic life cycle to generate PDF from HTML using this library is shown in the below flow chart.

generate pdf from html life cycle

Example 1: Generate PDF from HTML containing only text.

           

Example 2: Supply library options to override defaults

Unlike the above example, it sends an array of options to generate PDF from HTML. It overrides the default file name, margin, orientation and more defaults as specified.

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(); 

In old monolithic method, the html2pdf() accepts the HTML reference and options. To generate PDF from HTML DOM object reference and JSON options are supplied like,

html2pdf(pdfContent, optionArray); 

2. jsPDF

To generate PDF from HTML some libraries need a document definition of the markup. The jsPDF is popularly known for its feature of getting the HTML input in any format.

Читайте также:  Создать класс точек java

For example, it is capable of accepting HTML in the following formats.

  1. HTML markup.
  2. HTML file input data.
  3. HTML element object with the reference of selectors.

Example 1: Equivalent alternative solution to generate PDF from HTML

This example creates a basic usage reference of jsPDF to generate PDF from HTML template. It includes an external template source in the UI container.

The JavaScript maps an event handler to the “Generate PDF” button found in the HTML template.

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.

This hander defines a callback function that executes the HTML to PDF conversion. It saves or opens the generated PDF document in the callback.

This script uses the jsPDF CDN URL. If you want to download this jsPDF, the official documentation contains the npm command to install this library.

             

Example 2: Generate multipage PDF from HTML page

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.

This example is for generating a multipage document from lengthy HTML to PDF format.

It uses the jsPDF’s page handlers like addPage, setPage, insertPage and more.

It calculates the PDF page content height and width and split the HTML source content. It creates chunks of page content from the HTML markup.

It calculates the total pages to paginate split chunks of HTML to PDF multi-page document. The addPage() generates a page instance to render the page content chunk into it.

It loops through the same process to generate PDF from HTML containing long content.

   Generate multi-page PDF from HTML - jsPDF    .description  

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.

generate pdf from html output

3. wkHTMLtoPDF

It is a command-line tool to generate PDFs from HTML. Find the latest suitable release. Then, install this library before running the command in the terminal.

It requires supplying a sanitized HTML source to create a PDF output.

After installation, add the library path to the system classpath. Then, run the following command.

wkhtmltopdf sanitised_html_source_path output.pdf 

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 PHP cURL post will be best to read the remote content compared to the file_get_contents().

It provides a C library to get used to it via programming.

If you want to execute the command via a program, the PHP exec() function may help.

There is a third-party interface to generate PDF from HTML using the wkHTMLtoPDF. Visit the Github page to install the PHP library used to content HTML to PDF.

This code shows the command to install this library into your vendor directory.

composer require mikehaertl/phpwkhtmltopdf 

This simple usage example may initiate to start with this PHP library to generate PDF from HTML.

saveAs('output.pdf')) < $error = $pdf->getError(); // return error to the request handler > 

4. pdfmake

The pdfmake library has both client-side and server-side integrations. Both methods generate PDF from HTML by accessing the element content from JavaScript.

Installation

This example uses pdfmake CDN URL to import dependencies. The documentation has alternate methods of installing and integrating the library.

For example, it gives npm commands to download node_modules with required dependencies.

Client-side integration

This example uses the pdfmake’s client-side method to generate PDF from HTML objects.

It accesses HTML element content from JavaScript and prepares the document definition object.

The document definition can supply the following types of content.

The HTML contains a heading, text, and image content. The docDefinition object is built with the content of these HTML elements.

Images will be supplied as encoded binary data. In this example, the JavaScript getDataUrl() converts the image into a binary data URL.

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.

        

PDF Page Title

How to generate a pdf from the UI content description and example.

Conclusion

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.

Share your thoughts about the PDF generation concept we have seen. Also, share your comments on the example codes to generate PDF from HTML.

Comments to “Generate PDF from HTML with JavaScript and Example”

As always a great tutorial!
Thank you very much. There are probably many more, but I think FPDF is also worth diving into. Best regards,
Cor van Dooren
The Netherlands

Hi Dooren, Yes, you are right in a way. I have already written about FPDF. I am continuing to use FPDF in my projects and freelance services work. It is a great tool. It is good for server-side PHP-based PDF generation. For PDF generation, I am using FPDF for the server-side and JSPDF for the client-side predominantly. Thank you.

Источник

HTML to PDF Conversion

HTML format is the backbone of the world wide web. An HTML file contains blocks of code that render a web page within a browser. From the simplest static pages to the most complicated web apps, HTML plays a part in nearly everything online.

A PDF, however, is a file format used for sharing digital documents. A PDF document usually contains text, images, and hyperlinks. PDFs can also be viewed in web browsers, but they are not interactive like web pages and are much more limited in scope.

Generally, an HTML file will be the blueprint of a web page while a PDF will be a snapshot of a document.

Why would you want to convert HTML to PDF?

Most HTML files don’t do much on their own. They will have code that references other files, whether they be images, style sheets, or even other files with different coding languages. If you shared an HTML file with someone but didn’t include these other elements, the recipient would be missing out on a huge chunk of the visual experience.

If you convert an HTML file into a PDF, however, the recipient would be able to see a facsimile of a web page. This could be incredibly useful for a web designer who is showing off an idea to a client. A PDF would show the client what the designer has in mind for the web page without requiring the client to go through the complication of opening a raw HTML file.

How to convert HTML to PDF for free?

Our tool here can convert an HTML file into a PDF. You can upload a simple HTML file or a ZIP file containing the HTML code along with its corresponding images and style sheets.

The first thing you need to do is decide how you’ll want your HTML rendered. There are four options on the page: Grayscale, Landscape, No Background, and No JavaScript. Ticking the Grayscale box will render your page without color; Landscape creates PDF pages in landscape mode rather than portrait; No Background will render the page with a simple white background; No JavaScript will remove all JavaScript from the page.

Note that you need to make these selections before uploading your HTML or ZIP files. If you don’t tick the necessary boxes before uploading, the boxes won’t have any effect on the outputted content.

Once you’ve selected the necessary checkboxes, upload your files by hitting the “UPLOAD FILES” button or dragging and dropping them onto the “Drop Your Files Here” field. Our tool will then automatically render the HTML and convert it into a multi-page PDF.

After the conversion has finished, you can download the new PDF by hitting the “DOWNLOAD” button under each image. However, you can also wait until all the conversions are finished and then hit “DOWNLOAD ALL”. This will download all the PDFs inside one ZIP archive.

You can at once upload up to 20 HTML files, ZIP archives, or a combination thereof. If you need to convert more than 20 files, you can hit “CLEAR QUEUE” after the conversion and repeat the process as many times as needed.

Is it safe to convert HTML to PDF?

It is totally safe to perform these conversions using our tool. Our system will automatically delete all uploads and conversions after one hour in order to secure your sensitive data.

All uploaded data is deleted after 1 hour.

Источник

Оцените статью