The editor of Downcodes brings you a tutorial on how to use JavaScript and PHP to convert HTML web pages into PDF files. This article will detail two methods: using the JavaScript library jsPDF and using the PHP library TCPDF or mPDF. The jsPDF library allows conversion directly on the client side, while the PHP library requires processing on the server side. We will focus on explaining how to use jsPDF and provide code examples, covering the steps of introducing libraries, processing HTML content, creating PDF instances, adjusting formats, saving files, etc. We will also briefly introduce the conversion method and advanced functions using PHP. Implementation, such as adding pictures, watermarks, headers and footers, etc. No matter which method you choose, this article will help you complete HTML to PDF conversion efficiently.
Converting web pages to PDF is a common requirement, which allows us to save website content in a fixed format. Using JavaScript or PHP to convert HTML web pages to PDF includes: using JavaScript libraries and using PHP libraries. Among these conversion tools, JavaScript libraries like jsPDF and html2pdf.js are very popular, while PHP has libraries like TCPDF or mPDF. We will focus on using the jsPDF library of JavaScript to achieve conversion. This is because the jsPDF library provides good client support, is simple to operate, and can complete the conversion without communicating with the server.
jsPDF is a library written in pure JavaScript that works in a front-end environment and requires no back-end support. To use jsPDF, you first need to introduce its library file into the project. You can install it from jsPDF’s GitHub repository or via npm. Once the jsPDF library is introduced, you can use JavaScript code to read the content of HTML and use the API provided by jsPDF to generate PDF files.
To start the conversion process, you first need to import jsPDF into your web page. You can directly download the jsPDF library and pass
Or install using npm:
npm install jspdf
Then import it in your JavaScript file:
import { jsPDF } from jspdf;
Before generating the PDF, you may wish to modify the HTML to ensure that the converted PDF file meets your needs. For example, you may need to hide certain page elements and keep only the main content.
// Get the HTML elements that need to be converted
const element = document.getElementById('content-to-pdf');
// Modify HTML content, such as hiding unnecessary elements
element.querySelectorAll('.no-print').forEach(element => element.style.display = 'none');
Create a new jsPDF instance and use the API provided by jsPDF to read HTML elements and convert them into PDF format.
const doc = new jsPDF();
// Assume you want the page to be rendered in an A4 size PDF
doc.html(document.body, {
callback: function (doc) {
doc.save('webpage.pdf');
},
x: 10,
y: 10,
width: 190,
windowWidth: document.body.scrollWidth
});
During the conversion process, you may need to adjust the format and layout of the PDF, such as page size, margins, or whether you need to print in landscape orientation, etc.
const doc = new jsPDF({
orientation: 'p', // portrait
unit: 'mm', // The unit is millimeters
format: 'a4', // The format is A4 paper
});
Once the HTML content has been converted to PDF, you can use the save() method to save the file, or otherwise process the resulting PDF data.
doc.save('converted-webpage.pdf'); // Save PDF file
If you want to perform HTML to PDF conversion on the server side, you can use PHP libraries such as TCPDF or mPDF. To use these libraries, you need to first introduce them into your PHP environment, usually through Composer.
composer require tecnickcom/tcpdf
Then create a TCPDF object in the PHP script and use the methods provided by the object to convert the HTML code to PDF format.
require_once('tcpdf_include.php');
//Create a new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//Set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
//Add a page
$pdf->AddPage();
//Set content
$html = '
$pdf->writeHTML($html, true, false, true, false, '');
// Output PDF
$pdf->Output('example_001.pdf', 'I');
When dealing with PDF conversion, you may want to consider the styles and fonts in the document to ensure that the resulting PDF file retains the style of the web content.
Both jsPDF and TCPDF provide basic support for styles. You can use CSS styles directly in HTML or apply styles when generating PDF. However, since PDFs are not rendered exactly the same as web pages, there may be slight differences. For jsPDF, support for CSS can be enhanced through plug-ins. With TCPDF, you need to carefully adjust the CSS to get the best results.
doc.setFont(helvetica);
doc.setFontStyle(bold);
doc.setFontSize(16);
doc.text(Hello World!, 10, 10);
$html = '
$pdf->writeHTML($html, true, false, true, false, '');
During the PDF conversion process, you may also need to deal with some advanced functions, such as adding headers and footers, watermarks, tables, images, etc. These features are generally supported in the jsPDF and TCPDF libraries, but they are implemented slightly differently. According to specific needs, you can call the corresponding library function to achieve it.
jsPDF provides various methods to enhance the functionality of PDF, such as addImage() for adding images, setProperties() for setting document properties, etc.
// add image
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
TCPDF also provides powerful functions to handle advanced content of PDF.
// Set header
$pdf->setHeaderData('', 0, 'Title', 'Header', array(0,64,255), array(0,64,128));
$pdf->setHeaderFont(Array('helvetica', '', 10));
//Add watermark
$pdf->SetAlpha(0.3);
$pdf->Image('watermark.png', 25, 110, 160, 40, '', '', '', false, 300, '', false, false, 0);
//Restore full transparency
$pdf->SetAlpha(1);
To sum up, using JavaScript or PHP to convert HTML web pages to PDF files involves choosing an appropriate library, processing web page content, adjusting PDF layout, and using the advanced functions provided by the library to achieve complex customization requirements. Regardless of whether you choose jsPDF on the client side or TCPDF on the server side, the basic implementation steps and methods are similar. During specific implementation, the most appropriate tools and methods need to be selected based on the actual needs and environment of the project.
1. How to convert HTML webpage to PDF using JavaScript?
You can use the jsPDF library to convert HTML web pages to PDF. This library allows you to generate PDF files in front-end JavaScript. You can do this by rendering the content of an HTML element onto a Canvas and then using jsPDF to convert the Canvas to a PDF file. This way you can generate PDF files directly on the client.2. How to convert HTML web pages to PDF using PHP?
The more common way to convert HTML web pages to PDF using PHP is to use the TCPDF or mPDF library. Both libraries can generate PDF files on the server side. You just need to install the corresponding library on the server, and then use PHP to render HTML web pages into PDF files.3. In addition to jsPDF, TCPDF and mPDF, what other tools can convert HTML web pages to PDF?
In addition to the common jsPDF, TCPDF and mPDF, there are other tools that can convert HTML web pages to PDF, such as: wkhtmltopdf, PhantomJS, etc. These tools can all run in the background to render HTML web pages into PDF files. You can choose the tool that best suits you according to your needs to realize the function of converting web pages to PDF.I hope this tutorial can help you master HTML to PDF conversion skills. The editor of Downcodes wishes you happy programming!