问题
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