`
zhengjj_2009
  • 浏览: 149287 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

 
阅读更多

最近在上下班的路上看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();
		}
	}

}

 

 

3
7
分享到:
评论
2 楼 zhengjj_2009 2013-04-03  
我为了安全起见,所以放了两个jar,其实一个应该可以了。
1 楼 tjj006 2013-04-03  
为什么需要两个ITEXT包??

相关推荐

Global site tag (gtag.js) - Google Analytics