iText – 使用Java將HTML轉換為PDF

jopen 11年前發布 | 3M 次閱讀 iText PDF工具包

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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!