使用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 小时前
23种设计模式-行为型模式之状态模式(Java版本)
java·jvm·设计模式·状态模式·软考·软件设计师·行为模式
跑马的程序员3 小时前
word模板填充导出-(支持word导出、pdf导出)
pdf·word
豆沙沙包?3 小时前
2025年- H16-Lc124-169.多数元素(技巧)---java版
java·开发语言
zhangxueyi3 小时前
Java实现基数排序算法
java·数据结构·算法
Another Iso5 小时前
同时启动俩个tomcat压缩版
java·tomcat
华纳云IDC服务商6 小时前
华纳云:centos如何实现JSP页面的动态加载
java·linux·centos
碎梦归途6 小时前
23种设计模式-行为型模式之访问者模式(Java版本)
java·开发语言·jvm·设计模式·软考·软件设计师·行为型模式
Demons_kirit6 小时前
LeetCode LCP40 心算挑战题解
java·数据结构·算法·leetcode·职场和发展
Jiaberrr7 小时前
uniapp 实现低功耗蓝牙连接并读写数据实战指南
java·前端·javascript·vue.js·struts·uni-app
家乡的落日7 小时前
一、I/O的相关概念
java