To create a PDF from an HTML file using iText in Java, you
can use the HtmlConverter class from the itext7 library. Below are the steps to
achieve this:
- Add
iText Dependency: Add the necessary iText and HTML to PDF dependencies
to your project.
- Convert
HTML to PDF: Use HtmlConverter to convert HTML content to a PDF file.
Step-by-Step Guide
1. Add iText Dependencies
First, add the following dependencies to your pom.xml if
you're using Maven:
Xml
<dependencies> <!-- iText 7 Core Library --> <dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId> <version>7.2.2</version> </dependency> <!-- iText HTML2PDF Converter --> <dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId> <version>3.0.3</version> </dependency> </dependencies> |
Make sure to check for the latest versions of these
dependencies.
2. Java Code to Convert HTML to PDF
Here's an example of how to convert an HTML file to a PDF
using iText:
java
import
com.itextpdf.html2pdf.HtmlConverter; import
java.io.File; import
java.io.IOException; public class
HtmlToPdfConverter { public static void main(String[] args) { // Source HTML file String htmlSource =
"path/to/source.html"; // Target PDF file String pdfDest =
"path/to/destination.pdf"; try { // Convert HTML to PDF HtmlConverter.convertToPdf(new
File(htmlSource), new File(pdfDest)); System.out.println("PDF
created successfully."); } catch (IOException e) { e.printStackTrace(); } } } |
Detailed Explanation
- Import
HtmlConverter: import com.itextpdf.html2pdf.HtmlConverter;
- Define
File Paths: Specify the paths for the source HTML file and the
destination PDF file.
- Convert
HTML to PDF:
- HtmlConverter.convertToPdf(new
File(htmlSource), new File(pdfDest)); converts the HTML file to a PDF
file.
- Exception
Handling: Handle any IOException that may occur during file
operations.
Example HTML File
Save the following HTML content as source.html to test the
conversion:
html
<!DOCTYPE
html> <html> <head> <title>Sample HTML</title> </head> <body> <h1>Hello, PDF!</h1> <p>This is a sample HTML converted
to PDF using iText.</p> </body> </html> |
Running the Example
- Ensure
that the iText dependencies are correctly added to your project.
- Replace
the paths in the Java code with the actual paths to your HTML file and
desired PDF output location.
- Run
the Java program.
You should see a message PDF created successfully. if the
conversion is successful, and a PDF file should be created at the specified
location with the content of the HTML file.
Notes
- Ensure
that you have the necessary permissions to read the HTML file and write to
the PDF file location.
- The
example assumes a simple HTML file. More complex HTML files with CSS and
JavaScript might require additional configuration and resources.
- For
more advanced use cases, refer to the iText 7 documentation and user
guides.
0 Comments