java使用xmlWorkerHelper将html转pdf

1、引入maven包

         <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.12</version>
         </dependency>

        <dependency>
                <groupId>com.itextpdf.tool</groupId>
                <artifactId>xmlworker</artifactId>
                <version>5.5.8</version>
        </dependency>

2、编码示例:

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class XmlWorkerHelperUtil{

    public static void htmlToPDF(String htmlString,String pdfPath) {
        try {
            Document document = new Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream(pdfPath));
            document.open();
            document.addAuthor("pdf作者");
            document.addCreator("pdf创建者");
            document.addSubject("pdf主题");
            document.addCreationDate();
            document.addTitle("pdf标题,可在html中指定title");
            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
            InputStream inputStream=null;
            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlString.getBytes("UTF-8")),inputStream,Charset.forName("UTF-8"),new AsianFontProvider());
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import com.itextpdf.text.Font;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;

public class AsianFontProvider extends XMLWorkerFontProvider {

    @Override
    public Font getFont(final String fontname, String encoding, float size, final int style) {
        String fntname = fontname;
        if (fntname == null) {
           /*使用的windows里的宋体,可将其文件放资源文件中引入
            *请确保simsun.ttc字体在windows下支持
            *我是将simsun.ttc字体打进maven的jar包中使用
            */
            fntname = "fonts/simsun.ttc";
        }
        if (size == 0) {
            size = 4;
        }
        return super.getFont(fntname, encoding, size, style);
    }
}

3、字体乱码问题:

 html字符串指定utf-8字体,指定body标签样式为SimSun,若内容有设定字体样式的也一并修改为SimSun。

<head>
<title>XXX合同</title>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Type" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
<style>
body{font-family:SimSun}
</style>
</head>

4、针对SimSun的说明

fonts/simsun.ttc字体,为宋体。这是存放于maven的jar中的资源文件。

两种方式可以保证其在linux服务器上正常运行。

1、将simsun.ttc文件作为maven组件资源白名单文件打成jar包(我目前使用的这种)

2、将simsun.ttc文件用root用户上传至linux服务器上,大概是/usr/share/font目录下。

     fc-cache 刷新字体缓存

     fc-list 查看字体列表

 

展开阅读全文

没有更多推荐了,返回首页