Merge pdf files within folder java

不羁的心 提交于 2021-02-19 07:52:27

问题


I have searched a few solutions but cannot really find an answer. Within my app i save reports to pdf using IText, but now i would like to merge all the files within the folder as I complete the report.

The issue is each folder contains different number of files so I cannot just hardcode them in.

Any advice will be appreciated.


回答1:


Here is a working example. I have used ITEXT

Dependencies :

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>



import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;

/**
 * Created by RGOVIND on 11/7/2016.
 */
public class MergePDF {
    static public void main(String[] args) throws Exception{
        mergePDF("C:\\XX\\PDF","mergedFile.pdf");
    }
    public static void mergePDF(String directory, String targetFile) throws DocumentException, IOException {
        File dir = new File(directory);
        File[] filesToMerge = dir.listFiles(new FilenameFilter() {
            public boolean accept(File file, String fileName) {
                //System.out.println(fileName);
                return fileName.endsWith(".pdf");
            }
        });
        Document document = new Document();
        FileOutputStream outputStream = new FileOutputStream("C:\\DevelopmentTools\\PDF\\"+targetFile);
        PdfCopy copy = new PdfSmartCopy(document, outputStream);
        document.open();

        for (File inFile : filesToMerge) {
            System.out.println(inFile.getCanonicalPath());
            PdfReader reader = new PdfReader(inFile.getCanonicalPath());
            copy.addDocument(reader);
            reader.close();
        }
        document.close();
    }
}


来源:https://stackoverflow.com/questions/40460935/merge-pdf-files-within-folder-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!