最近試著用iText將HTML資料,轉成PDF,遇到一些問題,包括:

1. iText 5.4 如何將HTML轉PDF

2. HTML 包含中文,如何轉成PDF後能正常顯示?

3.在Unix平台,需另外處理字型檔

網路上有很多人分享,可惜都是 iText 2.X版的,如果是用新版的 iText 例如 5.4版,這些方法是不適用的,

( 新版的 iText package名稱已改成: com.itextpdf.xxx ,舊版的是:com.lowagie.xxx )

因此將方法整理摘要記下來分享。

 

 1.首先,需下載:itext-5.4.5.zip ,  xmlworker-5.4.5.zip  解開後,程式import裡面需要的LIB(jar檔)。 

  iText 5.4 需透xmlworker,以XHTML Parser解析HTML。

2. 確認字型檔存放於Unix路徑下,具有程式執行者可以讀取的Permission

 

Java Sample:

   //Initial Document Object

  Document document = new Document();

   //Initial PdfWriter, Assign document obj, and PDF ouput path

  PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(

  "/hello/pdf/xxxx.pdf"));

   document.open();

    //中文字型檔路徑

   String fontPath =  "/pdf/font/mingliu.ttc"; 

   //自訂字型物件

   XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(fontPath);

   FontFactory.setFontImp(fontImp);

    //註冊FontFactory,定義Font Alias Name = mingliu

   FontFactory.register(fontPath, "mingliu");

    //Check是否註冊字型成功

   System.out.println("IS mingliu?==="+ FontFactory.isRegistered("mingliu"));

    //Initial HTML轉換物件

   XMLWorkerHelper xmlWorker =XMLWorkerHelper.getInstance();

   //Parse HTML字串,要把自訂的FontProvider傳入

   xmlWorker.parseXHtml(writer, document,

       new ByteArrayInputStream(htmlStr.getBytes("BIG5")), null,  

       Charset.forName("BIG5"),  fontImp);

   if(document != null) {
      document.close();
    }

 

    System.out.println("PDF Created!");

 

   //=========Finished=================

 

HTML注意事項:

HTML要宣告與PDF相同的字型,如上述的Font alias: mingliu

 

簡單一點的作法,直接在body tag裡宣告Style,或者在外部宣告也可以。

    <body STYLE=\"font-family: mingliu; font-size:10pt\">"

 

 

重要參考資料:

iText API: http://api.itextpdf.com/itext/

iText XML Worker API: http://api.itextpdf.com/xml/ 

使用itext将html生成pdf中文换行问题解决方案2

 http://blog.csdn.net/jys1109/article/details/10066747

 

  

   

 

 

 

arrow
arrow
    文章標籤
    iText PDF JAVA
    全站熱搜

    psalter 發表在 痞客邦 留言(1) 人氣()