One of my static web pages needed a new feature that is to export the web page as a PDF file, it is good to do this function in pure JavaScript. Here are a few ways I tried.
Let me show the conclusion first: the first one is what I ended up using; the second one is the simplest one, but there’s one step that requires users to switch a edit box to [Save as PDF], which may cause confusion and not easy to use; the third one should be the most effective one for keeping the complex style of web pages, but it converts the pages as images which lead to the loss of PDF editable features.
printjs
1 | <body id="main-body"> |
In order to keep the original page style for the exported PDF:
css
: Place all the style sheets used on the page in the parameterstyle
: Place custom style (inline CSS and internal CSS) in the parameter
window.print()
https://www.w3schools.com/jsref/met_win_print.asp
It will open the Print dialog, users have to change the destination printer to “Save as PDF” and hit the “Print” button and the webpage, actually which means the content in <body>
of the webpage, will download as a PDF document.
1 | <input type="button" value="Print this page" onClick="window.print()"> |
The exported PDF has no typle by default, but several ways can help:
- Import style sheet, and add media=”print”
Configure a style sheet for printing, such asprint.css
, add it to HTML, meanwhile addmedia="print"
in<link>
which can tell the printer to use this style when printing.1
<link href="/path/print.css" media="print" rel="stylesheet" />
- When we don’t have many styles to change, there is no need to rewrite a new style sheet at all, a media query can achieve the same effect
1
2
3
4
5
6@media print {
h1 {
font-size: 20px;
color: red;
}
}
jsPDF
https://github.com/MrRio/jsPDF
It converts the page as a canvas image, then exports the images to a PDF file, so it keeps the styles on the page well, but just because of this, you will not be able to copy or edit the content in the PDF as compared to the previous two methods.
Personally, I don’t like it.
In addition, the following is a secondary development based on jsPDF, which is slightly easier to use:
https://github.com/eKoopmans/html2pdf.js