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

相关推荐
SUPER52661 小时前
FastApi项目启动失败 got an unexpected keyword argument ‘loop_factory‘
java·服务器·前端
咕噜咕噜啦啦1 小时前
Eclipse集成开发环境的使用
java·ide·eclipse
光军oi4 小时前
全栈开发杂谈————关于websocket若干问题的大讨论
java·websocket·apache
weixin_419658314 小时前
Spring 的统一功能
java·后端·spring
小许学java5 小时前
Spring AI-流式编程
java·后端·spring·sse·spring ai
haogexiaole5 小时前
Java高并发常见架构、处理方式、api调优
java·开发语言·架构
EnCi Zheng6 小时前
@ResponseStatus 注解详解
java·spring boot·后端
wdfk_prog6 小时前
闹钟定时器(Alarm Timer)初始化:构建可挂起的定时器基础框架
java·linux·数据库
怎么没有名字注册了啊6 小时前
C++后台进程
java·c++·算法
z日火6 小时前
Java 泛型
java·开发语言