需要的JAR包
itext-pdfa-5.5.0.jar
itextpdf-5.5.0.jar
itext-asian.jar
package com.itext;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
public class ItextToPdf {
public static void main(String[] args) {
ItextToPdf ih = new ItextToPdf();
ih.htmlCodeComeFromFile("D:\\main.html", "D:\\iText_3.pdf");
ih.htmlCodeComeString("Hello中文", "D:\\iText_2.pdf");
}
public void htmlCodeComeFromFile(String filePath, String pdfPath) {
Document document = new Document();
try {
StyleSheet st = new StyleSheet();
st.loadTagStyle("body", "leading", "16,0");
PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
Paragraph t = new Paragraph(filePath, FontChinese);
ArrayList p = (ArrayList) HTMLWorker.parseToList(new FileReader(filePath), st);
for(int k = 0; k < p.size(); ++k) {
document.add((Element)p.get(k));
}
document.close();
System.out.println("文档创建成功");
}catch(Exception e) {
e.printStackTrace();
}
}
public void htmlCodeComeString(String htmlCode, String pdfPath) {
Document doc = new Document(PageSize.A4);
try {
PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
doc.open();
// 解决中文问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
Paragraph t = new Paragraph(htmlCode, FontChinese);
doc.add(t);
doc.close();
System.out.println("文档创建成功");
}catch(Exception e) {
e.printStackTrace();
}
}
}