网页生成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

本文转自chainli 51CTO博客,原文链接:http://blog.51cto.com/lichen/264297,如需转载请自行联系原作者
上一篇:查看centos服务器硬盘状态信息


下一篇:linux查询内存真是利用率