引入jar包,pdfbox和itextpdf,pom文件如下
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.9</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency>
废话不说直接上干货
List<String> filePath = new ArrayList();
String sep = java.io.File.separator;
PdfReader reader = null;
int numberOfPages;
String saveBasePath = FileUtils.getFolderName(UUID.randomUUID().toString().replaceAll("-", ""));
try {
URL url = new URL(ossFileDTO.getDownloadUrl());
reader = new PdfReader(url);
numberOfPages = reader.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
Document document = null;
PdfCopy copy = null;
try {
document = new Document(reader.getPageSize(i));
String fileName_half ;
String text_i = PdfTextExtractor.getTextFromPage(reader, i);
fileName_half = fileName_half.replaceAll("[:*|,*|:*|,*| *| *| *|\\s*]*", "");
String savePath = saveBasePath + sep +
ossFileDTO.getFilename().substring(0, ossFileDTO.getFilename().lastIndexOf(".")) + "_"+ i + fileName_half + ".pdf";
File file = new File(saveBasePath, savePath);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
copy = new PdfCopy(document, new FileOutputStream(savePath));
document.open();
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, i);
copy.addPage(page);
filePath.add(savePath);
} catch (Exception e) {
Log.error("上传oss失败!",e);
} finally {
if (document != null)
document.close();
if (copy != null)
copy.close();
}
}
} catch (Exception e){
log.error("转换失败!",e);
} finally {
if (reader != null){
reader.close();
}
}
总结:获取到filePath 后,根据自己的需求,进行灵活使用。