有时候有些PDF里面只有很少的页数内容,对于有些多个PDF需要归类到一个PDF上,就用到了PDF的合并。
下面是项目结构截图:
需要用的关键jar包是pdfbox.jar,这里选用的版本是1.8.11版本,其中还需要依赖一个日志jar包:commons-logging.jar
项目结构说明:
- pdfs文件夹里放的是多个要合并的pdf
- lib目录下方的是引入的jar包
- 主类:MultiPdf2One.java,代码如下:
package com.acconsys.vpm.test;
import java.io.File;
public class MultiPdf2One {
/**
*
* @param folder
* @return
* @throws IOException
*/
private static String[] getFiles(String folder) throws IOException {
File _folder = new File(folder);
String[] filesInFolder;
if (_folder.isDirectory()) {
filesInFolder = _folder.list();
return filesInFolder;
} else {
throw new IOException("Path is not a directory");
}
}
public static void main(String[] args) throws Exception {
PDFMergerUtility mergePdf = new PDFMergerUtility();
// String folder = System.getProperty("user.dir")+"\\pdfs";
String folder = "pdfs";
System.out.println(folder);
String destinationFileName = "mergedPdf.pdf";
String[] filesInFolder = getFiles(folder);
for (int i = 0; i < filesInFolder.length; i++)
mergePdf.addSource(folder + File.separator + filesInFolder[i]);
mergePdf.setDestinationFileName(destinationFileName);
mergePdf.mergeDocuments();
System.out.print("done");
}
}
具体代码可以在这里获得:http://pan.baidu.com/s/1bY91F4