网页生成PDF

看了 介绍一个PDF的生成方案
由于是高手所写,难免简略一下,所以自己写一个简单好理解的.
 
需要的jar包: core-renderer.jar 和 iText-2.0.8.jar , jar包 下载
一个html页面
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >    
< html xmlns ="http://www.w3.org/1999/xhtml" >    
< head >    
< meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" />    
< title >test </title>    
< style type ="text/css" >        
body {    
        font-family: SimSun;        
        font-size:22px;    
        font-style:italic;    
        font-weight:bold;    
        color:#00F;    
}    
</style> </head>    
    
< body >    
显示中文dsklahsdal;das哈哈哈哈 < br />
上多哈考虑的哈    
</body>    
</html>    
 
生成PDF
package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;
  
public class ITextRendererTest {    
         public static void main(String[] args) throws Exception {    
                String inputFile = "WebRoot/a.html";    
                String url = new File(inputFile).toURI().toURL().toString();    
                String outputFile = "WebRoot/a.pdf";    
                System.out.println(url);
                OutputStream os = new FileOutputStream(outputFile);    
                ITextRenderer renderer = new ITextRenderer();    
                renderer.setDocument(url);    
    
                 // 解决中文支持问题    
                ITextFontResolver fontResolver = renderer.getFontResolver();    
                fontResolver.addFont( "C:/Windows/Fonts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);    
    
                 // 解决图片的相对路径问题    
//                renderer.getSharedContext().setBaseURL("file:/D:/z/temp/");    
                    
                renderer.layout();    
                renderer.createPDF(os);    
                    
                os.close();    
        }    
}    
pdf效果
网页生成PDF

 

本文出自 “wIsper 把技术做成艺术” 博客,请务必保留此出处http://lichen.blog.51cto.com/697816/264297

你可能感兴趣的:(职场,网页,pdf,休闲)