http://zhengjj-2009.iteye.com/blog/1841190原文地址
最近在上下班的路上看pdf文件比较多,想把整本书dpdf分割成对应的章节,所以自己看了一些参考资料后,自己写了一个小程序,实现了自己的想法。
我的基本需求是:提供一个pdf文件的全路径 + 新生成pdf文件名称 + 起始页码 + 结束页码 最后就能在相同目录下找到新文件。
可以运行的代码是(需要导入的三个jar包见附件)
- 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();
- }
- }
- }