1. 程式人生 > >Itext 實現 html轉換成pdf

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"/ >