由于``某些不可抗力原因,公司不允許使用itext系列的jar包,因此系統中使用的相關jar得替換成開源的,經比較和嘗試考慮使用org.apache.pdfbox來替換,同時修改系統中原有的方法,發現比itext系列稍顯簡潔一點,記錄如下:
加密檔案
/**
* 加密檔案測驗
* @date 2022/4/7
*/
@Test
public void encryptTest(){
try {
String filePath = "D:\\test\\像李開復一樣思考人生.pdf";
String password = "1234";
PDDocument document = PDDocument.load(new File(filePath));
StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password,new AccessPermission());
document.protect(spp);
String newFilePath = "D:\\test\\像李開復一樣思考人生2.pdf";
document.save(newFilePath);
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
切割檔案
/**
* 切割檔案測驗
* @date 2022/4/7
*/
@Test
public void extractTest(){
try {
String newFilePath = "D:\\test\\像李開復一樣思考人生2.pdf";
String password = "1234";
PDDocument document = PDDocument.load(new File(newFilePath), password);//帶密碼讀取
//從第一頁截取到第二頁
PageExtractor pageExtractor = new PageExtractor(document, 1, 2);
PDDocument extract = pageExtractor.extract();
extract.save("D:\\test\\像李開復一樣思考人生free.pdf");
extract.close();
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
生成封面圖
/**
* 切割檔案測驗
* @date 2022/4/7
*/
@Test
public void createCoverPicTest(){
try {
String pdfPath = "D:\\test\\像李開復一樣思考人生.pdf";
File file = new File(pdfPath);
//order目錄
String orderPath = file.getParent();
//轉換后的img目錄
String bookName = file.getName().substring(0,file.getName().lastIndexOf("."));
String imgPath = orderPath + File.separator +bookName+".png";
log.debug("pdf封面圖生成成功:{}", imgPath);
PDDocument pdDocument = PDDocument.load(new File(pdfPath));
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* 第二位引數越大轉換后越清晰,相對轉換速度越慢 */
BufferedImage image = renderer.renderImageWithDPI(0, 150);
ImageIO.write(image, "png", new File(imgPath));
} catch (IOException e) {
e.printStackTrace();
}
}
總結一下,現在的工具都比較豐富了,不需要自己去造輪子,
step-1 去maven倉庫檢索同型別的包,比較一下熱度和使用人數
step-2 下載對應包的source源代碼,看一下框架整體結構,里面都有哪些package和類,不知道類是干什么的,可以看一下類上面的注釋,一般都是比較簡單的英文
step-3 動手寫單元測驗進行驗證,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457529.html
標籤:Java
上一篇:CORS與CSRF在Spring Security中的使用
下一篇:異步任務-springboot
