- 导入依赖。
org.apache.pdfbox pdfbox 2.0.24
注:普通java项目请自行去官网下载依赖并加入项目构建路径,需要注意pdfbox似乎会依赖commons-logging。
- 编写如下三个类文件
import java.io.File;
import java.nio.file.Paths;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
public final class PDFMerge {
public static boolean merge(String i, String reName) throws IllegalArgumentException{
boolean sign = true;
File in = new File(i);
if (!in.isDirectory()) {
throw new IllegalArgumentException("源地址应指向待合并资源的目录");
}
File[] sources = in.listFiles();
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
try {
pdfMergerUtility.setDestinationFileName(Paths.get(i,reName).toString());
for (File source : sources) {
if (source.getName().indexOf(".pdf") != -1) {
pdfMergerUtility.addSource(source);
}
}
pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
} catch (Exception e) {
sign = false;
}
return sign;
}
}
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
public final class PDFSplitter {
public static void split(int start, int end, String uri, String reName) throws IOException {
Path path = Paths.get(uri);
try(PDDocument document = PDDocument.load(path.toFile())) {
Splitter splitter = new Splitter();
splitter.setStartPage(start);
splitter.setEndPage(end);
splitter.setSplitAtPage(end - start + 1);
List documents = splitter.split(document);
documents.get(0)
.save(path.getParent().resolve(reName).toFile());
}
}
}
public final class Launch {
public static void main(String[] args) throws IllegalArgumentException, IOException {
if (args.length == 0) {throw new IllegalArgumentException("参数缺失");}
if (args[0].equals("-M")) {
switch (args.length) {
case 1:
throw new IllegalArgumentException("参数缺失");
case 2:
PDFMerge.merge(args[1], "newFile.pdf");
break;
default:
PDFMerge.merge(args[1], args[2]);
break;
}
} else if (args[0].equals("-S")) {
switch (args.length) {
case 1:
case 2:
case 3:
throw new IllegalArgumentException("参数缺失");
case 4:
PDFSplitter.split(Integer.valueOf(args[1]), Integer.valueOf(args[2]), args[3], "newFile.pdf");
break;
default:
PDFSplitter.split(Integer.valueOf(args[1]), Integer.valueOf(args[2]), args[3], args[4]);
break;
}
}else {
throw new IllegalArgumentException(String.format("指定的功能参数%s未定义", args[0]));
}
}
}
最后,为日后方便使用可以将项目打包成可运行的jar,这样每次在使用的时候只需在控制台输入一条命令即可。关于打包的方法,请自行在网络上搜索。
如果你懒的打包,那也可下载我打包好的。。。
3pjt
闲话:在CSDN这个高手云集的地方,我这个菜鸟在处处显得格格不入,经过一番的思考,我想我以后还是不在这个平台发文章了,以免浪费宝贵的服务器资源。



