天天看點

使用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();
    }