Java 合并PDF文件


   处理PDF文档时,我们可以通过合并的方式,来任意合并几个不同的PDF文件,使我们方便的存储和管理文档。例如,在做毕业设计的时候,封面和论文正文往往是两个PDF文档,但是,上交电子档的时候,需要合二为一。下面将通过Java程序代码介绍具体的PDF合并方法。

maven 依赖

 

    <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
    <dependency>
        <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
        <version>4.2.2</version>
    </dependency>

Java代码

 

package com.wiener.lou.TestWebApp.Controller; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; public class MergeFile { public static void main(String[] args) { String[] files = {  "e:\\1.pdf", "e:\\2.pdf" , "e:\\3.pdf"}; String savepath = "e:\\temp\\tempNew.pdf"; Boolean bool = mergePdfFiles(files, savepath); System.out.println(bool); } /* * 合并pdf文件 * @param files 要合并文件数组(绝对路径如{ "e:\\1.pdf", "e:\\2.pdf" , * "e:\\3.pdf"}),合并的顺序按照数组中的先后顺序,如2.pdf合并在1.pdf后。 * @param newfile 合并后新产生的文件绝对路径,如 e:\\temp\\tempNew.pdf, * @return boolean 合并成功返回true;否则,返回false * */

    public static boolean mergePdfFiles(String[] files, String newfile) { boolean retValue = false; Document document = null; try { document = new Document(new PdfReader(files[0]).getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile)); document.open(); for (int i = 0; i < files.length; i++) { PdfReader reader = new PdfReader(files[i]); int n = reader.getNumberOfPages(); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } } retValue = true; } catch (Exception e) { System.out.println(e); } finally { System.out.println("执行结束"); document.close(); } return retValue; } }

Reference

    https://www.cnblogs.com/pocketbook/p/6427579.html

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM