自己整理的java版的PDF分割实用代码

来源:互联网 发布:keil 端口电压查看 编辑:程序博客网 时间:2024/05/16 13:08

http://zhengjj-2009.iteye.com/blog/1841190原文地址

最近在上下班的路上看pdf文件比较多,想把整本书dpdf分割成对应的章节,所以自己看了一些参考资料后,自己写了一个小程序,实现了自己的想法。

我的基本需求是:提供一个pdf文件的全路径 + 新生成pdf文件名称 + 起始页码 + 结束页码 最后就能在相同目录下找到新文件。

可以运行的代码是(需要导入的三个jar包见附件)

Java代码  收藏代码
  1. package com.peter.utils;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6.   
  7. import com.lowagie.text.Document;  
  8. import com.lowagie.text.DocumentException;  
  9. import com.lowagie.text.pdf.PdfCopy;  
  10. import com.lowagie.text.pdf.PdfImportedPage;  
  11. import com.lowagie.text.pdf.PdfReader;  
  12.   
  13. public class MyPDFUtil {  
  14.   
  15.     public static void main(String[] args) {  
  16.         partitionPdfFile("D:\\mag_test\\test_pdf.pdf","Chapter04.pdf"11,23);  
  17.     }  
  18.       
  19.     /** 
  20.      * 截取pdfFile的第from页至第end页,组成一个新的文件名 
  21.      * @param pdfFile 
  22.      * @param subfileName 
  23.      * @param from 
  24.      * @param end 
  25.      */  
  26.     public static void partitionPdfFile(String pdfFile,  
  27.             String newFile, int from, int end) {  
  28.         Document document = null;  
  29.         PdfCopy copy = null;          
  30.         try {  
  31.             PdfReader reader = new PdfReader(pdfFile);            
  32.             int n = reader.getNumberOfPages();            
  33.             if(end==0){  
  34.                 end = n;  
  35.             }  
  36.             ArrayList<String> savepaths = new ArrayList<String>();  
  37.             String staticpath = pdfFile.substring(0, pdfFile.lastIndexOf("\\")+1);  
  38.             String savepath = staticpath+ newFile;  
  39.             savepaths.add(savepath);  
  40.             document = new Document(reader.getPageSize(1));  
  41.             copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));  
  42.             document.open();  
  43.             for(int j=from; j<=end; j++) {  
  44.                 document.newPage();   
  45.                 PdfImportedPage page = copy.getImportedPage(reader, j);  
  46.                 copy.addPage(page);  
  47.             }  
  48.             document.close();  
  49.   
  50.         } catch (IOException e) {  
  51.             e.printStackTrace();  
  52.         } catch(DocumentException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.     }  
  56.   
  57. }
  • itext-2.0.2.jar (1.3 MB)
  • 下载次数: 362
  • iText-2.1.4.jar (1 MB)
  • 下载次数: 149
  • bcprov-jdk15-139.jar (1.5 MB)
  • 下载次数: 156

原创粉丝点击