Java實現HTML程式碼生成PDF文件
阿新 • • 發佈:2019-01-08
1、IText實現html2pdf,速度快,糾錯能力差,支援中文(要求HTML使用unicode編碼),但中支援一種中文字型,開源。
2、Flying Sauser實現html2pdf,糾錯能力差,支援多種中文字型(部分樣式不能識別),開源。
3、PD4ML實現html2pdf,速度快,糾錯能力強,支援多種中文字型,商業。
(一)IText
依賴jar包:iText-2.0.8.jar、iTextAsian.jar(支援中文)
下面只是一個小的測試案例,如果專案中使用到了該元件可以參考API完成專案組中相應的功能!
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.util.ArrayList;
- import com.lowagie.text.Document;
- import com.lowagie.text.Element;
- import com.lowagie.text.Font;
- import com.lowagie.text.PageSize;
- import com.lowagie.text.Paragraph;
-
import com.lowagie.text.html.simpleparser.HTMLWorker;
- import com.lowagie.text.html.simpleparser.StyleSheet;
- import com.lowagie.text.pdf.BaseFont;
- import com.lowagie.text.pdf.PdfWriter;
- publicclass TestIText{
- publicstaticvoid main(String[] args) {
- TestIText ih = new TestIText();
-
ih.htmlCodeComeFromFile("D://Test//iText.html"
- ih.htmlCodeComeString("Hello中文", "D://Test//iText_2.pdf");
- }
- publicvoid htmlCodeComeFromFile(String filePath, String pdfPath) {
- Document document = new Document();
- try {
- StyleSheet st = new StyleSheet();
- st.loadTagStyle("body", "leading", "16,0");
- PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
- document.open();
- ArrayList p = HTMLWorker.parseToList(new FileReader(filePath), st);
- for(int k = 0; k < p.size(); ++k) {
- document.add((Element)p.get(k));
- }
- document.close();
- System.out.println("文件建立成功");
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
- publicvoid htmlCodeComeString(String htmlCode, String pdfPath) {
- Document doc = new Document(PageSize.A4);
- try {
- PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
- doc.open();
- // 解決中文問題
- BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
- Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
- Paragraph t = new Paragraph(htmlCode, FontChinese);
- doc.add(t);
- doc.close();
- System.out.println("文件建立成功");
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
(二)Flying Sauser
依賴jar包:iText-2.0.8.jar、iTextAsian.jar、core-renderer.jar
預設情況下,core-renderer.jar對中文是不能進行換行的,如果想解決換行問題可以去http://bettereveryday.javaeye.com/blog/611561下載一個jar包,該包對原始碼做了稍加修改.
下面只是一個小的測試案例,如果專案中使用到了該元件可以參考API完成專案組中相應的功能!
- 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;
- publicclass TestFlyingSauser {
- publicstaticvoid main(String[] args) throws Exception {
- demo_1();
- demo_2();
- }
- // 不支援中文
- publicstaticvoid demo_1() throws Exception {
- String inputFile = "D:/Test/flying.html";
- String url = new File(inputFile).toURI().toURL().toString();
- String outputFile = "D:/Test/flying.pdf";
- OutputStream os = new FileOutputStream(outputFile);
- ITextRenderer renderer = new ITextRenderer();
- renderer.setDocument(url);
- renderer.layout();
- renderer.createPDF(os);
- os.close();
- }
- // 支援中文
- publicstaticvoid demo_2() throws Exception {
- String outputFile = "D:/Test/demo_3.pdf";
- OutputStream os = new FileOutputStream(outputFile);
- ITextRenderer renderer = new ITextRenderer();
- ITextFontResolver fontResolver = renderer.getFontResolver();
- fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
- StringBuffer html = new StringBuffer();
- // DOCTYPE 必需寫否則類似於 這樣的字元解析會出現錯誤
- html.append("<!DOCTYPE html PUBLIC /"-//W3C//DTD XHTML 1.0 Transitional//EN/" /"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd/">");
- html.append("<html xmlns=/"http://www.w3.org/1999/xhtml/">").append("<head>")
- .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")
- .append("<mce:style type=/"text/css/"><!--
- body {font-family: SimSun;}
- --></mce:style><style type=/"text/css/" mce_bogus="1">body {font-family: SimSun;}</style>")
- .append("</head>")
- .append("<body>");
- html.append("<div>支援中文!</div>");
- html.append("</body></html>");
- renderer.setDocumentFromString(html.toString());
- // 解決圖片的相對路徑問題
- // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");
- renderer.layout();
- renderer.createPDF(os);
- os.close();
- }
- }
(三)PD4ML
依賴jar包:pd4ml_demo.jar、pd4ml__css2.jar、fonts.jar
下面只是一個小的測試案例,如果專案中使用到了該元件可以參考API完成專案組中相應的功能!
- import java.awt.Insets;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.StringReader;
- import org.zefer.pd4ml.PD4Constants;
- import org.zefer.pd4ml.PD4ML;
- publicclass Converter {
- publicstaticvoid main(String[] args) throws Exception {
- Converter converter = new Converter();
- converter.generatePDF_2(new File("D:/Test/demo_ch_pd4ml_a.pdf"), "D:/Test/a.htm");
- File pdfFile = new File("D:/Test/demo_ch_pd4ml.pdf");
- StringBuffer html = new StringBuffer();
- html.append("<html>")
- .append("<head>")
- .append("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/" />")
- .append("</head>")
- .append("<body>")
- .append("<font face=/"KaiTi_GB2312/">")
- .append("<font color='red' size=22>顯示中文</font>")
- .append("</font>")
- .append("</body></html>");
- StringReader strReader = new StringReader(html.toString());
- converter.generatePDF_1(pdfFile, strReader);
- }
- // 手動構造HTML程式碼
- publicvoid generatePDF_1(File outputPDFFile, StringReader strReader) throws Exception {
- FileOutputStream fos = new FileOutputStream(outputPDFFile);
- PD4ML pd4ml = new PD4ML();
- pd4ml.setPageInsets(new Insets(20, 10, 10, 10));
- pd4ml.setHtmlWidth(950);
- pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
- pd4ml.useTTF("java:fonts", true);
- pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312");
- pd4ml.enableDebugInfo();
- pd4ml.render(strReader, fos);
- }