html转pdf(itextpdf)

1、pom依赖

        
            com.itextpdf
            itextpdf
            5.4.2
        

        
            org.xhtmlrenderer
            core-renderer
            R8
        

2、转换工具类


import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;

/**
 * Created by roy on 2017/12/19.
 */
public class PDFUtil {
    /**
     * 生成 PDF 文件
     * @param out 输出流
     * @param html HTML字符串
     * @throws IOException IO异常
     * @throws DocumentException Document异常
     */
    public static void createPDF(OutputStream out, String html) throws IOException, DocumentException {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        if (System.getProperty("os.name").contains("Window")) {
            fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } else {
            fontResolver.addFont("/usr/share/fonts/win/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        renderer.layout();
        renderer.createPDF(out);
    }

    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File("/app/data/test.pdf");
        FileOutputStream outputStream = new FileOutputStream(file);
        String html =
                "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "
row 1, cell 1row 1, cell 2
哈哈哈row 2, cell 2
\n" + "\n" + "\n"; createPDF(outputStream,html); }

3、备注

xhtmlrenderer只能处理静态化的html。由于xhtmlrenderer对html的检查很严格,必须使用闭合标签,即""或者""这种才是可识别的。而且如果是复杂一点的html,最外层必须有""标签才可以。

  • 参考资料
    使用 IText 将 HTML 转化为 PDF
    html文件转pdf

你可能感兴趣的:(html转pdf(itextpdf))