Itext 实现 html转换成pdf


需要的jar包: core-renderer.jar 和 iText-2.0.8.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> 

 

Java代码

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;

/**    
* TODO class description *    
*   
* @author pcwang   
*   
* @version 1.0, 上午11:03:26    create $Id$   
*/    
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();    
        }    
}  

 

注意事项:

<!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 "> 
(1)头文件必须这个,否则会报以下错误:
             错误:“The declaration for the entity "HTML.Version" must end with '>'.”
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
(2)charset 必须是UTF-8,否则会报以下错误:
             错误:“Invalid byte 1 of 1-byte UTF-8 sequence.”
(3)需要定一个样式:body {font-family: SimSun};
(4)html页面必须严格遵循, 该打引号就要打引号
             错误:cellpadding=0 ,border=1"
(5)不要引用无效的链接
  <link rel="stylesheet" type="text/css" href="XX/ll.css"/ >
 <link rel="stylesheet" type="text/css" href="XX/main.css"/

你可能感兴趣的:(html,pdf,itext)