亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 學院 > 開發設計 > 正文

使用PDFBox處理PDF文檔

2019-11-10 19:12:40
字體:
來源:轉載
供稿:網友

使用PDFBox處理PDF文檔(新建PDF文件、修改PDF文件、PDF中插入圖片、將PDF文件轉換為圖片)

閱讀:4462 時間:2015-01-26 20:07分享:7

項目需要在原有的PDF文件中插入圖片、文字,并將最終的PDF文件轉換為圖片,在網上找了很多Demo,現在開源可以解析處理PDF文件的第三方插件比較多,eg:IText、PDFBox等,現在就PDFBox解析處理PDF文件總結如下:

 

【PDFBox簡介】

自從Adobe公司1993年第一次發布公共PDF參考以來,支持各種語言和平臺的PDF工具和類庫就如雨后春筍般涌現。然而,java應用開發中Adobe技術的支持相對滯后了。這是個奇怪的現象,因為PDF文檔是企業信息系統存儲和交換信息的大勢所趨,而Java技術特別適合這種應用。然而,Java開發人員似乎直到最近才獲得成熟可用的PDF支持。   PDFBox(一個BSD許可下的源碼開放項目)是一個為開發人員讀取和創建PDF文檔而準備的純Java類庫。它提供如下特性: 提取文本,包括Unicode字符。和Jakarta Lucene等文本搜索引擎的整合過程十分簡單。加密/解密PDF文檔。從PDF和XFDF格式中導入或導出表單數據。向已有PDF文檔中追加內容。將一個PDF文檔切分為多個文檔。覆蓋PDF文檔。   PS:http://baike.baidu.com/link?url=TsYWHJtTPMhlf0UvKzPOk-j3f9KzF7morIa4CqoZ0s4yIDCLB3z8nLVgLHVz-AO4dE6S7ls_3_yuvXP03nLSiq  

【PDFBox下載】

最常見的一種PDF文本抽取工具就是PDFBox了,訪問網址http://pdfbox.apache.org/download.cgi,進入如下圖所示的下載界面。讀者可以在該網頁下載其最新的版本。本書采用的是pdfbox-1.8.8版本。PDFBox是一個開源的Java PDF庫,這個庫允許你訪問PDF文件的各項信息。在接下來的例子中,將演示如何使用PDFBox提供的API操作PDF文件。

 

【將剛下載的7個jar包引入到工程當中】

pdfbox-1.8.8-src.zip為pdfbox源代碼,里面有很對的例子,在pdfbox-1.8.8/examples目錄下存在

 

【以下為Demo正式開始】

1、創建PDF文件

 

 1     public void createHelloPDF() { 2         PDDocument doc = null; 3         PDPage page = null; 4  5         try { 6             doc = new PDDocument(); 7             page = new PDPage(); 8             doc.addPage(page); 9             PDFont font = PDType1Font.HELVETICA_BOLD;10             PDPageContentStream content = new PDPageContentStream(doc, page);11             content.beginText();12             content.setFont(font, 12);13             content.moveTextPositionByAmount(100, 700);14             content.drawString("hello");15 16             content.endText();17             content.close();18             doc.save("F://java56班//eclipse-SDK-4.2-win32//pdfwithText.pdf");19             doc.close();20         } catch (Exception e) {21             System.out.PRintln(e);22         }23     }

 

2、讀取PDF文件:

 1     public void readPDF() { 2         PDDocument helloDocument = null; 3         try { 4             helloDocument = PDDocument.load(new File( 5                     "F://java56班//eclipse-SDK-4.2-win32//pdfwithText.pdf")); 6             PDFTextStripper textStripper = new PDFTextStripper("GBK"); 7             System.out.println(textStripper.getText(helloDocument)); 8  9             helloDocument.close();10         } catch (IOException e) {11             // TODO Auto-generated catch block12             e.printStackTrace();13         }14     }

3、修改PDF文件(處理中文亂碼,我可以搞定的):

 1  /** 2      * Locate a string in a PDF and replace it with a new string. 3      * 4      * @param inputFile The PDF to open. 5      * @param outputFile The PDF to write to. 6      * @param strToFind The string to find in the PDF document. 7      * @param message The message to write in the file. 8      * 9      * @throws IOException If there is an error writing the data.10      * @throws COSVisitorException If there is an error writing the PDF.11      */12     public void doIt( String inputFile, String outputFile, String strToFind, String message)13         throws IOException, COSVisitorException14     {15         // the document16         PDDocument doc = null;17         try18         {19             doc = PDDocument.load( inputFile );20 //            PDFTextStripper stripper=new PDFTextStripper("ISO-8859-1");21             List pages = doc.getDocumentCatalog().getAllPages();22             for( int i=0; i<pages.size(); i++ )23             {24                 PDPage page = (PDPage)pages.get( i );25                 PDStream contents = page.getContents();26                 PDFStreamParser parser = new PDFStreamParser(contents.getStream() );27                 parser.parse();28                 List tokens = parser.getTokens();29                 for( int j=0; j<tokens.size(); j++ )30                 {31                     Object next = tokens.get( j );32                     if( next instanceof PDFOperator )33                     {34                         PDFOperator op = (PDFOperator)next;35                         //Tj and TJ are the two operators that display36                         //strings in a PDF37                         if( op.getOperation().equals( "Tj" ) )38                         {39                             //Tj takes one operator and that is the string40                             //to display so lets update that operator41                             COSString previous = (COSString)tokens.get( j-1 );42                             String string = previous.getString();43                             string = string.replaceFirst( strToFind, message );44                             System.out.println(string);45                             System.out.println(string.getBytes("GBK"));46                             previous.reset();47                             previous.append( string.getBytes("GBK") );48                         }49                         else if( op.getOperation().equals( "TJ" ) )50                         {51                             COSArray previous = (COSArray)tokens.get( j-1 );52                             for( int k=0; k<previous.size(); k++ )53                             {54                                 Object arrElement = previous.getObject( k );55                                 if( arrElement instanceof COSString )56                                 {57                                     COSString cosString = (COSString)arrElement;58                                     String string = cosString.getString();59                                     string = string.replaceFirst( strToFind, message );60                                     cosString.reset();61                                     cosString.append( string.getBytes("GBK") );62                                 }63                             }64                         }65                     }66                 }67                 //now that the tokens are updated we will replace the68                 //page content stream.69                 PDStream updatedStream = new PDStream(doc);70                 OutputStream out = updatedStream.createOutputStream();71                 ContentStreamWriter tokenWriter = new ContentStreamWriter(out);72                 tokenWriter.writeTokens( tokens );73                 page.setContents( updatedStream );74             }75             doc.save( outputFile );76         }77         finally78         {79             if( doc != null )80             {81                 doc.close();82             }83         }84     }

4、在PDF中加入圖片:

 1 /** 2      * Add an image to an existing PDF document. 3      * 4      * @param inputFile The input PDF to add the image to. 5      * @param image The filename of the image to put in the PDF. 6      * @param outputFile The file to write to the pdf to. 7      * 8      * @throws IOException If there is an error writing the data. 9      * @throws COSVisitorException If there is an error writing the PDF.10      */11     public void createPDFFromImage( String inputFile, String image, String outputFile ) 12         throws IOException, COSVisitorException13     {14         // the document15         PDDocument doc = null;16         try17         {18             doc = PDDocument.load( inputFile );19 20             //we will add the image to the first page.21             PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );22 23             PDXObjectImage ximage = null;24             if( image.toLowerCase().endsWith( ".jpg" ) )25             {26                 ximage = new PDJpeg(doc, new FileInputStream( image ) );27             }28             else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))29             {30                 ximage = new PDCcitt(doc, new RandomaccessFile(new File(image),"r"));31             }32             else33             {34                 BufferedImage awtImage = ImageIO.read( new File( image ) );35                 ximage = new PDPixelMap(doc, awtImage);36             }37             PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);38 39             //contentStream.drawImage(ximage, 20, 20 );40             // better method inspired by http://stackoverflow.com/a/22318681/53564641             float scale = 0.5f; // reduce this value if the image is too large42             System.out.println(ximage.getHeight());43             System.out.println(ximage.getWidth());44 //            ximage.setHeight(ximage.getHeight()/5);45 //            ximage.setWidth(ximage.getWidth()/5);46             contentStream.drawXObject(ximage, 20, 200, ximage.getWidth()*scale, ximage.getHeight()*scale);47 48             contentStream.close();49             doc.save( outputFile );50         }51         finally52         {53             if( doc != null )54             {55                 doc.close();56             }57         }58     }

5、PDF文件轉換為圖片:

 1 public void toImage() { 2     try { 3         PDDocument doc = PDDocument 4                 .load("F://java56班//eclipse-SDK-4.2-win32//pdfwithText.pdf"); 5         int pageCount = doc.getPageCount(); 6         System.out.println(pageCount); 7         List pages = doc.getDocumentCatalog().getAllPages(); 8         for (int i = 0; i < pages.size(); i++) { 9             PDPage page = (PDPage) pages.get(i);10             BufferedImage image = page.convertToImage();11             Iterator iter = ImageIO.getImageWritersBySuffix("jpg");12             ImageWriter writer = (ImageWriter) iter.next();13             File outFile = new File("F://java56班//eclipse-SDK-4.2-win32//"14                     + i + ".jpg");15             FileOutputStream out = new FileOutputStream(outFile);16             ImageOutputStream outImage = ImageIO17                     .createImageOutputStream(out);18             writer.setOutput(outImage);19             writer.write(new IIOImage(image, null, null));20         }21         doc.close();22         System.out.println("over");23     } catch (FileNotFoundException e) {24         // TODO Auto-generated catch block25         e.printStackTrace();26     } catch (IOException e) {27         // TODO Auto-generated catch block28         e.printStackTrace();29     }30 }

 

6、圖片轉換為PDF文件(支持多張圖片轉換為PDF文件):

 1 /** 2      * create the second sample document from the PDF file format specification. 3      *  4      * @param file 5      *            The file to write the PDF to. 6      * @param image 7      *            The filename of the image to put in the PDF. 8      *  9      * @throws IOException10      *             If there is an error writing the data.11      * @throws COSVisitorException12      *             If there is an error writing the PDF.13      */14     public void createPDFFromImage(String file, String image)throws IOException, COSVisitorException {15         // 多張圖片轉換為PDF文件16         PDDocument doc = null;17         doc = new PDDocument();18         PDPage page = null;19         PDXObjectImage ximage = null;20         PDPageContentStream contentStream = null;21 22         File files = new File(image);23         String[] a = files.list();24         for (String string : a) {25             if (string.toLowerCase().endsWith(".jpg")) {26                 String temp = image + "//" + string;27                 ximage = new PDJpeg(doc, new FileInputStream(temp));28                 page = new PDPage();29                 doc.addPage(page);30                 contentStream = new PDPageContentStream(doc, page);31                 float scale = 0.5f;32                 contentStream.drawXObject(ximage, 20, 400, ximage.getWidth()33                         * scale, ximage.getHeight() * scale);34                 35                 PDFont font = PDType1Font.HELVETICA_BOLD;36                 contentStream.beginText();37                 contentStream.setFont(font, 12);38                 contentStream.moveTextPositionByAmount(100, 700);39                 contentStream.drawString("Hello");40                 contentStream.endText();41                 42                 contentStream.close();43             }44         }45         doc.save(file);46         doc.close();47     }

7、替換PDF文件中的某個字符串:

 1  /** 2      * Locate a string in a PDF and replace it with a new string. 3      * 4      * @param inputFile The PDF to open. 5      * @param outputFile The PDF to write to. 6      * @param strToFind The string to find in the PDF document. 7      * @param message The message to write in the file. 8      * 9      * @throws IOException If there is an error writing the data.10      * @throws COSVisitorException If there is an error writing the PDF.11      */12     public void doIt( String inputFile, String outputFile, String strToFind, String message)13         throws IOException, COSVisitorException14     {15         // the document16         PDDocument doc = null;17         try18         {19             doc = PDDocument.load( inputFile );20 //            PDFTextStripper stripper=new PDFTextStripper("ISO-8859-1");21             List pages = doc.getDocumentCatalog().getAllPages();22             for( int i=0; i<pages.size(); i++ )23             {24                 PDPage page = (PDPage)pages.get( i );25                 PDStream contents = page.getContents();26                 PDFStreamParser parser = new PDFStreamParser(contents.getStream() );27                 parser.parse();28                 List tokens = parser.getTokens();29                 for( int j=0; j<tokens.size(); j++ )30                 {31                     Object next = tokens.get( j );32                     if( next instanceof PDFOperator )33                     {34                         PDFOperator op = (PDFOperator)next;35                         //Tj and TJ are the two operators that display36                         //strings in a PDF37                         if( op.getOperation().equals( "Tj" ) )38                         {39                             //Tj takes one operator and that is the string40                             //to display so lets update that operator41                             COSString previous = (COSString)tokens.get( j-1 );42                             String string = previous.getString();43                             string = string.replaceFirst( strToFind, message );44                             System.out.println(string);45                             System.out.println(string.getBytes("GBK"));46                             previous.reset();47                             previous.append( string.getBytes("GBK") );48                         }49                         else if( op.getOperation().equals( "TJ" ) )50                         {51                             COSArray previous = (COSArray)tokens.get( j-1 );52                             for( int k=0; k<previous.size(); k++ )53                             {54                                 Object arrElement = previous.getObject( k );55                                 if( arrElement instanceof COSString )56                                 {57                                     COSString cosString = (COSString)arrElement;58                                     String string = cosString.getString();59                                     string = string.replaceFirst( strToFind, message );60                                     cosString.reset();61                                     cosString.append( string.getBytes("GBK") );62                                 }63                             }64                         }65                     }66                 }67                 //now that the tokens are updated we will replace the68                 //page content stream.69                 PDStream updatedStream = new PDStream(doc);70                 OutputStream out = updatedStream.createOutputStream();71                 ContentStreamWriter tokenWriter = new ContentStreamWriter(out);72                 tokenWriter.writeTokens( tokens );73                 page.setContents( updatedStream );74             }75             doc.save( outputFile );76         }77         finally78         {79             if( doc != null )80             {81                 doc.close();82             }83         }84     }

 

上述描述的只是PDFBox的部分功能,在原始資源包中有很對例子,大家可以學習,PDFBox API路徑:http://pdfbox.apache.org/docs/1.8.8/javadocs/

轉載自:愛編程w2bc.com
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
欧美大全免费观看电视剧大泉洋| 在线视频一区二区| 亚洲欧美日韩在线一区| 日韩美女激情视频| 久热99视频在线观看| 欧美日本国产在线| 亚洲精品欧美日韩| 黄色成人av在线| 精品国产一区av| 国产精品自拍网| 亚洲精品美女久久久久| 91精品啪在线观看麻豆免费| 欧美日韩免费观看中文| 国产v综合ⅴ日韩v欧美大片| 久久天天躁狠狠躁夜夜av| 亚洲精品美女久久久久| 91视频国产高清| 国产在线观看精品| 91国内精品久久| 伊人青青综合网站| 亚洲免费精彩视频| 狠狠躁夜夜躁人人爽天天天天97| 久久国内精品一国内精品| 欧美富婆性猛交| 国模私拍一区二区三区| 97成人在线视频| 久久久久久中文字幕| 日韩在线视频观看| 8090成年在线看片午夜| 亚洲男人第一av网站| 2019亚洲日韩新视频| 日韩女优人人人人射在线视频| 久久91精品国产91久久久| 欧美精品在线免费观看| 8050国产精品久久久久久| 国产精品一区二区久久久久| 精品国产成人av| 国产精品久久久久久亚洲影视| 日本精品一区二区三区在线| 亚洲日本aⅴ片在线观看香蕉| 国产日韩精品在线播放| 尤物yw午夜国产精品视频明星| 日本一欧美一欧美一亚洲视频| 欧美日韩中文字幕在线视频| 久久综合网hezyo| 日韩免费精品视频| 久久这里有精品| 91九色国产在线| 深夜精品寂寞黄网站在线观看| 亚洲精品自拍第一页| 成人欧美一区二区三区黑人孕妇| 久久五月天综合| 日韩专区在线播放| 欧美激情网友自拍| 欧美理论电影在线观看| 欧美激情视频一区二区三区不卡| 亚洲福利视频免费观看| 热久久这里只有| 久久深夜福利免费观看| 成人妇女免费播放久久久| 人人做人人澡人人爽欧美| 亚洲女成人图区| 色777狠狠综合秋免鲁丝| 亚洲午夜av久久乱码| 上原亚衣av一区二区三区| 国产日韩欧美视频在线| 久久久久久久国产精品| 国产一区二区美女视频| 国内精品久久久久久久久| 亚洲综合社区网| 欧美国产精品日韩| 久久久久五月天| 91精品综合视频| 欧美日韩国产二区| 欧美日韩一区二区精品| 色偷偷av一区二区三区| 久久福利网址导航| 琪琪亚洲精品午夜在线| 久久99久久亚洲国产| 久久视频在线观看免费| 欧美第一淫aaasss性| 91在线无精精品一区二区| 国产日本欧美一区| 2019亚洲日韩新视频| 日韩精品视频在线观看免费| 91精品国产91久久久久久不卡| 国产精品久久久久久久一区探花| 久久99国产精品久久久久久久久| 66m—66摸成人免费视频| 久久影院模特热| 亚洲二区在线播放视频| 国产精品高潮呻吟久久av无限| 日韩国产精品一区| www.午夜精品| 亚洲欧美自拍一区| 国产欧美日韩中文字幕在线| 亚洲成人av在线| 亚洲电影免费观看高清完整版在线| 青青久久av北条麻妃黑人| 国产精品av电影| 精品高清一区二区三区| 亚洲一区二区三区四区在线播放| 亚洲高清一二三区| 欧美精品久久久久a| 国产精品自拍偷拍视频| 中文字幕日韩欧美精品在线观看| 亚洲国产精品中文| 亚洲精品久久久久中文字幕二区| 在线视频欧美日韩| 日韩精品免费综合视频在线播放| 日韩av在线播放资源| 奇米4444一区二区三区| 高清一区二区三区日本久| 日韩亚洲精品视频| 成人免费看片视频| 久久精品视频中文字幕| 亚洲成人激情视频| 欧美人与性动交a欧美精品| 国产免费成人av| 久久免费在线观看| 日韩成人性视频| 欧美高跟鞋交xxxxxhd| 亚洲男人天堂2019| 国产精品一区二区久久精品| 国产精品露脸自拍| 91精品国产91久久久久久久久| 日韩av在线网站| 亚洲性日韩精品一区二区| 91老司机精品视频| 久久精品国产免费观看| 欧美电影院免费观看| 2019国产精品自在线拍国产不卡| 国产精品视频一区二区三区四| 欧美日韩高清在线观看| 91天堂在线观看| 久久免费视频这里只有精品| 国产亚洲精品91在线| 精品人伦一区二区三区蜜桃网站| 91在线无精精品一区二区| 久久精品国产欧美亚洲人人爽| 国产精品夜色7777狼人| 国产精品成人免费电影| 九色精品美女在线| 日韩欧美国产激情| 亚洲一区二区少妇| 国精产品一区一区三区有限在线| 欧美老女人在线视频| 久久免费福利视频| 欧美性猛交xxxx乱大交| 亚洲加勒比久久88色综合| 亚洲天堂av女优| 亚洲黄页视频免费观看| 亚洲精品av在线播放| 亚洲男人天堂2019| 国产福利视频一区| 一区二区三区美女xx视频| 亚洲综合中文字幕在线| 亚洲欧美国产精品| 国产精品情侣自拍| 欧美日本亚洲视频| 国产精品扒开腿爽爽爽视频| 成人免费福利在线| 欧美成人中文字幕| 亚洲国产精品专区久久|