使用java代码对pdf进行切割

使用java代码对pdf进行切割

起因,pdf下载的太大了,无法上传有道云笔记,切割成上下两部分

代码

java 复制代码
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 PDF {
	public static void main(String[] args) {
		partitionPdfFile("D:/Java 8编程官方参考教程(第9版).pdf","D:/Java 8编程官方参考教程(第9版).pdf)下.pdf", 700,1281);
	}
	
	/**
	 * 截取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();
		}
	}
}

所需jar包

bcprov-jdk15-141.jar

iText-2.1.4.jar

itext-2.0.2.jar

相关推荐
2501_9275393010 分钟前
PDF Reader 编辑阅读(Mac)
pdf·mac·pdf reader
CHANG_THE_WORLD10 分钟前
BrotliCompressor压缩器封装,以及 PDF编码器介绍
pdf
在路上`23 分钟前
前端学习之后端java小白(三)-sql外键约束一对多
java·前端·学习
dazhong201233 分钟前
Spring Boot 项目新增 Module 完整指南
java·spring boot·后端
xrkhy1 小时前
SpringBoot之日志处理(logback和AOP记录操作日志)
java·spring boot·logback
搬山境KL攻城狮1 小时前
MacBook logback日志输出到绝对路径
java·intellij-idea·logback
yb0os11 小时前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc
liuyao_xianhui1 小时前
内存管理(C/C++)
java·开发语言·c++
superlls1 小时前
(设计模式)区分建造者、 规格模式(MyBatis Example+Criteria )
java·tomcat
kimble_xia@oracle1 小时前
SQL 笔记
java·数据库·oracle