最簡單 iText 的 PDF 生成方案(含中文解決方案)HTML 轉爲 PDF

ITEXT 的功能和簡介這裏就很少說了,直接帶你們作一遍:html

一段可運行的代碼比說不少廢話強得多java


S1 :首先下載 JAR 包ui

    CORE 包:http://sourceforge.net/projects/itext/files/
spa

    XML  包:http://sourceforge.net/projects/xmlworker/files/
.net


S2:建立 HTML 文檔(將要使用的 HTML 文檔素材)code

    

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body screen_capture_injected="true" ryt11773="1">
	<p>
		<span style="font-size:12.0pt; font-family:MS Mincho">長空</span> <span
			style="font-size:12.0pt; font-family:Times New Roman,serif">(Broken
			Sword),</span> <span style="font-size:12.0pt; font-family:MS Mincho">秦王殘劍</span>
		<span style="font-size:12.0pt; font-family:Times New Roman,serif">(Flying
			Snow),</span> <span style="font-size:12.0pt; font-family:MS Mincho">飛雪</span>
		<span style="font-size:12.0pt; font-family:Times New Roman,serif">(Moon),
		</span> <span style="font-size:12.0pt; font-family:MS Mincho">如月</span> <span
			style="font-size:12.0pt; font-family:Times New Roman,serif">(the
			King), and</span> <span style="font-size:12.0pt; font-family:MS Mincho">秦王</span>
		<span style="font-size:12.0pt; font-family:Times New Roman,serif">(Sky).</span>
	</p>
</body>
</html>


S3: 引入 JAR 包 ,編寫JAVA 轉換代碼xml

package com.zhouqian.itext;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
 
 
public class D07_ParseHtmlAsian {
 
	
	
    public static final String HTML = "E:/Dropbox/document/java/designPattern/data/hero.html";
    public static final String DEST = "E:/Dropbox/document/java/designPattern/data/hero.pdf";
 
    /**
     * Creates a PDF with the words "Hello World"
     * @param file
     * @throws IOException
     * @throws DocumentException
     */
    public void createPdf(String file) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new FileInputStream(HTML), Charset.forName("UTF-8"));
        // step 5
        document.close();
    }
 
    /**
     * Main method
     */
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new D07_ParseHtmlAsian().createPdf(DEST);
    }
}

    

S4:在指定路徑下就能夠獲得 PDF 結果htm

    


若是你們有不明白的能夠留言問我,一同進步文檔

相關文章
相關標籤/搜索