Converting HTML to PDF using iText
Problem: CSS positioning not respected
Many developers encounter difficulties converting HTML to PDF using iText, particularly regarding the placement of elements using CSS.
HTMLWorker's Limitations
HTMLWorker, a deprecated component of iText, has significant drawbacks:
-
CSS support: It doesn't support real CSS and requires explicit style definition in code.
-
Deprecated: Many classes and methods used in HTMLWorker have become outdated.
XMLWorker's Challenges
XMLWorker, intended as a generic XML parsing framework, faced similar issues:
-
Missing image: Images were missing without an ImageProvider; even then, CSS attributes like float were ignored.
-
Partial CSS support: Positioning-related CSS styles weren't fully supported.
Solution with iText 7 and pdfHTML
To resolve these shortcomings, iText 7 and its pdfHTML add-on were developed. They offer a simplified approach:
public static final String SRC = "src/main/resources/html/sample.html";
public static final String DEST = "target/results/sample.pdf";
public void createPdf(String src, String dest) throws IOException {
HtmlConverter.convertToPdf(new File(src), new File(dest));
}
This code generates the desired PDF output with CSS attributes like float being respected.
Additional Considerations
-
Licensing: iText 7 is released under the AGPL, allowing free use in open source projects, but commercial licenses are required for closed source applications.
-
Legacy systems: Migrating from older iText versions to iText 7 can be beneficial for code simplicity and future-proofing.
-
Beginner's guide: For those new to iText 7, it's recommended to discard existing code and start anew, simplifying the conversion process.
The above is the detailed content of How Can iText 7 and pdfHTML Solve HTML to PDF Conversion Problems with CSS Positioning?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn