在文件夹Java中合并pdf文件 [英] Merge pdf files within folder java

查看:72
本文介绍了在文件夹Java中合并pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一些解决方案,但找不到真正的答案.在我的应用程序中,我使用IText将报告保存为pdf,但是现在我想在完成报告时合并文件夹中的所有文件.

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.

任何建议将不胜感激.

推荐答案

这是一个有效的示例.我用过ITEXT

Here is a working example. I have used ITEXT

依赖项:

<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();
    }
}

这篇关于在文件夹Java中合并pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆