For those of you who are front-end developers, there is a need to save the entire content of the web page you are responsible for developing, including text and images, into a PDF file. If a screenshot is taken, the default Windows screenshot button cannot capture more than one screen.

I have been searching the Internet for some time and have collected some solutions, which I would like to share with programmers.

The solution consists of two steps to convert the front page to PDF:

1. Traverse the DOM structure of the current web page, collect the element information and corresponding styles of each node in the DOM tree, and render the Canvas image. The traversal and rendering operations are wrapped in the script file html2Canvas.js.

2. Use an open source JavaScript library, jsPDF, to generate PDF files with JavaScript on the browser side. The PDF generation logic is encapsulated in the script file jspdf.debug.js.

Take a look at how to use these two JavaScript files in your front-end web page.

Here is the page:

If YOU put a long, long file here, you can see that the resulting PDF is automatically paginated…

Draw a button on your front page that triggers the event to save the current page as a PDF file.

Save the entire page as a PDF

The HTML to PDF code is as follows:

If you want to download code text that you can copy and paste, you can download it from this link. Github.com/linwalker/r…

Here’s a look at the effect of this solution.

Click this button:

This is what a PDF file generated in JavaScript looks like when opened locally:

You can see that there are no problems with turning pages in the PDF.

You if you want to own experience through JavaScript to the effect of HTML to PDF, try my demo: i042416. Making. IO/FioriODataT…

The solution was originally designed by a programmer named Linwalker, whose Github link is shown below:

Github.com/linwalker/r…

For more of Jerry’s original technical articles, please follow the public account “Wang Zixi” or scan the following QR code: