Convert HTML To PDF In Javascript (Simple Examples)

Welcome to a tutorial on how to convert HTML to PDF files in Javascript. Yes, creating PDF files is not limited to the server side.

To generate PDF files from HTML in Javascript:

  • We can use a library called HTML2PDF.
  • Download the library from their GitHub page, or load it from CDNJS.
  • To convert the entire HTML page into a PDF file – html2pdf().from(document.body).save();

That covers the quick basics, but read on for more examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

HTML TO PDF WITH JAVASCRIPT

All right, let us now get into detailed examples of using the HTML2PDF library to turn HTML into a PDF file.

 

1) SAVE THE ENTIRE PAGE AS PDF FILE

1-entire-page.html
<!-- (A) LOAD HTML2PDF -->
<!-- https://cdnjs.com/libraries/html2pdf.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
 
<!-- (B) DUMMY CONTENTS -->
<h1>Hello World!</h1>
<p>This is an example.</p>
 
<!-- (C) ENTIRE PAGE TO PDF -->
<script>
function toPDF () {
  html2pdf()
    .from(document.body)
    .save();
}
</script>
<button onclick="toPDF()">To PDF</button>

As in the introduction, all we need to do is to use the HTML2PDF library – html2pdf().from(document.body).save() will convert the entire page into a PDF file. But take note, the generated PDF file may not be 100% accurate on complex pages.

 

2) CONVERT A SECTION INTO PDF (AND OPTIONS)

2-section.html
<!-- (A) LOAD HTML2PDF -->
<!-- https://cdnjs.com/libraries/html2pdf.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
 
<!-- (B) DUMMY CONTENTS -->
<h1>Hello World!</h1>
<div id="demo">
  <div><img src="music.png"></div>
  <p>Convert this section to PDF only.</p>
</div>
<p>This is an example.</p>
 
<!-- (C) SECTION TO PDF -->
<script>
function toPDF () {
  html2pdf()
    // (C1) SET OPTIONS
    .set({
      margin: 1,
      filename: "demo.pdf",
      image: { type: "jpeg", quality: 0.8 },
      enableLinks : true,
      jsPDF: { format: "A4", orientation: "landscape" }
    })
 
    // (C2) GET CONTENT FROM SECTION & SAVE
    .from(document.getElementById("demo"))
    .save();
}
</script>
<button onclick="toPDF()">To PDF</button>

Not going to go through these step-by-step, but it should be pretty self-explanatory.

  • (C1) Yes, HTML2PDF does accept options. We can set the page format and orientation of PDF, alongside some other settings such as the image quality.
  • (C2) Same old “get content and save to PDF”, except that we are getting from a single <div> instead of the entire <body> now.

 

 

3) HTML STRING TO PDF

3-string.html
<!-- (A) LOAD HTML2PDF -->
<!-- https://cdnjs.com/libraries/html2pdf.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
 
<!-- (B) PDF FROM HTML STRING -->
<script>
function toPDF () {
html2pdf()
  .from(`<h1>Hello World!</h1><p>This is an example.</p>`)
  .save();
}
</script>
 
<!-- (C) GO! -->
<button onclick="toPDF()">To PDF</button>

Lastly, I don’t think this needs further explanation – We can also directly feed an HTML string into the library to generate a PDF file.

 

 

4) FETCH HTML FROM ANOTHER PAGE TO PDF

4-fetch.html
<!-- (A) LOAD HTML2PDF -->
<!-- https://cdnjs.com/libraries/html2pdf.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
 
<!-- (B) FETCH PAGE TO PDF -->
<script>
function toPDF () {
  fetch("1-entire-page.html")
  .then(res => res.text())
  .then(html => {
    html2pdf()
      .from(html)
      .save();
  })
  .catch(err => console.error(err));
}
</script>
<button onclick="toPDF()">Fetch Page To PDF</button>

Yes, we can use fetch() to get the HTML from another page, then pass it into html2pdf().

P.S. By default. you can only use fetch() to get HTML pages on your own server. If you want to get a page from another server, that is called “cross origins” and an entirely different topic. I will leave a link to another tutorial below.

 

EXTRAS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

MANUAL CONVERSION TO PDF

Lastly, this is an alternative for you guys who may only need to convert a few pages – Just print and select “Save as PDF” as the destination. Yep, some modern browsers already have this converter built-in.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *