您的位置:首页 > 编程语言 > Java开发

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

2017-07-07 09:29 295 查看

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

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

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

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

Java代码  


package com.peter.utils;  
  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.ArrayList;  
  
import com.lowagie.text.Document;  
import com.lowagie.text.DocumentException;  
import com.lowagie.text.pdf.PdfCopy;  
import com.lowagie.text.pdf.PdfImportedPage;  
import com.lowagie.text.pdf.PdfReader;  
  
public class MyPDFUtil {  
  
    public static void main(String[] args) {  
        partitionPdfFile("D:\\mag_test\\test_pdf.pdf","Chapter04.pdf", 11,23);  
    }  
      
    /** 
     * 截取pdfFile的第from页至第end页,组成一个新的文件名 
     * @param pdfFile 
     * @param subfileName 
     * @param from 
     * @param end 
     */  
    public static void partitionPdfFile(String pdfFile,  
            String newFile, int from, int end) {  
        Document document = null;  
        PdfCopy copy = null;          
        try {  
            PdfReader reader = new PdfReader(pdfFile);            
            int n = reader.getNumberOfPages();            
            if(end==0){  
                end = n;  
            }  
            ArrayList<String> savepaths = new ArrayList<String>();  
            String staticpath = pdfFile.substring(0, pdfFile.lastIndexOf("\\")+1);  
            String savepath = staticpath+ newFile;  
            savepaths.add(savepath);  
            document = new Document(reader.getPageSize(1));  
            copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));  
            document.open();  
            for(int j=from; j<=end; j++) {  
                document.newPage();   
                PdfImportedPage page = copy.getImportedPage(reader, j);  
                copy.addPage(page);  
            }  
            document.close();  
  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch(DocumentException e) {  
            e.printStackTrace();  
        }  
    }  
  
}

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: