美文网首页
itextpdf convert html string to

itextpdf convert html string to

作者: _浅墨_ | 来源:发表于2021-11-04 15:39 被阅读0次

一、导入依赖

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

二、解决中文乱码问题

/**
 * @description: html导出PDF支持中文,避免乱码
 * @author: chang
 * @create: 2021-11-04 14:25
 **/
public class ChineseFontProvider extends XMLWorkerFontProvider {

    @Override
    public Font getFont(String fontname, String encoding, float size, int style) {

        try {
            BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//            BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            return new Font(bfChinese,13,style);
            //            return new Font(bfChinese,size,style);
        }catch (Exception e){
            e.printStackTrace();
        }
        return super.getFont(fontname, encoding, size, style);
    }
}

三、由html字符串生成pdf

 public static void convertHtmlToPdf() throws IOException{
        String htmlStr = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta charset=\"utf-8\">\n" +
                "<title>文档标题</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "\t<h1>我的第一个HTML页面</h1>\n" +
                "\t<p>我的第一个段落。</p>\n" +
                "</body>\n" +
                "</html>\n" +
                "\n";
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(FILE_BASE_PATH+"htmlToPDF.pdf"));
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer,document,new ByteArrayInputStream(htmlStr.getBytes(StandardCharsets.UTF_8)),null, Charset.forName("UTF-8"),new ChineseFontProvider());
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

参考链接:

  1. iText-Asian jar可以使用的中文字符及iText——>html2pdf使用(附坑)_Chuck_le的博客-程序员宅基地
  2. Hello HTML to PDF
  3. using fonts in pdfhtml

相关文章

网友评论

      本文标题:itextpdf convert html string to

      本文链接:https://www.haomeiwen.com/subject/jirkzltx.html