java使用flySaucer实现html转pdf

1、引入maven包

           
                com.itextpdf
                itextpdf
                5.5.12
           


           
                org.xhtmlrenderer
                flying-saucer-pdf-itext5
                9.1.6
           

 

2、FlySaucerUtil示例

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FlySaucerUtil {

    /**
     *将htmlCode转换为pdf文件
     *
     * @param htmlCode  其中body体必须包含字体样式设置,否则无法识别汉字。
     *                    字体样式设置举例:style='font-family:SimSun'
     * @param pdfPath 实际存在的全路径pdf文件
     */
    public static void htmlCodeToPdf(String htmlCode, String pdfPath) {
        OutputStream os =null;
        try {
            os=new FileOutputStream(pdfPath);
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.setDocumentFromString(htmlCode);
            renderer.layout();
            renderer.createPDF(os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            if(null!=os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3、字体乱码问题:

 html字符串指定utf-8字体,指定body标签样式为SimSun。

SimSun是windows里的宋体,可将其文件放资源文件中引入。


XXX合同






 

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 查看字体列表

你可能感兴趣的:(java开发)