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 take HTML form data as text and send them to html2pdf?
The html2pdf is a JavaScript library that allows developers to convert HTML content to PDF format. It takes HTML elements as parameters and generates downloadable PDF documents. This library is particularly useful for creating reports, forms, and other documents from web page content.
In this article, we will learn how to capture HTML form data and convert it to PDF using the html2pdf library. We will explore different approaches to include form data in PDF documents.
Syntax
Following is the basic syntax to convert HTML form data to PDF using html2pdf
var element = document.getElementById('formId');
html2pdf().from(element).save();
In the above syntax, we access the form element using its ID and pass it to the html2pdf() method to generate and download the PDF.
Including html2pdf Library
Before using html2pdf, you need to include the library in your HTML document. You can use the CDN link
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
Method 1 Converting Entire Form to PDF
This approach converts the complete form structure, including labels, input fields, and their values, directly to PDF. It preserves the original form layout and styling.
Example
Following example demonstrates how to convert an entire HTML form to PDF
<!DOCTYPE html>
<html>
<head>
<title>Form to PDF - Complete Form</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<style>
#form {
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
max-width: 400px;
font-family: Arial, sans-serif;
}
label { display: block; margin: 10px 0 5px; font-weight: bold; }
input { width: 100%; padding: 8px; margin-bottom: 15px; border: 1px solid #ddd; }
button { background: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; }
</style>
</head>
<body>
<h2>Convert Complete Form to PDF</h2>
<form id="form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="John Doe">
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="john@example.com">
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" value="123-456-7890">
<button type="button" onclick="generatePDF()">Download as PDF</button>
</form>
<script>
function generatePDF() {
var element = document.getElementById('form');
var options = {
margin: 1,
filename: 'form-data.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().from(element).set(options).save();
}
</script>
</body>
</html>
The output generates a PDF containing the complete form structure with all input fields and their values as they appear on the webpage.
Method 2 Converting Form Data Only
This approach extracts only the form data values and creates a custom formatted PDF document without the original form structure. It provides more control over the PDF layout and content presentation.
Example
Following example shows how to extract form data and create a formatted PDF
<!DOCTYPE html>
<html>
<head>
<title>Form to PDF - Data Only</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<style>
.form-container {
padding: 20px;
max-width: 400px;
font-family: Arial, sans-serif;
}
label { display: block; margin: 10px 0 5px; font-weight: bold; }
input, textarea { width: 100%; padding: 8px; margin-bottom: 15px; border: 1px solid #ddd; }
button { background: #28a745; color: white; padding: 10px 20px; border: none; cursor: pointer; }
</style>
</head>
<body>
<h2>Convert Form Data to Formatted PDF</h2>
<div class="form-container">
<form id="userForm">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" value="Jane Smith">
<label for="department">Department:</label>
<input type="text" id="department" name="department" value="IT Department">
<label for="feedback">Feedback:</label>
<textarea id="feedback" name="feedback" rows="4">Great service and support!</textarea>
<button type="button" onclick="generateFormattedPDF()">Create PDF Report</button>
</form>
</div>
<script>
function generateFormattedPDF() {
// Extract form data
var fullName = document.getElementById('fullName').value;
var department = document.getElementById('department').value;
var feedback = document.getElementById('feedback').value;
// Create formatted content
var contentDiv = document.createElement('div');
contentDiv.innerHTML = `
<div style="font-family: Arial, sans-serif; padding: 20px;">
<h1 style="color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px;">
Employee Report
</h1>
<div style="margin: 20px 0;">
<p><strong>Full Name:</strong> ${fullName}</p>
<p><strong>Department:</strong> ${department}</p>
<p><strong>Feedback:</strong></p>
<p style="border-left: 3px solid #007bff; padding-left: 15px; margin-left: 10px; font-style: italic;">
${feedback}
</p>
<p style="margin-top: 30px; color: #666; font-size: 12px;">
Generated on: ${new Date().toLocaleDateString()}
</p>
</div>
</div>
`;
// Generate PDF with custom options
var options = {
margin: 0.5,
filename: 'employee-report.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(contentDiv).set(options).save();
}
</script>
</body>
</html>
This example creates a professionally formatted PDF report containing only the form data with custom styling, headers, and timestamps.
Advanced Configuration Options
The html2pdf library provides several configuration options to customize the PDF output
var options = {
margin: 1, // Margin in inches
filename: 'document.pdf', // Output filename
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {
scale: 2, // Scale for better quality
useCORS: true // Handle cross-origin images
},
jsPDF: {
unit: 'in', // Units: in, pt, cm, mm
format: 'letter', // Page format: a4, letter, legal
orientation: 'portrait' // Portrait or landscape
}
};
Handling Form Validation Before PDF Generation
It is good practice to validate form data before generating the PDF. Here is an example that includes validation
<!DOCTYPE html>
<html>
<head>
<title>Form Validation and PDF Generation</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<style>
.container { max-width: 500px; margin: 20px; font-family: Arial, sans-serif; }
.form-group { margin-bottom: 15px; }
label { display: block; font-weight: bold; margin-bottom: 5px; }
input { width: 100%; padding: 8px; border: 1px solid #ddd; }
.error { color: red; font-size: 14px; margin-top: 5px; }
button { background: #dc3545; color: white; padding: 10px 15px; border: none; cursor: pointer; margin-right: 10px; }
.success { background: #28a745; }
</style>
</head>
<body>
<div class="container">
<h2>Registration Form with Validation</h2>
<form id="registrationForm">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<div id="usernameError" class="error"></div>
</div>
<div class="form-group">
<label for="userEmail">Email:</label>
<input type="email" id="userEmail" name="userEmail" required>
<div id="emailError" class="error"></div>
</div>
<button type="button" onclick="validateAndGeneratePDF()">Validate & Generate PDF</button>
<button type="button" class="success" onclick="clearForm()">Clear Form</button>
</form>
</div>
<script>
function validateAndGeneratePDF() {
var username = document.getElementById('username').value.trim();
var email = document.getElementById('userEmail').value.trim();
var isValid = true;
// Clear previous error messages
document.getElementById('usernameError').textContent = '';
document.getElementById('emailError').textContent = '';
// Validate username
if (username.length < 3) {
document.getElementById('usernameError').textContent = 'Username must be at least 3 characters long';
isValid = false;
}
// Validate email
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
document.getElementById('emailError').textContent = 'Please enter a valid email address';
isValid = false;
}
if (isValid) {
generateRegistrationPDF(username, email);
}
}
function generateRegistrationPDF(username, email) {
var pdfContent = document.createElement('div');
pdfContent.innerHTML = `
<div style="font-family: Arial, sans-serif; padding: 30px;">
<h1 style="color: #28a745; text-align: center;">Registration Confirmation</h1>
<hr style="border: 1px solid #28a745; margin: 20px 0;">
<h3>User Details:</h3>
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 10px; border: 1px solid #ddd; font-weight: bold;">Username:</td>
<td style="padding: 10px; border: 1px solid #ddd;">${username}</td>
</tr>
<tr>
<td style="padding: 10px; border: 1px solid #ddd; font-weight: bold;">Email:</td>
<td style="padding: 10px; border: 1px solid #ddd;">${email}</td>
< 