html转pdf

itextpdf是常用html转pdf的工具,但对界面布局的要求较高(比如使用div布局如position:absolute支持不好),结合flying saucer,能完美支持,整个转换过程:
vm---->html---->pdf

vm模板,其中font-family很重要(方正兰亭黑),用于支持中文(底下会讲到)
<!DOCTYPE html>
<html>
 <head>
<meta charset="utf-8" />
  <style type="text/css">
	body{
	font-family: "FZLanTingHei-R-GB18030"
	}
            .shape{ position:absolute; overflow: hidden; }
            .shape img{ width:100%;}
            .contenteditable{ display: table-cell; }
            .text-shape{ width: 100%; height: 100%; display: table; padding:0; cursor: default;  position: absolute;}
			  .vertical-line {
      width: 1px;
      height: 30mm;
      background: #000;
    }
            </style>
 </head>
 <body>
  <div style="position: relative;width: 100mm;height:150mm;">
   <div id="element_page_C7A27138B84E839E">


vm转html
public String initVelocityEngine() {
		VelocityEngine ve = new VelocityEngine();  
		Properties p = new Properties(); 
		p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, TestVmToPdf.class.getResource("/tpl").getPath());
        ve.init(p);  
        Template template = ve.getTemplate("test.vm");
VelocityContext context = new VelocityContext(); 
context.put("username", "张三");
StringWriter writer = new StringWriter();  
        template.merge(context, writer);
        return writer.toString();
	}


html转pdf,其中使用的字体要与vm中的font-family对应,以便支持中文
public void createPDFFromString(String html, String pdf)
            throws IOException, DocumentException {
        String outputFile = pdf;  
        OutputStream os = new FileOutputStream(outputFile);  
  
        ITextRenderer renderer = new ITextRenderer();  
        // PDFEncryption pdfEncryption = new  
        // PDFEncryption(null,null,PdfWriter.ALLOW_PRINTING);  
        // renderer.setPDFEncryption(pdfEncryption); //只有打印权限的  
        //renderer.setDocument(new File(url));  
        renderer.setDocumentFromString(html);
  
        // 解决中文问题  
        ITextFontResolver fontResolver = renderer.getFontResolver();  
        try {  
            fontResolver.addFont("/configinfo/FZLTH_GB18030.TTF",  
                    BaseFont.IDENTITY_H, false);  
        } catch (DocumentException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } 
  
        renderer.layout();  
        try {  
            renderer.createPDF(os);  
        } catch (DocumentException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } 
    }


中文支持的原理:
flying saucer、会首先确认font family,如果页面设置,则取页面中的,否则取程序默认的CSSName.FONT_FAMILY(实际上就是serif)。然后,根据font family从org.xhtmlrenderer.pdf.ITextFontResolver对象中的_fontFamilies集合中取得字体,若集合中不存在对应的字体则再取默认(即Serif)
引自:http://blog.csdn.net/adverse/article/details/6105355

其他生产pdf方案,参见:
http://blog.csdn.net/zdtwyjp/article/details/5769353

猜你喜欢

转载自dien.iteye.com/blog/2314395