Cyh的博客

          Email:kissyan4916@163.com
          posts - 26, comments - 19, trackbacks - 0, articles - 220

          操作PDF文件

          Posted on 2009-05-30 23:38 啥都寫點(diǎn) 閱讀(1016) 評論(1)  編輯  收藏 所屬分類: J2SE
          關(guān)鍵技術(shù):
          • 一個(gè)Excel文檔從大到小可以分成如下幾個(gè)要素:文檔、章節(jié)、小節(jié)、段落、表格、列表。
          • com.lowagie.text.Document表示PDF文檔。必須為它創(chuàng)建一個(gè)PDF寫入器,即com.lowagie.text.pdf.Pdfwriter對象,寫入器的作用是將Document對象與目標(biāo)文件關(guān)聯(lián)起來。調(diào)用Document的open方法便打開與目標(biāo)文件的連接;Document的add方法為文檔添加章節(jié)。
          • com.lowagie.text.Chapter表示PDF文檔中的章節(jié)。它的setTitle方法設(shè)置章節(jié)的標(biāo)題;setNumberDepth方法設(shè)置小節(jié)的編號(hào)級別;add方法為小節(jié)中添加內(nèi)容,可以是段落、表格、列表等。
          • com.lowagie.text.Paragraph表示PDF文檔中的段落。可以指定段落的對齊方式、字體等屬性。
          • com.lowagie.text.Table表示PDF文檔中的表格。通過它的一系列set方法可以設(shè)置表格的樣式,比如邊框大小、顏色等;addCell方法為表格添加單元格,單元格是com.lowagie.text.Cell對象。
          • com.lowagie.text.List表示PDF文檔中的列表。com.lowagie.text.ListItem表示列表中項(xiàng)。通過List的add方法將列表項(xiàng)添加到列表中。
            使用pdfbox的類庫讀取PDF文檔的關(guān)鍵技術(shù)點(diǎn)如下:
          • org.pdfbox.pdfparser.PDFParser用于解析PDF文檔,它的parse方法對PDF文件輸入流進(jìn)行解析;getPDDocument方法獲得解析后得到的PDF文檔對象,是一個(gè)org.pdfbox.pdmodel.PDDocument對象。
          • org.pdfbox.util.PDFTextStripper是分析PDF文檔對象中文本的工具類,它的getText方法能夠提取PDF文檔對象中包含的文本。

          package book.io;

          import java.awt.Color;
          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.IOException;

          import org.pdfbox.pdfparser.PDFParser;
          import org.pdfbox.pdmodel.PDDocument;
          import org.pdfbox.util.PDFTextStripper;

          import com.lowagie.text.Cell;
          import com.lowagie.text.Chapter;
          import com.lowagie.text.Document;
          import com.lowagie.text.DocumentException;
          import com.lowagie.text.Font;
          import com.lowagie.text.FontFactory;
          import com.lowagie.text.List;
          import com.lowagie.text.ListItem;
          import com.lowagie.text.PageSize;
          import com.lowagie.text.Paragraph;
          import com.lowagie.text.Section;
          import com.lowagie.text.Table;
          import com.lowagie.text.pdf.BaseFont;
          import com.lowagie.text.pdf.PdfWriter;

          /**
           * 很多應(yīng)用程序要求動(dòng)態(tài)生成 PDF 文檔。這類應(yīng)用程序包括銀行生成用于電子郵件投遞的客戶報(bào)表,到讀者購買特定圖書章節(jié)并以 PDF 格式接收這些文檔。例子羅列下去是很多的。在本文中,將使用 iText Java 庫生成 PDF 文檔,并引導(dǎo)您完成一個(gè)示例應(yīng)用程序,以使您能夠更好地理解和使用 iText。 
          iText 是 Lowagie.com 站點(diǎn)(請參閱 參考資料)免費(fèi)提供的 Java 庫。iText 庫的功能很強(qiáng)大,支持 HTML、RTF 和 XML 文檔的生成,此外還能夠生成 PDF 文檔。可以從多種字體中選擇文檔中所使用的字體。同時(shí),iText 的結(jié)構(gòu)允許使用相同的代碼生成以上任意類型的文檔。
           * 
          http://www.lowagie.com/iText/
           * iText API:近距離觀察
          com.lowagie.text.Document 是生成 PDF 的主要的類。它是需要使用的第一個(gè)類。一旦開始創(chuàng)建文檔,將需要一個(gè)寫入器向文檔中寫入內(nèi)容。com.lowagie.text.pdf.PdfWriter 就是一個(gè) PDF 寫入器。下面列出了通常需要使用的類:
          com.lowagie.text.Paragraph —— 這個(gè)類表示一個(gè)縮進(jìn)的段落。 
          com.lowagie.text.Chapter —— 這個(gè)類表示 PDF 文檔中的章節(jié)。使用 Paragraph 作為題目并使用 int 作為章節(jié)號(hào)碼來創(chuàng)建它。
          com.lowagie.text.Font —— 這個(gè)類包含了全部的字體規(guī)范,例如字體、大小、樣式和顏色。各種字體都在這個(gè)類中聲明為靜態(tài)常數(shù)。 
          com.lowagie.text.List —— 這個(gè)類表示一個(gè)列表,按順序包含許多 ListItems。
          com.lowagie.text.Table —— 這個(gè)類表示包含單元格的表,單元格有序地排列在矩陣中。
           
          */
          public class PDFFile {

              
          /**
               * 寫PDF文件,展示了PDF文檔、章節(jié)、小節(jié)、字體、段落、表格、列表的使用
               * 最后展示如何使用寫入中文。
               * 
          @param fileName
               
          */
              
          public void writePDF(String fileName) {
                  File file 
          = new File(fileName);
                  FileOutputStream out 
          = null;

                  
          try {
                      
          //(1)實(shí)例化文檔對象
                      
          //第一個(gè)參數(shù)是頁面大小。接下來的參數(shù)分別是左、右、上和下頁邊距。
                      Document document = new Document(PageSize.A4, 50505050);

                      
          //(2)創(chuàng)建寫入器
                      
          //第一個(gè)參數(shù)是對文檔對象的引用,第二個(gè)參數(shù)是輸出的文件,將out和document連接起來
                      out = new FileOutputStream(file);
                      PdfWriter writer 
          = PdfWriter.getInstance(document, out);
                      
          //打開文檔準(zhǔn)備寫入內(nèi)容
                      document.open();
                      
                      
          //(3)下面創(chuàng)建章節(jié)對象
                      
          //首先創(chuàng)建段落對象,作為章節(jié)的標(biāo)題。FontFactory用于指定段落的字體。
                      Font font = FontFactory.getFont(FontFactory.HELVETICA, 
                              
          18, Font.BOLDITALIC, new Color(00255));
                      Paragraph chapter1_title 
          = new Paragraph("Chapter 1",font);
                      
          //創(chuàng)建了一個(gè)章節(jié)對象,標(biāo)題為"Chapter 1"
                      Chapter chapter1 = new Chapter(chapter1_title, 1);
                      
          //將編號(hào)級別設(shè)為 0 就不會(huì)在頁面上顯示章節(jié)編號(hào)
                      chapter1.setNumberDepth(0);
                      
          //(4)創(chuàng)建小節(jié)對象
                      
          //創(chuàng)建小節(jié)對象的標(biāo)題
                      font = FontFactory.getFont(FontFactory.HELVETICA, 16
                              Font.BOLD, 
          new Color(25500));
                      Paragraph section1_title1 
          = new Paragraph("Section 1 of Chapter 1", font);
                      
          //創(chuàng)建一個(gè)小節(jié)對象,標(biāo)題為"This is Section 1 in Chapter 1",屬于chapter1。
                      Section section1 = chapter1.addSection(section1_title1);
                      
          //(5)往小節(jié)中寫文本內(nèi)容
                      Paragraph text = new Paragraph("This is the first text in section 1 of chapter 1.");
                      section1.add(text);
                      text 
          = new Paragraph("Following is a 5×5 table:");
                      section1.add(text);
                      
                      
          //(6)往小節(jié)中寫表格
                      
          //創(chuàng)建表格對象
                      Table table = new Table(55);
                      
          //設(shè)置表格邊框顏色
                      table.setBorderColor(new Color(220255100));
                      
          //設(shè)置單元格的邊距間隔等
                      table.setPadding(1);
                      table.setSpacing(
          1);
                      table.setBorderWidth(
          1);
                      
          //單元格對象
                      Cell cell = null;
                      
          //添加表頭信息
                      for (int colNum=0; colNum<5; colNum++){
                          cell 
          = new Cell("header-" + colNum);
                          cell.setHeader(
          true);
                          table.addCell(cell);
                      }
                      table.endHeaders();
                      
          //添加表的內(nèi)容
                      for (int rowNum=1; rowNum<5; rowNum++){
                          
          for (int colNum=0; colNum<5; colNum++){
                              cell
          = new Cell("value-" + rowNum + "-" + colNum);
                              table.addCell(cell);
                          }
                      }
                      
          //將表格對象添加到小節(jié)對象中
                      section1.add(table); 
                      
                      
          //(7)添加列表
                      
          // 列表包含一定數(shù)量的 ListItem。可以對列表進(jìn)行編號(hào),也可以不編號(hào)。
                      
          // 將第一個(gè)參數(shù)設(shè)置為 true 表明想創(chuàng)建一個(gè)進(jìn)行編號(hào)的列表;
                      
          // 第二個(gè)參數(shù)設(shè)置為true表示列表采用字母進(jìn)行編號(hào),為false則用數(shù)字進(jìn)行編號(hào);
                      
          // 第三個(gè)參數(shù)為列表內(nèi)容與編號(hào)之間的距離。
                      List list = new List(truefalse20);
                      ListItem item 
          = new ListItem("First item of list;");
                      list.add(item);
                      item 
          = new ListItem("Second item of list;");
                      list.add(item);
                      item 
          = new ListItem("Third item of list.");
                      list.add(item);
                      
          //將列表對象添加到小節(jié)對象中
                      section1.add(list);
                      
                      
          //(8)添加中文
                      
          //允許在PDF中寫入中文,將字體文件放在classPath中。
                      
          //simfang.ttf是仿宋的字體文件
                      BaseFont bfChinese = BaseFont.createFont("simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                      
          //中文大小為20,加粗
                      font = new Font(bfChinese, 20, Font.BOLD);
                      text 
          = new Paragraph("PDF中文測試", font);
                      section1.add(text);
                      
                      
          //(9)將章節(jié)對象加入到文檔中
                      document.add(chapter1);
                      
                      
          //(10)關(guān)閉文檔
                      document.close();
                      System.out.println(
          "PDF文件生成成功,PDF文件名:" + file.getAbsolutePath());
                  } 
          catch (DocumentException e) {
                      System.out.println(
          "PDF文件"+ file.getAbsolutePath() + "生成失敗!" + e);
                      e.printStackTrace();
                  } 
          catch (IOException ee) {
                      System.out.println(
          "PDF文件"+ file.getAbsolutePath() + "生成失敗!" + ee);
                      ee.printStackTrace();
                  } 
          finally {
                      
          if (out != null){
                          
          try {
                              
          //關(guān)閉輸出文件流
                              out.close();
                          } 
          catch (IOException e1) {
                          }
                      }
                  }
              }
              
          /**
               * 讀PDF文件,使用了pdfbox開源項(xiàng)目,新的版本已經(jīng)支持中文了。
               * 上www.pdfbox.org下載讀PDF的jar包
               * 
          @param fileName
               
          */
              
          public void readPDF(String fileName) {
                  File file 
          = new File(fileName);
                  FileInputStream in 
          = null;
                  
          try {
                      in 
          = new FileInputStream(fileName);
                      
          //新建一個(gè)PDF解析器對象
                      PDFParser parser = new PDFParser(in);
                      
          //對PDF文件進(jìn)行解析
                      parser.parse();
                      
          //獲取解析后得到的PDF文檔對象
                      PDDocument pdfdocument = parser.getPDDocument();
                      
          //新建一個(gè)PDF文本剝離器
                      PDFTextStripper stripper = new PDFTextStripper();
                      
          //從PDF文檔對象中剝離文本
                      String result = stripper.getText(pdfdocument);
                      System.out.println(
          "PDF文件" + file.getAbsolutePath() + "的文本內(nèi)容如下:");
                      System.out.println(result);
                      
                  } 
          catch (Exception e) {
                      System.out.println(
          "讀取PDF文件"+ file.getAbsolutePath() + "生失敗!" + e);
                      e.printStackTrace();
                  } 
          finally {
                      
          if (in != null){
                          
          try {
                              in.close();
                          } 
          catch (IOException e1) {
                          }
                      }
                  }
              }
              
              
          public static void main(String[] args) {
                  PDFFile pdf 
          = new PDFFile();
                  String fileName 
          = "C:/temp/tempPDF.pdf";
                  pdf.writePDF(fileName);
                  pdf.readPDF(fileName);
              }
          }


                                                                                                                 --    學(xué)海無涯
                  

          Feedback

          # re: 操作PDF文件  回復(fù)  更多評論   

          2012-05-12 10:06 by ly.wolf
          stripper.getText(pdfdocument);
          這裡提示錯(cuò)誤:
          "Object reference not set to an instance of an object."





          ly-msn@msn.com
          主站蜘蛛池模板: 侯马市| 子洲县| 溧阳市| 施秉县| 自治县| 舟曲县| 景宁| 连山| 闵行区| 南安市| 镇宁| 习水县| 乌兰浩特市| 金寨县| 平乡县| 西丰县| 甘洛县| 琼中| 赣榆县| 宝兴县| 靖西县| 施秉县| 万宁市| 无棣县| 灵璧县| 浠水县| 大田县| 高平市| 阳曲县| 武定县| 洛阳市| 讷河市| 克什克腾旗| 邯郸市| 莱芜市| 原平市| 忻城县| 玉龙| 沙河市| 沭阳县| 岑溪市|