天天看点

使用itext7把html导出为pdf,并设置中文

  1. 导包
<!--        html转pdf工具-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!--        中文字体-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>7.1.11</version>
        </dependency>
           

html导出为pdf(问题:中文无法显示)

/**
     * html导出为pdf(问题:中文无法显示)
     *
     * @throws IOException IOException
     */
    @Test
    public void test() throws IOException {
        String htmlStr = "<p>hello</p>";
        OutputStream outputStream = new FileOutputStream("D:\\导出test.pdf");
        HtmlConverter.convertToPdf(htmlStr, outputStream);
        outputStream.close();
    }
           

html导出为pdf(解决中文无法显示的问题)

/**
     * html导出为pdf(解决中文无法显示的问题)
     * 步骤1:导包font-asian
     * 步骤2:设置converterProperties
     *
     * @throws IOException IOException
     */
    @Test
    public void test1() throws IOException {
        ConverterProperties converterProperties;

        FontProvider fontProvider = new FontProvider();
        PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");

        converterProperties = new ConverterProperties();
        converterProperties.setFontProvider(fontProvider);

        String htmlStr = "<p>hello 你好你好你好</p>";
        OutputStream outputStream = new FileOutputStream("D:\\中文test.pdf");
        HtmlConverter.convertToPdf(htmlStr, outputStream, converterProperties);
        outputStream.close();
    }