The important thing in life is to have a great aim , and the determination

          常用鏈接

          統(tǒng)計(jì)

          IT技術(shù)鏈接

          保險(xiǎn)相關(guān)

          友情鏈接

          基金知識(shí)

          生活相關(guān)

          最新評(píng)論

          iText JSP中生成PDF(入門)

          iText簡(jiǎn)介

            iText是一個(gè)開放源碼的Java類庫(kù),可以用來方便地生成PDF文件。大家通過訪問http://sourceforge.net/project/showfiles.php?group_id=15255&release_id=167948下載最新版本的類庫(kù),下載完成之后會(huì)得到一個(gè).jar包,把這個(gè)包加入JDK的classpath即可使用。如果生成的PDF文件中需要出現(xiàn)中文、日文、韓文字符,則還需要通過訪問http://itext.sourceforge.net/downloads/iTextAsian.jar下載iTextAsian.jar包。

            關(guān)于iText類庫(kù)的使用,http://www.lowagie.com/iText/tutorial/index.html有比較詳細(xì)的教程。該教程從入門開始,比較系統(tǒng)地介紹了在PDF文件中放入文字、圖片、表格等的方法和技巧。讀完這片教程,大致就可以做一些從簡(jiǎn)單到復(fù)雜的PDF文件了。不過,試圖通過教程解決在生成PDF文件過程中遇到的所有困難無(wú)疑是一種奢望。所以,閱讀iText的api文檔顯得非常重要。讀者在下載類庫(kù)的同時(shí),也可以下載類庫(kù)的文檔。

          可參考資料 :  

          http://dev.csdn.net/article/62/62119.shtm       http://myowndream.blog.com.cn/archives/2007/2089386.shtml
          http://tag.csdn.net/tag/itext.xml

          一  HelloWorld實(shí)例

          以下是上述教程中一個(gè)最簡(jiǎn)單的例子,這個(gè)例子刻畫了通過iText生成PDF文件的一般程序框架。讀者只需要在document.open();和document.close();兩條語(yǔ)句中間加入自己希望放在PDF文件中的內(nèi)容即可。該例子只在PDF文件中加了“Hello World“一行文字。

          Document document = new Document();

          try{
              PdfWriter.getInstance(document, new FileOutputStream ("Chap0101.pdf"));

              document.open();

              document.add(new Paragraph("Hello World"));
          }catch(DocumentException de){
               System.err.println(de.getMessage());
          }catch(IOException ioe){
               System.err.println(ioe.getMessage());
          }
           
          document.close();

          可以看到一個(gè)PDF文件的輸出,總共只需要5個(gè)步驟
          a.創(chuàng)建一個(gè)Document實(shí)例
            Document document = new Document();
          b.將Document實(shí)例和文件輸出流用PdfWriter類綁定在一起
            PdfWriter.getInstance(document,new FileOutputStream("HelloWorld.pdf"));
          c.打開文檔
            document.open();
          d.在文檔中添加文字
            document.add(new Paragraph("Hello World"));
          e.關(guān)閉文檔
            document.close();
          這樣5個(gè)步驟,就可以生成一個(gè)PDF文檔了。

          然而在PDF中指定文字、圖畫、表格的位置是一件非常麻煩的事情。除了不斷地在程序中修改位置、然后運(yùn)行程序、生成PDF文件、觀察元素在PDF中的位置是否合理這樣的過程以外,似乎還沒有其它更好的方法。

          二。如何使用jsp、servlet輸出iText生成的pdf?
             如果每次都在服務(wù)端生成一個(gè)PDF文件給用戶,不僅麻煩,而且浪費(fèi)服務(wù)器資源,最好的方法就是以二進(jìn)制流的形式輸送到客戶端。
          1)JSP輸出:

          <%@ page import="java.io.*,java.awt.Color,com.lowagie.text.*,com.lowagie.text.pdf.*"%>
          <%
           response.setContentType( "application/pdf" );
           Document document = new Document();
           ByteArrayOutputStream buffer = new ByteArrayOutputStream();
           PdfWriter writer=PdfWriter.getInstance( document, buffer );

           document.open();

           document.add(new Paragraph("Hello World"));

           document.close();

           DataOutput output = new DataOutputStream( response.getOutputStream() );
           byte[] bytes = buffer.toByteArray();
           response.setContentLength(bytes.length);
           for( int i = 0; i < bytes.length; i++ ){
            output.writeByte( bytes[i] );
           }

          %>

          2)servlet輸出,稍微改造下就可以使用在struts中:

          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;
          import com.lowagie.text.*;
          import com.lowagie.text.pdf.*;

          public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{

            Document document = new Document(PageSize.A4, 36,36,36,36);
            ByteArrayOutputStream ba = new ByteArrayOutputStream();

            try{
             PdfWriter writer = PdfWriter.getInstance(document, ba);

             document.open();

             document.add(new Paragraph("Hello World"));
            }catch(DocumentException de){
             de.printStackTrace();
             System.err.println("A Document error:" +de.getMessage());
              }

            document.close();

            response.setContentType("application/pdf");
            response.setContentLength(ba.size());
            ServletOutputStream out = response.getOutputStream();
            ba.writeTo(out);
            out.flush();
          }

          三。如何輸出中文?
               首先需要下載iTextAsian.jar包,可以到iText的主站上下,ireport也是需要這個(gè)包的。然后定義中文字體:

              private static final Font getChineseFont() {
                   Font FontChinese
          = null;
                  
          try {
                       BaseFont bfChinese
          = BaseFont.createFont("STSong-Light",
                              
          "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                       FontChinese
          = new Font(bfChinese, 12, Font.NORMAL);
                   }
          catch (DocumentException de) {
                       System.err.println(de.getMessage());
                   }
          catch (IOException ioe) {
                       System.err.println(ioe.getMessage());
                   }
                  
          return FontChinese;
               }


          我將產(chǎn)生中文字體封裝在方法內(nèi),自定義一個(gè)段落PDFParagraph繼承自Paragraph,默認(rèn)使用中文字體:

          class PDFParagraph extends Paragraph {
                  
          public PDFParagraph(String content) {
                      
          super(content, getChineseFont());
                   }
               }


          使用的時(shí)候就可以簡(jiǎn)化了:

          Paragraph par = new PDFParagraph("你好");


          四。如何設(shè)置PDF橫向顯示和打印?

          Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定義A4頁(yè)面大小
          rectPageSize = rectPageSize.rotate();// 加上這句可以實(shí)現(xiàn)A4頁(yè)面的橫置
          Document doc = new Document(rectPageSize,50,50,50,50);//4個(gè)參數(shù),設(shè)置了頁(yè)面的4個(gè)邊距


          五。如何設(shè)置跨行和跨列?

          使用PdfPTable和PdfPCell 是沒辦法實(shí)現(xiàn)跨行的,只能跨列,要跨行使用com.lowagie.text.Table和com.lowagie.text.Cell類,Cell類有兩個(gè)方法:setRowspan()和setColspan()。

          六。如何設(shè)置單元格邊界寬度?

          Cell類的系列setBorderWidthXXXX()方法,比如setBorderWidthTop(),setBorderWidthRight()等

          七。如何設(shè)置表頭?
          希望每一頁(yè)都有表頭,可以通過設(shè)置表頭來實(shí)現(xiàn)。對(duì)于PdfPTable類來說,可以這樣設(shè)置:

          PdfPTable table = new PdfPTable(3);
          table.setHeaderRows(
          2); // 設(shè)置了頭兩行為表格頭


          而對(duì)于om.lowagie.text.Table類,需要在添加完所有表頭的單元格后加上一句代碼:

          table.endHeaders();


          八。如何設(shè)置列寬?

          Table table = new Table(8);
          float[] widths = { 0.10f, 0.15f, 0.21f, 0.22f, 0.08f, 0.08f, 0.10f,
                              
          0.06f };
          table.setWidths(widths);


          上面的代碼設(shè)置了一個(gè)有8列的表格,通過一個(gè)float數(shù)組設(shè)置列寬,這里是百分比。

          九。單元格內(nèi)段落文字居中和換行?
          居中通過Cell類來設(shè)置,一開始我以為設(shè)置段落對(duì)齊就可以了,沒想到是需要設(shè)置單元格:

          cell.setHorizontalAlignment(Element.ALIGN_CENTER);



          轉(zhuǎn)義符\n實(shí)現(xiàn)。在我的這個(gè)應(yīng)用中,因?yàn)閿?shù)據(jù)庫(kù)取出的數(shù)據(jù)是為了顯示在html上的,所以有很多<br>標(biāo)簽,可以使用正則表達(dá)式替換成"\n"

          "<br>1.測(cè)試<br>2.測(cè)試2".replaceAll("<br>|</br>","\n");


          十。如何顯示頁(yè)碼?
          復(fù)雜的頁(yè)碼顯示和水印添加,需要使用到PdfPageEventHelper、PdfTemplate等輔助類,具體的例子參見iText的文檔,如果只是為了簡(jiǎn)單的顯示頁(yè)數(shù),可以使用下面的代碼:

                       HeaderFooter footer = new HeaderFooter(new Phrase("頁(yè)碼:",getChineseFont()), true);
                       footer.setBorder(Rectangle.NO_BORDER);
                       document.setFooter(footer);
                       document.open();

          你可能注意到了,添加footer需要在document.open之前。

          posted on 2009-08-12 09:48 鴻雁 閱讀(2337) 評(píng)論(0)  編輯  收藏 所屬分類: IT技術(shù)相關(guān)

          主站蜘蛛池模板: 当阳市| 台湾省| 博客| 东阿县| 息烽县| 招远市| 怀安县| 海南省| 渭源县| 疏勒县| 密山市| 松原市| 昆山市| 庆元县| 兴山县| 青田县| 西峡县| 潢川县| 象山县| 阿拉善盟| 繁峙县| 哈密市| 简阳市| 雷州市| 合肥市| 台东市| 日喀则市| 巩留县| 黎平县| 珲春市| 太保市| 武夷山市| 阳原县| 宁阳县| 洪雅县| 土默特左旗| 宕昌县| 湟源县| 冀州市| 邹平县| 南陵县|