1. 添加依赖
//itext
implementation 'com.itextpdf:html2pdf:2.1.0'
implementation 'com.itextpdf:forms:7.1.3'
implementation 'com.itextpdf:layout:7.1.3'
2. 编写Html2PdfUtil工具类
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();
}
}