Java实现PDF文件分割与加密的方法
作者:若安舟已远
时间:2023-04-25
来源:互联网
浏览:0
加密文件/***加密文件测试*@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 动手写单元测试进行验证。
作者最新文章
Word格式转换成PDF?Word转PDF的具体步骤是什么?
2026-09-02 19:13
长安猎手K50 2026款上市,14.19万元起售
2026-08-25 16:08
价格大跳水,网友惊呼买早了!两大巨头正面交锋,最高直降2500元,几乎所有品类“你降我也降”
2026-08-25 16:02
全新奥迪Q3 L申报信息揭晓,车身尺寸升级,动力配置保持强劲
2026-08-25 15:44
iPhone15ProMax屏幕常亮怎么设置 iPhone15ProMax屏幕常亮设置方法
2026-08-25 15:31
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















