itext HTML 转 PDF
henry.huang

1. 添加依赖

1
2
3
4
//itext
implementation 'com.itextpdf:html2pdf:2.1.0'
implementation 'com.itextpdf:forms:7.1.3'
implementation 'com.itextpdf:layout:7.1.3'

2. 编写Html2PdfUtil工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public class Html2PdfUtil {
private final static String FONTS_DIR = "C:\\Windows\\Fonts";

public static void main(String[] args) throws IOException {
createPdf(readTextFromFile("d:\\input.html"),"d:\\output.pdf");
}

/**
*
* @param fileName
* @return
* @throws IOException
*/
public static String readTextFromFile(String fileName) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String content;
while ((content = br.readLine()) != null) {
sb.append(content);
}
return sb.toString();
}

/**
* @param htmlContent html文本
* @throws IOException IO异常
*/
public static byte[] convert2Pdf(String htmlContent) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

ConverterProperties props = new ConverterProperties();
// props.setCharset("UFT-8"); 编码
FontProvider fp = new FontProvider();
fp.addStandardPdfFonts();
// .ttf 字体所在目录
fp.addDirectory(StringUtils.isBlank(FONTS_DIR) ? "/usr/share/fonts" : FONTS_DIR);
props.setFontProvider(fp);
// html中使用的图片等资源目录(图片也可以直接用url或者base64格式而不放到资源里)
// props.setBaseUri(resources);

List<IElement> elements = HtmlConverter.convertToElements(htmlContent, props);
PdfDocument pdf = new PdfDocument(new PdfWriter(outputStream));
Document document = new Document(pdf, PageSize.A4.rotate(), false);
for (IElement element : elements) {
// 分页符
if (element instanceof HtmlPageBreak) {
document.add((HtmlPageBreak) element);
//普通块级元素
} else {
document.add((IBlockElement) element);
}
}
document.close();
return outputStream.toByteArray();
}

/**
* @param htmlContent html文本
* @param dest 目的文件路径,如 /xxx/xxx.pdf
* @throws IOException IO异常
*/
public static void convert2Pdf(String htmlContent, String dest) throws IOException {
ConverterProperties props = new ConverterProperties();
// props.setCharset("UFT-8"); 编码
FontProvider fp = new FontProvider();
fp.addStandardPdfFonts();
// .ttf 字体所在目录
fp.addDirectory(StringUtils.isBlank(FONTS_DIR) ? "/usr/share/fonts" : FONTS_DIR);
props.setFontProvider(fp);
// html中使用的图片等资源目录(图片也可以直接用url或者base64格式而不放到资源里)
// props.setBaseUri(resources);

List<IElement> elements = HtmlConverter.convertToElements(htmlContent, props);
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Document document = new Document(pdf, PageSize.A4.rotate(), false);
for (IElement element : elements) {
// 分页符
if (element instanceof HtmlPageBreak) {
document.add((HtmlPageBreak) element);
//普通块级元素
} else {
document.add((IBlockElement) element);
}
}
document.close();
}
}
 评论