java后台HTML转换成pdf
程序员文章站
2022-07-13 13:35:18
...
java后台HTML转换成pdf
private final static String DEST = "C:\\80afa41a3bfc474cbf1ac8b5bc1d.pdf"; //生成pdf的路径
private final static String SRC = "D:\\3b33a68bbf52417aac48687937352464.html"; //html文件路径
public static final String FONT = "/font/NotoSansCJKsc-Regular.otf"; //本地字体路径(百度下载)
public static void main(String[] args) {
try {
HtmlToPdf html = new HtmlToPdf();
html.tomPdf(SRC, DEST);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* HTML转换成pdf
* @param html html文件路径
* @param DEST 生成pdf的路径
* @throws Exception
*/
public static void tomPdf(String html, String DEST) throws Exception {
ConverterProperties props = new ConverterProperties();
DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
defaultFontProvider.addFont(FONT);
props.setFontProvider(defaultFontProvider);
PdfWriter writer = new PdfWriter(DEST);
PdfDocument pdf = new PdfDocument(writer);
pdf.setDefaultPageSize(new PageSize(595.0F, 842.0F));
Document document = HtmlConverter.convertToDocument(new FileInputStream(html), pdf, props);
document.close();
pdf.close();
}
<!--将html转换成pdf-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.1.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>barcodes</artifactId>
<version>7.1.2</version>
</dependency>
下一篇: java 解析PDF