In this comprehensive guide, we'll walk through the complete process of implementing HTML to PDF conversion using JavaScript with the powerful html2pdf library. This tutorial covers everything from basic setup to advanced customization options.
What is html2pdf?
html2pdf is a lightweight JavaScript library that converts HTML to PDF using JavaScript entirely on the client-side. Built on top of html2canvas and jsPDF, it captures HTML elements and transforms them into downloadable PDF documents without any server-side dependencies.
Key Features of html2pdf
- Client-side PDF generation - no server required
- Easy integration with existing HTML content
- Customizable page size, orientation, and margins
- Support for images, CSS styles, and complex layouts
- Automatic page breaks and pagination
- Lightweight and fast performance
Getting Started: Installation and Setup
Step 1: Create Your Project Structure
First, create a new project folder with the following structure:
project-folder/
├── index.html (Main HTML file)
├── style.css (Optional: Styling file)
└── script.js (Optional: Separate JavaScript file)
Step 2: Create the HTML File (index.html)
Create a new file named index.html in your project folder and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML to PDF Converter</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
}
#content {
border: 2px solid #333;
padding: 30px;
border-radius: 8px;
background: #f9f9f9;
}
h1 {
color: #2c3e50;
}
button {
background: #3498db;
color: white;
padding: 12px 30px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin-top: 20px;
}
button:hover {
background: #2980b9;
}
</style>
</head>
<body>
<div id="content">
<h1>Sample Document</h1>
<p>This is a sample document that will be converted to PDF.</p>
<p>You can include any HTML content here including:</p>
<ul>
<li>Text formatting</li>
<li>Images</li>
<li>Tables</li>
<li>Lists</li>
</ul>
</div>
<button onclick="generatePDF()">Download PDF</button>
<!-- Include html2pdf library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
function generatePDF() {
const element = document.getElementById('content');
html2pdf().from(element).save();
}
</script>
</body>
</html>
Basic Implementation
The simplest way to convert HTML to PDF using JavaScript is with just three lines of code:
function generatePDF() {
const element = document.getElementById('content');
html2pdf().from(element).save();
}
This basic implementation will capture the HTML element with the ID 'content' and download it as a PDF with default settings.
Advanced Configuration Options
For more control over the PDF output, you can customize various options when converting HTML to PDF using JavaScript:
Step 3: Create Advanced JavaScript (script.js)
Create a new file named script.js in your project folder with advanced configuration:
// Advanced PDF generation with custom options
function generateAdvancedPDF() {
const element = document.getElementById('content');
const options = {
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2, logging: true, dpi: 192, letterRendering: true },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().set(options).from(element).save();
}
// Generate PDF with custom page size
function generateCustomSizePDF() {
const element = document.getElementById('content');
const options = {
margin: [0.5, 0.5, 0.5, 0.5],
filename: 'custom-document.pdf',
image: { type: 'jpeg', quality: 0.95 },
html2canvas: { scale: 3 },
jsPDF: { unit: 'in', format: 'a4', orientation: 'landscape' }
};
html2pdf().set(options).from(element).save();
}
// Generate PDF with callback
function generatePDFWithCallback() {
const element = document.getElementById('content');
html2pdf()
.from(element)
.set({
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
})
.save()
.then(() => {
console.log('PDF generated successfully!');
alert('Your PDF has been downloaded!');
})
.catch((error) => {
console.error('Error generating PDF:', error);
alert('Failed to generate PDF. Please try again.');
});
}
Configuration Options Explained
- margin: Sets the page margins (number or array [top, left, bottom, right])
- filename: Name of the downloaded PDF file
- image.type: Image format ('jpeg' or 'png')
- image.quality: Image quality (0-1)
- html2canvas.scale: Scale factor for better quality (higher = better quality but larger file)
- jsPDF.unit: Unit of measurement ('pt', 'mm', 'cm', 'in')
- jsPDF.format: Page format ('a3', 'a4', 'letter', 'legal', etc.)
- jsPDF.orientation: Page orientation ('portrait' or 'landscape')
Complete Working Example
Here's a complete example that demonstrates multiple PDF generation options:
Step 4: Create Complete HTML Example (complete-example.html)
Create a new file named complete-example.html with all features:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced HTML to PDF Converter</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 30px;
min-height: 100vh;
}
.container {
max-width: 900px;
margin: 0 auto;
background: white;
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
overflow: hidden;
}
.header {
background: #2c3e50;
color: white;
padding: 30px;
text-align: center;
}
#content {
padding: 40px;
}
h1 {
color: #2c3e50;
margin-bottom: 20px;
}
h2 {
color: #34495e;
margin-top: 30px;
margin-bottom: 15px;
}
p {
line-height: 1.6;
margin-bottom: 15px;
color: #555;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background: #3498db;
color: white;
}
.buttons {
display: flex;
gap: 10px;
flex-wrap: wrap;
padding: 30px;
background: #f8f9fa;
justify-content: center;
}
button {
background: #3498db;
color: white;
padding: 12px 25px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s;
}
button:hover {
background: #2980b9;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.btn-success {
background: #27ae60;
}
.btn-success:hover {
background: #229954;
}
.btn-warning {
background: #f39c12;
}
.btn-warning:hover {
background: #d68910;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>? HTML to PDF Converter</h1>
<p>Advanced PDF Generation Demo</p>
</div>
<div id="content">
<h1>Professional Business Report</h1>
<p><strong>Date:</strong> October 4, 2025</p>
<p><strong>Department:</strong> Web Development</p>
<h2>Executive Summary</h2>
<p>This document demonstrates the powerful capabilities of html2pdf library for converting HTML content to PDF format using JavaScript. The conversion happens entirely in the browser without requiring any server-side processing.</p>
<h2>Key Benefits</h2>
<ul>
<li>Client-side processing - no server required</li>
<li>Maintains HTML styling and layout</li>
<li>Supports images and complex content</li>
<li>Customizable output options</li>
<li>Easy integration with existing code</li>
</ul>
<h2>Performance Metrics</h2>
<table>
<thead>
<tr>
<th>Metric</th>
<th>Value</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Conversion Speed</td>
<td>Fast</td>
<td>✓ Excellent</td>
</tr>
<tr>
<td>Quality</td>
<td>High</td>
<td>✓ Excellent</td>
</tr>
<tr>
<td>Browser Support</td>
<td>Wide</td>
<td>✓ Excellent</td>
</tr>
</tbody>
</table>
<h2>Conclusion</h2>
<p>The html2pdf library provides a robust solution for converting HTML to PDF in modern web applications. Its ease of use and powerful customization options make it an ideal choice for generating professional documents directly in the browser.</p>
</div>
<div class="buttons">
<button onclick="generateBasicPDF()">Basic PDF</button>
<button onclick="generateHighQualityPDF()" class="btn-success">High Quality PDF</button>
<button onclick="generateLandscapePDF()" class="btn-warning">Landscape PDF</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
// Basic PDF generation
function generateBasicPDF() {
const element = document.getElementById('content');
html2pdf().from(element).save('basic-document.pdf');
}
// High quality PDF with custom settings
function generateHighQualityPDF() {
const element = document.getElementById('content');
const options = {
margin: 0.5,
filename: 'high-quality-report.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {
scale: 3,
logging: false,
dpi: 300,
letterRendering: true
},
jsPDF: {
unit: 'in',
format: 'letter',
orientation: 'portrait',
compress: true
}
};
html2pdf().set(options).from(element).save();
}
// Landscape orientation PDF
function generateLandscapePDF() {
const element = document.getElementById('content');
const options = {
margin: 1,
filename: 'landscape-document.pdf',
image: { type: 'jpeg', quality: 0.95 },
html2canvas: { scale: 2 },
jsPDF: {
unit: 'in',
format: 'a4',
orientation: 'landscape'
}
};
html2pdf().set(options).from(element).save();
}
</script>
</body>
</html>
1. Save the above code as complete-example.html
2. Open the file in your web browser (Chrome, Firefox, Edge, etc.)
3. Click any of the three buttons to generate different PDF formats
4. The PDF will automatically download to your default downloads folder
Best Practices and Tips
1. Optimize for PDF Output
When designing content for PDF conversion, keep these tips in mind:
- Use web-safe fonts or include custom fonts via @font-face
- Avoid absolute positioning when possible
- Test with different content lengths to ensure proper page breaks
- Use relative units (em, rem, %) for better scaling
2. Handle Large Documents
function generateLargeDocumentPDF() {
const element = document.getElementById('content');
const options = {
margin: 0.5,
filename: 'large-document.pdf',
image: { type: 'jpeg', quality: 0.90 },
html2canvas: {
scale: 2,
useCORS: true,
logging: false
},
jsPDF: {
unit: 'in',
format: 'letter',
orientation: 'portrait'
},
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
};
// Show loading indicator
showLoadingIndicator();
html2pdf()
.set(options)
.from(element)
.save()
.then(() => {
hideLoadingIndicator();
alert('PDF generated successfully!');
})
.catch((error) => {
hideLoadingIndicator();
console.error('Error:', error);
alert('Failed to generate PDF');
});
}
function showLoadingIndicator() {
// Add your loading indicator code
console.log('Generating PDF...');
}
function hideLoadingIndicator() {
// Remove loading indicator
console.log('PDF generation complete!');
}
3. Handle Images Properly
// Ensure images are loaded before PDF generation
function generatePDFWithImages() {
const element = document.getElementById('content');
const images = element.getElementsByTagName('img');
// Wait for all images to load
Promise.all(
Array.from(images).map(img => {
if (img.complete) return Promise.resolve();
return new Promise(resolve => {
img.onload = resolve;
img.onerror = resolve;
});
})
).then(() => {
const options = {
margin: 1,
filename: 'document-with-images.pdf',
image: { type: 'jpeg', quality: 0.95 },
html2canvas: {
scale: 2,
useCORS: true,
allowTaint: true
},
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().set(options).from(element).save();
});
}
Common Issues and Solutions
Issue 1: Styles Not Appearing in PDF
Solution: Ensure all CSS is inline or in a <style> tag within the document. External stylesheets may not always be captured.
Issue 2: Content Cut Off
Solution: Adjust margins and scale settings, or use page break CSS properties:
.page-break {
page-break-after: always;
break-after: page;
}
.avoid-break {
page-break-inside: avoid;
break-inside: avoid;
}
Issue 3: Low Quality Output
Solution: Increase the scale and DPI settings:
html2canvas: {
scale: 3, // Higher scale = better quality
dpi: 300, // Higher DPI = sharper text
letterRendering: true
}
Conclusion
Learning to convert HTML to PDF using JavaScript with html2pdf opens up numerous possibilities for creating dynamic, downloadable documents in your web applications. This library provides a simple yet powerful solution for client-side PDF generation with extensive customization options.
Whether you're building invoice generators, report systems, or certificate creators, html2pdf gives you the tools to create professional PDFs directly in the browser. Start implementing it in your projects today and enhance your application's document generation capabilities!