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

          常用鏈接

          統計

          IT技術鏈接

          保險相關

          友情鏈接

          基金知識

          生活相關

          最新評論

          iText JSP中生成PDF(入門)

          iText簡介

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

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

          可參考資料 :  

          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實例

          以下是上述教程中一個最簡單的例子,這個例子刻畫了通過iText生成PDF文件的一般程序框架。讀者只需要在document.open();和document.close();兩條語句中間加入自己希望放在PDF文件中的內容即可。該例子只在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();

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

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

          二。如何使用jsp、servlet輸出iText生成的pdf?
             如果每次都在服務端生成一個PDF文件給用戶,不僅麻煩,而且浪費服務器資源,最好的方法就是以二進制流的形式輸送到客戶端。
          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也是需要這個包的。然后定義中文字體:

              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;
               }


          我將產生中文字體封裝在方法內,自定義一個段落PDFParagraph繼承自Paragraph,默認使用中文字體:

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


          使用的時候就可以簡化了:

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


          四。如何設置PDF橫向顯示和打印?

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


          五。如何設置跨行和跨列?

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

          六。如何設置單元格邊界寬度?

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

          七。如何設置表頭?
          希望每一頁都有表頭,可以通過設置表頭來實現。對于PdfPTable類來說,可以這樣設置:

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


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

          table.endHeaders();


          八。如何設置列寬?

          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);


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

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

          cell.setHorizontalAlignment(Element.ALIGN_CENTER);



          轉義符\n實現。在我的這個應用中,因為數據庫取出的數據是為了顯示在html上的,所以有很多<br>標簽,可以使用正則表達式替換成"\n"

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


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

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

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

          posted on 2009-08-12 09:48 鴻雁 閱讀(2338) 評論(0)  編輯  收藏 所屬分類: IT技術相關

          主站蜘蛛池模板: 平谷区| 油尖旺区| 翁源县| 南城县| 阿城市| 普宁市| 全州县| 宿迁市| 凯里市| 海城市| 贵州省| 邢台县| 收藏| 饶阳县| 漯河市| 阿合奇县| 辉南县| 哈尔滨市| 柳州市| 英山县| 保靖县| 上高县| 平陆县| 和龙市| 任丘市| 庆阳市| 黄石市| 三亚市| 长兴县| 同心县| 鄄城县| 且末县| 公安县| 肃北| 红安县| 康乐县| 罗定市| 铜川市| 乌鲁木齐县| 达拉特旗| 临西县|