• 使用java代码对pdf进行切割


    使用java代码对pdf进行切割

    起因,pdf下载的太大了,无法上传有道云笔记,切割成上下两部分

    代码

    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();
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    所需jar包

    bcprov-jdk15-141.jar
    iText-2.1.4.jar
    itext-2.0.2.jar

  • 相关阅读:
    Nginx 面试 40 问
    Java.lang.Class类 getModifiers()方法有什么功能呢?
    Static 静态成员
    牛客 NC24755 [USACO 2010 Dec S]Apple Delivery
    ES 批量删除数据
    软路由koolshare故障处理集锦
    三等分功分器[波导]设计详细教程
    【C++】内联函数&auto&范围for循环&nullptr
    五个维度着手MySQL的优化,我和面试官都聊嗨了
    OllamaFunctions 学习笔记
  • 原文地址:https://blog.csdn.net/do_finsh/article/details/136323938