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

相关推荐
A 计算机毕业设计-小途10 分钟前
大四零基础用Vue+ElementUI一周做完化妆品推荐系统?
java·大数据·hadoop·python·spark·毕业设计·毕设
AirDroid_cn2 小时前
PDF转图片需要用到什么技术?苹果手机怎样将PDF转为jpg?
pdf·iphone·ipad·快捷指令
岁忧2 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
猿究院--王升5 小时前
jvm三色标记
java·jvm·算法
妮妮学代码5 小时前
c#:TCP服务端管理类
java·tcp/ip·c#
兔老大RabbitMQ6 小时前
git pull origin master失败
java·开发语言·git
探索java6 小时前
Netty Channel详解:从原理到实践
java·后端·netty
tuokuac7 小时前
maven与maven-archetype-plugin版本匹配问题
java·maven
ankleless7 小时前
Spring Boot 实战:从项目搭建到部署优化
java·spring boot·后端
野生技术架构师8 小时前
2025年中高级后端开发Java岗八股文最新开源
java·开发语言