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

相关推荐
道尔柯南1 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
kingx32 小时前
Bugku 3122 谷歌小恐龙题解:纯离线逆向 Vault 的 AES-GCM 加密资源(附 Python 解密器)
java·逆向·ctf·bugku·aes-gcm
DevOpenClub4 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考
露天赏雪5 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
天天被压力5 小时前
【A股分钟级高频数据完全手册 #06】北交所分钟级数据接口:京市股票Pro版最新分时
java·人工智能·python
天天被压力5 小时前
【A股分钟级高频数据完全手册 #05】指数历史分钟数据接口:Pro版沪深指数分时回放
java·人工智能·python
captain3766 小时前
▲统一功能——DispatcherServlet源码分析
java·spring·java-ee·log4j·maven
金銀銅鐵6 小时前
JDK 21 中 List.of 的实现细节:从 List12 到 ListN
java·后端·ai编程
yeccheng7 小时前
MySQL 索引超详解:从底层 B+ 树到面试高频考点
java·开发语言·jvm·mysql·面试
联犀7 小时前
纯 Go 的 CAD 开源库 go-cad:直接解析 DWG/DXF,现在也能导出 PDF
开发语言·golang·pdf