使用itext html2pdf的正确姿势,避坑必备

itext html2pdf 网上一些资料不全面,网上很多例子不太靠谱,有很多坑,这里给出工具和常见的坑,可以少走很多弯路。

支持html前端分页符和避免分页的属性。

1、优势

  • 转换效果非常理想
  • 不需要安装软件

2、依赖3个包 

https://mvnrepository.com/artifact/com.itextpdf/html2pdf/2.1.0

https://mvnrepository.com/artifact/com.itextpdf/forms/7.1.3

https://mvnrepository.com/artifact/com.itextpdf/layout/7.1.3

3、工具类

/**
* by 明明如月 github :https://github.com/chujianyun
*/

public class Html2PdfUtil {

    /**
     * 字体所在目录
     */
    private static final String FONT_RESOURCE_DIR = "/font";

    /**
     * @param htmlContent html文本
     * @param dest        目的文件路径,如 /xxx/xxx.pdf
     * @throws IOException IO异常
     */
    public static void createPdf(String htmlContent, String dest) throws IOException {
        ConverterProperties props = new ConverterProperties();
        // props.setCharset("UFT-8"); 编码
        FontProvider fp = new FontProvider();
        fp.addStandardPdfFonts();
        // .ttf 字体所在目录
        String resources = Html2PdfUtil.class.getResource(FONT_RESOURCE_DIR).getPath();
        fp.addDirectory(resources);
        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();
    }
}

4、主要的坑!!

  1. Html尽量规范
  2. html不支持float样式(关键字)
  3. 不要设置表格最小宽度

猜你喜欢

转载自blog.csdn.net/w605283073/article/details/83352856