Jspdf html to pdf with css

I am using jspdf.debug.js to export different data from a website but there are a few problems, I can't get it to render the CSS in the exported PDF and if I have an image in the page I am exporting, the PDF returns blank...

Does anyone know a way to fix this ?

Here is a jsfiddle showing it's not rendering the CSS

And my script

$[document].ready[function[] {
$['#export'].click[function[]{
var d = new Date[].toISOString[].slice[0, 19].replace[/-/g, ""],
        filename = 'financiar_' + d + '.pdf',
        pdf = new jsPDF['p', 'pt', 'letter'],
        specialElementHandlers = {
          '#editor': function[ element, renderer ] {
              return true;
          }
    };
    pdf.fromHTML[
          $['.export'].get[0] // HTML element
        , 25  // x coord
        , 25  // y coord
        , {
              'width': 550 // was 7.5, max width of content on PDF
            , elementHandlers: specialElementHandlers
        }
    ];
    pdf.save[ filename ];
}]
}];

by Vincy. Last modified on August 22nd, 2022.

HTML to PDF in JavaScript is easier than a server-side implementation to PDF creation.

PDF creation is one of the most important features in building websites. Generate a PDF from HTML format will be useful in many places while building a website for generating reports.

These are some of the PDF creator tools I built for my clients while providing freelance services.

  1. Client assessment tool – Medication plan report
  2. Sales assessment tool – API via Amazon sales report
  3. Material management tool – Stock report

These tools convert HTML templates or database-backed dynamic data into a PDF and provide a download.

When adding a feature to perform HTML to PDF conversion, it should be flexible to get the source in any form. The different forms of HTML sources for the PDF creation process can be,

  1. HTML string
  2. HTML object with selector reference
  3. HTML files

The jsPDF JavaScript library supports different forms of input to create a PDF. For example, it uses “dompurify” dependency to implement HTML to PDF conversion.

The jsPDF is the best JavaScript library to create PDFs on the client-side.  We have seen the jsPDF example already for converting HTML sources into PDF. This article will create an example to get a HTML file to create PDF in JavaScript.

Existing tools to create PDF

There are some popular tools that exist online to process HTML to PDF conversion. You may find the best PDF readers and converters in the linked article.

Dompdf is a HTML to PDF converter library that converts HTML files to PDF. It also accepts the manually entered HTML markup. Download Dompdf from Github to install it into an application.

About this jsPDF example

This example is for simply converting HTML to PDF in JavaScript with few lines of code.

It uses the jsPDF library to build a custom PDF generator tool on the client-side.

We have already seen some jsPDF examples of converting HTML to PDF.  If you want an example of creating a multi-page PDF from a long HTML document.

This example allows users to browse the input HTML file. The landing page shows a form UI with a file input field to choose the source HTML file.

It includes 2 steps to achieve the HTML to PDF generation in JavaScript.

  1. Step1: Read HTML data and show preview in the UI.
  2. Step2: Generate PDF and give the option to download the output file.

It handles JavaScript validation and file type restrictions before starting PDF generation. It contains JavaScript to import and instantiate jsPDF. It uses htmltocanvas dependency to convert uploaded HTML file content into PDF.

HTML to PDF example files

The below image shows the file structure of this HTML to PDF generation example.

It contains a sample HTML template in the Template directory. You may use the template for testing this example script.

The index.php file has the HTML form UI to browse the “.html” file resource.

It processes the two-step PDF creation with the convert.js file. It reads the HTML file and sends the content to the jsPDF-dependent library function. It uses HTML content to create the output PDF.

Organizers' Team if you need any support.

I have used simple CSS for designing the source template. It helps to form an event registration receipt in HTML.

assets/css/style.css

#container {
    -webkit-font-smoothing: antialiased;
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    font-size: .9em;
    color: #1e2a28;
    width: 740px;
    margin: 0 auto;
    padding: 12px 12px 0px 36px;
}

.input-form {
    background: #ffffff;
    padding: 10px 25px;
    border-radius: 3px;
    text-align: left;
    border: #ccc 1px solid;
}

.row {
    margin: 18px 0;
}

.input-file {
    border-radius: 3px;
    border: #a6a6a6 1px solid;
    padding: 10px;
    margin-bottom: 10px;
}

.btn-preview {
    padding: 10px 30px;
    border-radius: 3px;
    display: inline-block;
    cursor: pointer;
    color: #211c1c;
    background-color: #36de5c;
    border: #27a544 1px solid;
}

.btn-generate {
    padding: 10px 30px;
    border-radius: 3px;
    display: inline-block;
    cursor: pointer;
    color: #211c1c;
    background-color: #36de5c;
    border: #27a544 1px solid;
    display: none;
}

.preview {
    display: none;
    padding: 20px;
    border-radius: 3px;
    box-shadow: 0 1px 6px rgb[32 33 36/ 28%];
    border-color: rgba[223, 225, 229, 0];
}

.heading {
    text-align: center;
}

.form-label {
    display: block;
    margin-bottom: 5px;
}

.error {
    color: #ee0000;
    margin-left: 10px;
}

jsPDF function to create PDF in JavaScript

In JavaScript, the PDF conversion is implemented in two steps. First, it reads the file content and shows the preview in the UI. Then, it gets the preview content and creates PDF in JavaScript.

The convert.js file do this using two functions readHTML[] and convertHTMLToPDF[].

The readHTML[] gets the uploaded file temp path and reads the content using FileReader[]. It loads the preview into the specified target. This step helps users assure of the content before calling the JavaScript PDF conversion.

The convertHTMLFileToPDF[] imports the jsPDF library and instatiate it. It calls the .html[] that depends on htmltocanvas. It converts the preview page HTML to PDF format from it.

Then finally, the .save[] method in the callback prompts to download the created PDF document.

assets/js/convert.js

function readHTML[] {
	// get the HTML source file path
	var path = document.getElementById["fileUpload"].files[0];
	var contents;
	$["#error-message"].html[""];
	$["#fileUpload"].css["border", "#a6a6a6 1px solid"];
	if [$[path].length != 0] {
		var r = new FileReader[];
		r.onload = function[e] {
			// read HTML file content
			contents = e.target.result;
			// show JavaScript PDF preview
			$[".preview"].show[];
			$["#temp-target"].html[contents];
			
			$[".btn-preview"].hide[];
			$[".btn-generate"].show[];
		}
		r.readAsText[path];
	} else {
		$["#error-message"].html["required."].show[];
		$["#fileUpload"].css["border", "#d96557 1px solid"];
	}
}

function converHTMLFileToPDF[] {
	const { jsPDF } = window.jspdf;
	var doc = new jsPDF['l', 'mm', [1200, 1210]];

	var pdfjs = document.querySelector['#temp-target'];

	// Convert HTML to PDF in JavaScript
	doc.html[pdfjs, {
		callback: function[doc] {
			doc.save["output.pdf"];
		},
		x: 10,
		y: 10
	}];
}

Output screenshot to upload HTML file

This screenshot shows the UI frontend with the file upload option. It displays a sample preview of the uploaded HTML.

The “Generate PDF” button in the below image is initially hidden. Then, on preview, the script will toggle it on.

The “Generate PDF” button’s on-click event will trigger the HTML to PDF conversion to save the .pdf file.

Conclusion

The example script created in this article explains how easy it is to perform HTML to PDF generation in JavaScript using jsPDF.

We have seen the possible types of input HTML sources for a PDF generation process.

The jsPDF is the best suitable library to implement the HTML to PDF generation tool.

This jsPDF example has a clear separation of reading the source content and generating HTML to PDF in JavaScript. The show-preview step may help to have a glance before downloading the PDF. You download the example script below.

Download

↑ Back to Top

How do I convert HTML CSS to PDF?

How to convert HTML pages into PDF files:.
On a Windows computer, open an HTML web page in Internet Explorer, Google Chrome, or Firefox. ... .
Click the “Convert to PDF” button in the Adobe PDF toolbar to start the PDF conversion..
Enter a file name and save your new PDF file in a desired location..

How do I create a PDF from HTML?

Example 2: Using jsPDF Library Include the CDN link to jsPDF in the tag of the HTML to import the library. Now we can use the above library to use its functions. We will use the fromHTML method to create PDF from HTML. Save the file using the save[] function once the file is generated.

What is JavaScript jsPDF?

jsPDF is an open-source library for generating PDF documents using JavaScript. It provides multiple options to generate PDF files, with custom properties. It has numerous plugins to support various ways of PDF generation.

Chủ Đề