Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add HTML and CSS to PDF?
In this tutorial, we will learn how to convert HTML and CSS content to PDF using JavaScript libraries. Creating PDFs from web content allows users to save styled webpages, forms, reports, or any HTML content as downloadable documents.
Converting HTML and CSS to PDF from scratch using vanilla JavaScript is complex and requires extensive coding. Fortunately, several JavaScript libraries simplify this process by providing easy-to-use methods for generating PDFs from web content.
We will explore two popular libraries html2pdf.js and jsPDF both of which can convert styled HTML content into PDF documents directly in the browser.
Using the html2pdf.js Library
The html2pdf.js library is a client-side solution that converts any HTML element into a PDF document. It preserves the original styling and layout of the webpage, making it ideal for converting complete styled content.
Syntax
Following is the syntax to include and use the html2pdf.js library
<!-- Include html2pdf library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.js"></script>
<!-- Convert element to PDF -->
var element = document.getElementById('elementId');
html2pdf(element);
For advanced options, you can configure the PDF generation
var options = {
margin: 1,
filename: 'document.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().set(options).from(element).save();
Example
Following example demonstrates converting a styled HTML section to PDF using html2pdf.js
<!DOCTYPE html>
<html>
<head>
<title>HTML to PDF with html2pdf.js</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
#content {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 10px;
text-align: center;
}
h2 { margin-top: 0; }
.highlight { background-color: rgba(255,255,255,0.2); padding: 10px; border-radius: 5px; }
</style>
</head>
<body>
<button id="downloadBtn">Download as PDF</button>
<div id="content">
<h2>Converting HTML & CSS to PDF</h2>
<p class="highlight">This styled content will be converted to PDF with all formatting preserved.</p>
<p>The html2pdf.js library maintains the original styling, colors, and layout.</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.js"></script>
<script>
document.getElementById('downloadBtn').addEventListener('click', function() {
var element = document.getElementById('content');
var options = {
margin: 0.5,
filename: 'styled-content.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
};
html2pdf().set(options).from(element).save();
});
</script>
</body>
</html>
The output displays a styled content box with a gradient background. Clicking "Download as PDF" saves the styled content as a PDF file
[Download as PDF] Converting HTML & CSS to PDF This styled content will be converted to PDF with all formatting preserved. The html2pdf.js library maintains the original styling, colors, and layout. (Content appears with gradient background and white text)
Using the jsPDF Library
The jsPDF library is another popular solution for generating PDFs from HTML content. While it offers more programmatic control over PDF creation, it may not preserve all CSS styling as accurately as html2pdf.js.
Syntax
Following is the syntax to include and use the jsPDF library
<!-- Include jsPDF library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<!-- Convert HTML to PDF -->
var doc = new jsPDF();
var element = document.getElementById('elementId');
doc.html(element, {
callback: function(doc) {
doc.save('document.pdf');
}
});
Example
Following example demonstrates converting HTML content to PDF using jsPDF
<!DOCTYPE html>
<html>
<head>
<title>HTML to PDF with jsPDF</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
#report {
border: 2px solid #4CAF50;
padding: 20px;
background-color: #f9f9f9;
}
.header { color: #4CAF50; text-align: center; }
.content { margin: 15px 0; line-height: 1.6; }
</style>
</head>
<body>
<button id="generatePDF">Generate PDF Report</button>
<div id="report">
<h2 class="header">Monthly Sales Report</h2>
<div class="content">
<p><strong>Period:</strong> January 2024</p>
<p><strong>Total Sales:</strong> $45,230</p>
<p><strong>Growth:</strong> +12% compared to last month</p>
<p>This report shows significant improvement in our sales performance.</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
document.getElementById('generatePDF').addEventListener('click', function() {
const { jsPDF } = window.jspdf;
var doc = new jsPDF();
var element = document.getElementById('report');
doc.html(element, {
callback: function(doc) {
doc.save('sales-report.pdf');
},
margin: [10, 10, 10, 10],
x: 10,
y: 10
});
});
</script>
</body>
</html>
The output shows a formatted report with borders and styling. Clicking "Generate PDF Report" creates a downloadable PDF
[Generate PDF Report] Monthly Sales Report Period: January 2024 Total Sales: $45,230 Growth: +12% compared to last month This report shows significant improvement in our sales performance. (Content appears with green border and light background)
Library Comparison
Following table compares the key differences between html2pdf.js and jsPDF libraries
| Feature | html2pdf.js | jsPDF |
|---|---|---|
| CSS Support | Excellent preserves most styling | Limited basic styling only |
| Implementation | Simple one-line conversion | More configuration required |
| File Size | Larger PDF files | Smaller, optimized PDFs |
| Performance | Slower for complex layouts | Faster processing |
| Best Use Case | Styled web content, reports with design | Text-heavy documents, simple forms |
| Browser Support | Modern browsers | Wide browser compatibility |
Key Considerations
When choosing between these libraries, consider the following factors
-
Styling Requirements Use html2pdf.js if you need to preserve complex CSS styling, gradients, and layouts.
-
Performance Choose jsPDF for faster processing and smaller file sizes when dealing with simple content.
-
Browser Compatibility jsPDF has broader browser support, while html2pdf.js works best in modern browsers.
-
File Size html2pdf.js generates larger files due to preserved styling, while jsPDF creates more compact documents.
Conclusion
Both html2pdf.js and jsPDF provide effective ways to convert HTML and CSS content to PDF documents. html2pdf.js excels at preserving complex styling and layouts, making it ideal for styled web content. jsPDF offers better performance and smaller file sizes, suitable for simple documents and forms. Choose based on your specific styling and performance requirements.
