iText html转pdf 中文消失问题

解决mac上 html转pdf中文消失问题

public void testpdf (String HTML,String file){
        try {
            File file1 = new File(file);
            if (file1.exists()) file1.delete();


            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();

            //加载字体
            XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider() {

                @Override
                public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
                    log.debug("fontname:{},size:{},encoding:{},embedded:{},style:{},color:{}",fontname,size,encoding,embedded,style,color == null ? null : color.toString());

                    //你的字体文件的位置
                    //这里把所有字体都设置为宋体了,可以根据fontname的值设置字体
                    String yaHeiFontName ="/Users/wangluyao/jf/123/font/simsun.ttc";
                    //如果是ttc需要这一行,ttf不需要
                    yaHeiFontName += ",1";
                    com.lowagie.text.Font yaHeiFont;
                    Font font = null;
                    try {
                         font = new Font(com.itextpdf.text.pdf.BaseFont.createFont(yaHeiFontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
                        font.setStyle(style);
                        font.setColor(color);
                        if (size>0){
                            font.setSize(size);
                        }
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return font;
                }
            };
//          fontProvider.addFontSubstitute("lowagie", "garamond");
//          fontProvider.setUseUnicode(true);
//          CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
//          HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
//          htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
//          htmlContext.autoBookmark(false);
//          XMLWorkerHelper.getInstance().getDefaultCssResolver(true);

            // step 4
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new FileInputStream(HTML), Charset.forName("UTF-8"),fontProvider);
            // step 5
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值