How to Convert HTML Tables into Beautiful PDFs

Tyler Hawkins
Level Up Coding
Published in
8 min readNov 10, 2020

--

Image courtesy of DocRaptor

Web apps that contain tables, charts, and graphs often include an option to export the data as a PDF. Have you ever wondered, as a user, what’s going on under the hood when you click that button?

And as a developer, how do you get the PDF output to look professional? Most free PDF exporters online essentially just convert the HTML content into a PDF without doing any extra formatting, which can make the data hard to read. What if you could also add things like page headers and footers, page numbers, or repeating table column headers? Small touches like these can go a long way toward turning an amateur-looking document into an elegant one.

Recently, I explored several solutions for generating PDFs and built this demo app to showcase the results. All of the code is also available here on Github. Let’s get started!

Overview of the Demo App

HTML to PDF Demo App
HTML to PDF demo app

Our demo app contains a lengthy styled table and four buttons to export the table as a PDF. The app is built with basic HTML, CSS and vanilla JavaScript, but you could easily create the same output using your UI framework or library of choice.

Each export button generates the PDF using a different approach. Viewing from right to left, the first uses the native browser print functionality. The second uses an open-source library called jsPDF. The third uses another open-source library called pdfmake. And finally, the fourth uses a paid service called DocRaptor.

Let’s dig into each solution one by one.

Native Browser Print Functionality

First off, let’s consider exporting the PDF using the browser’s built-in tools. When viewing any web page, you can easily print the page by right-clicking anywhere and then choosing the Print option from the menu. This opens a dialog for you to choose your print settings. But, you don’t actually have to print the document. The dialog also gives you the option to save the document as a PDF, which is what we’ll do. In JavaScript, the window object exposes a print method, so we can write a simple…

--

--