Java实现PDF文件分割与加密的方法
作者:若安舟已远
时间:2023-04-27
来源:正软商城
浏览:5
加密文件/***加密文件测试*@fromfhadmin.cn*/@TestpublicvoidencryptTest(){try{StringfilePath="D:\\test\\像李开复一样思考人生.pdf";Stringpassword="1234";PDDocumentdocument=PDDocument.load(newFile(filePath));StandardProtectionPolicyspp=newStandardProtectionPolicy(password,passwor
本文目录
加密文件
/**
* 加密文件测试
* @from fhadmin.cn
*/
@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();
}
}切割文件
/**
* 切割文件测试
* @from fhadmin.cn
*/
@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();
}
}生成封面图
/**
* 切割文件测试
* @from fhadmin.cn
*/
@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 动手写单元测试进行验证。
作者最新文章
winrar怎么设置成中文 设置步骤有哪些
2026-11-07 14:32
二狗PPT生成失败怎么办?常见问题解决
2026-11-02 22:16
Mac电脑怎么截图:Command+Shift组合键用法与保存位置
2026-10-16 17:07
漫蛙漫画网页下载安装包
2026-10-13 13:19
WPS 表格单元格内换行快捷键是什么
2026-10-10 15:48
上一篇:
MySQL教程:快速搭建主从复制架构
下一篇:
Django怎么使用Redis进行缓存
热门文章
更多
精品专题
更多
Mac软件
更多
火山引擎 网页版
Windows/ macOS/ Linux
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

















