使用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

相关推荐
mldong3 小时前
"applicant" 契约:退回发起人的闭环设计
java·架构
月华路4 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding4 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
zww89491115 小时前
校园跑腿系统开发实战指南:从需求分析到上线部署全流程解析
java
Fluxart.ai5 小时前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
名字还没想好☜6 小时前
Java 线上内存泄漏排查实战:jmap 导堆、MAT 找 GC Roots 与四类常见泄漏
java·开发语言·jvm·内存泄漏
IT爱学堂8 小时前
尚硅谷 - 2025年3月Java+AI大模型应用开发
java·开发语言·人工智能
赵广陆8 小时前
企业实战:主体识别
langchain·pdf·langgraph
小贤plus8 小时前
SpringBoot 三大核心注解精讲:@ControllerAdvice、@RestControllerAdvice、@Validated 分组校验(实战)
java
吠品9 小时前
Java byte数组与String互转:编码细节与踩坑记录
java·linux·服务器