iText “XML Worker”允许开发人员以一种程序员友好的方式将XML文件转换成PDF文件。iText还可以将包含CSS样式的HTML转换为PDF格式的文档。
目标:
实现如何利用iText Java库将HTML文件转换成PDF文档?
Environment & Tools
Eclipse (or any other IDE)Maven (optional)
Library:
iText 5.4.2
List of jar files: .classpathList of Maven dependencies: pom.xml
( 1 ) HTML File
index.html
01
02
03
04
HTML to PDF05
06
07
08
HTML to PDF
09
10 itext 5.4.2 converting HTML to PDF
11
12
13
14
Title15
iText - Java HTML to PDF16
17
18
URL19
http://hmkcode.com/itext-html-to-pdf-using-java20
21
22
23
style.css
01 h1 {
02 color:#ccc;
03 }
04 table tr td{
05 text-align:center;
06 border:1px solid gray;
07 padding:4px;
08 }
09 table tr th{
10 background-color:#84C7FD;
11 color:#fff;
12 width: 100px;
13 }
14 .itext{
15 color:#84C7FD;
16 font-weight:bold;
17 }
18 .description{
19 color:gray;
20 }
( 2 ) Java App App.java
01 package com.hmkcode;
02
03 import java.io.FileInputStream;
04 import java.io.FileOutputStream;
05 import java.io.IOException;
06 import com.itextpdf.text.Document;
07 import com.itextpdf.text.DocumentException;
08 import com.itextpdf.text.pdf.PdfWriter;
09 import com.itextpdf.tool.xml.XMLWorkerHelper;
10
11 public class App
12 {
13 public static void main( String[] args ) throws DocumentException, IOException
14 {
15 // step 1
16 Document document = new Document();
17 // step 2
18 PdfWriter writer = PdfWriter.getInstance(document, newFileOutputStream("pdf.pdf"));
19 // step 3
20 document.open();
21 // step 4
22 XMLWorkerHelper.getInstance().parseXHtml(writer, document,
23 new FileInputStream("index.html"));
24 //step 5
25 document.close();
26
27 System.out.println( "PDF Created!" );
28 }
29 }
( 3 ) Output “PDF” Source Code @ GitHub