iText – 使用Java将HTML转换为PDF

jopen 11年前

iText “XML Worker”允许开发人员以一种程序员友好的方式将XML文件转换成PDF文件。iText还可以将包含CSS样式的HTML转换为PDF格式的文档。

 

目标:

  • 实现如何利用iText Java库将HTML文件转换成PDF文档?

Environment & Tools

  • Eclipse (or any other IDE)
  • Maven (optional)

Library:

  • iText 5.4.2

( 1 ) HTML File

  • index.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>      <head>          <title>HTML to PDF</title>          <link href="style.css" rel="stylesheet" type="text/css" />      </head>      <body>          <h1>HTML to PDF</h1>          <p>              <span class="itext">itext</span> 5.4.2 <span class="description"> converting HTML to PDF</span>          </p>          <table>            <tr>                  <th class="label">Title</th>                  <td>iText - Java HTML to PDF</td>              </tr>              <tr>                  <th>URL</th>                  <td>http://hmkcode.com/itext-html-to-pdf-using-java</td>              </tr>          </table>      </body>  </html>
  • style.css
    h1 {    color:#ccc;  }  table tr td{      text-align:center;      border:1px solid gray;      padding:4px;  }  table tr th{      background-color:#84C7FD;      color:#fff;      width: 100px;  }  .itext{      color:#84C7FD;      font-weight:bold;  }  .description{      color:gray;  }

    ( 2 ) Java App

  • App.java
    package com.hmkcode;     import java.io.FileInputStream;  import java.io.FileOutputStream;  import java.io.IOException;  import com.itextpdf.text.Document;  import com.itextpdf.text.DocumentException;  import com.itextpdf.text.pdf.PdfWriter;  import com.itextpdf.tool.xml.XMLWorkerHelper;     public class App  {      public static void main( String[] args ) throws DocumentException, IOException      {        // step 1          Document document = new Document();          // step 2          PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));          // step 3          document.open();          // step 4          XMLWorkerHelper.getInstance().parseXHtml(writer, document,                  new FileInputStream("index.html"));          //step 5           document.close();             System.out.println( "PDF Created!" );      }  }

    ( 3 ) Output “PDF”

    itext-html-pdf-output

    Source Code @ GitHub