利用Flying Saucer 和 iText 實現HTMl轉PDF(java)

來源:互聯網
上載者:User
文章目錄
  • Flying Saucer和iText介紹:
  • 產生簡單的PDF
  • 用Fly產生內容
  • 在服務端建立PDF

PDF是目前為止最流行的文檔格式之一。通常情況下,想要建立一個PDF文檔,需要使用Adobe的API來產生,但這非常麻煩。為了能方便的將HTML(XHTML)產生PDF文檔,下面介紹兩個開源的java庫:Flying Saucer和iText。

Flying Saucer和iText介紹:

Flying Saucer(或者叫xhtmlrender project on java.net)是一個基於iText的開源java庫,能夠輕鬆的將html(帶css2.1)產生pdf。

iText是一個產生PDF文檔的開源java庫,能夠動態從XML或者資料庫產生PDF,同時它具備PDF文檔的絕大多數屬性(比如加密……),支援java,C#等。

產生簡單的PDF

下面我們首先建立一個簡單的帶css的html,代碼如下:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <title>My First Document</title>        <style type="text/css"> b { color: green; } </style>    </head>    <body>        <p>            <b>Greetings Earthlings!</b>            We've come for your Java.        </p>    </body></html>

接下來產生一個pdf
package oliver.itext.html2pdf;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import org.xhtmlrenderer.pdf.ITextRenderer;import com.lowagie.text.DocumentException;public class FirstDoc{    public static void main(String[] args) throws DocumentException, IOException    {        String path = System.getProperty("user.dir") + "/src/";        String inputFile = path + "samples/firstdoc.html";        String url = new File(inputFile).toURI().toURL().toString();        String outputFile = path + "outputs/fistdoc.pdf";        OutputStream os = new FileOutputStream(outputFile);        ITextRenderer render = new ITextRenderer();        render.setDocument(url);        render.layout();        render.createPDF(os);        os.close();    }}
結果如下:用Fly產生內容

下面的我們先用StringBuilder產生一個HTML的字串,然後用DOM解析,產生PDF。

package com.sankuai.meituan.ct.doamin;import java.io.FileOutputStream;import java.io.OutputStream;import java.io.StringBufferInputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import  org.xhtmlrenderer.pdf.ITextRenderer;@SuppressWarnings("deprecation")public class OneHundredBottles{    public static void main(String[] args) throws Exception    {        String path =System.getProperty("user.dir")+"/src/";        StringBuffer buf = new StringBuffer();        buf.append("<html>");        // put in some style        buf.append("<head><style language='text/css'>");        buf.append("h3 { border: 1px solid #aaaaff; background: #ccccff; ");        buf.append("padding: 1em; text-transform: capitalize; font-family: sansserif; font-weight: normal;}");        buf.append("p { margin: 1em 1em 4em 3em; } p:first-letter { color: red; font-size: 150%; }");        buf.append("h2 { background: #5555ff; color: white; border: 10px solid black; padding: 3em; font-size: 200%; }");        buf.append("</style></head>");        // generate the body        buf.append("<body>");        buf.append("<p><img src='"+path+"samples/100bottles.jpg'/></p>");        for(int i=99; i>0; i--) {            buf.append("<h3>"+i+" bottles of beer on the wall, "                    + i + " bottles of beer!</h3>");            buf.append("<p>Take one down and pass it around, "                    + (i-1) + " bottles of beer on the wall</p>/n");        }        buf.append("<h2>No more bottles of beer on the wall, no more bottles of beer. ");        buf.append("Go to the store and buy some more, 99 bottles of beer on the wall.</h2>");        buf.append("</body>");        buf.append("</html>");        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();        Document doc = builder.parse(new StringBufferInputStream(buf.toString()));        ITextRenderer renderer = new ITextRenderer();        renderer.setDocument(doc, null);        String outputFile = path+"outputs/100bottles.pdf";        OutputStream os = new FileOutputStream(outputFile);        renderer.layout();        renderer.createPDF(os);        os.close();    }}
效果如下:

在服務端建立PDF

下面展示在servlet裡面建立pdf

public class PDFServlet extends HttpServlet {        protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        response.setContentType("application/pdf");        StringBuffer buf = newStringBuffer();        buf.append("<html>");        String css = getServletContext().getRealPath("/PDFservlet.css");       // put in some style        buf.append("<head><link rel='stylesheet' type='text/css' "+"href='"+css+"' media='print'/></head>");       ... //generate the rest of the HTML       // parse our markup into an xml Document        try{            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();            Document doc = builder.parse(new StringBufferInputStream(buf.toString()));            ITextRenderer renderer = new ITextRenderer();            renderer.setDocument(doc, null);            renderer.layout();            OutputStream os = response.getOutputStream();            renderer.createPDF(os);            os.close();        } catch(Exception ex) {            ex.printStackTrace();        }    }

原文地址:http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.