使用pdfbox与itext设置pdf文件密码

一、使用pdfbox加解密
所需jar包:pdfbox-2.0.5.jar fontbox-2.0.5.jar commons-logging-1.1.1.jar
1.加密

String srcpath = “d:/1.pdf”;
String despath = "d:/2.pdf"
String ownerPassWord = "123";
String userPassWord = "456";
File file = new File(srcpath);
long start = System.currentTimeMillis();
PDDocument load = PDDocument.load(file); 
AccessPermission permissions = new AccessPermission(); 
permissions.setCanExtractContent(false);
permissions.setCanModify(false);
StandardProtectionPolicy p = new StandardProtectionPolicy(ownerPassWord , userPassWord, permissions); 
SecurityHandler sh = new StandardSecurityHandler(p); 
sh.prepareDocumentForEncryption(load);
PDEncryption encryptionOptions= new PDEncryption();
encryptionOptions.setSecurityHandler(sh);
load.setEncryptionDictionary(encryptionOptions);
load.save(despath);

2.解密

File file = new File(despath);
PDDocument load = PDDocument.load(file, ownerPassWord);
load.setAllSecurityToBeRemoved(true);
load.save(srcpath );

二、使用itextpdf加解密
所需jar包:itextpdf-5.5.6.jar bcprov-ext-jdk15on-150.jar
1.加密

String srcpath = “d:/1.pdf”;
String despath = "d:/2.pdf"
String userPassWord = "456";
String ownerPassWord = "123";
PdfReader reader = new PdfReader(srcpath);  
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(despath));  
stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), PdfWriter.ALLOW_MODIFY_CONTENTS, false); 
stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), PdfWriter.ALLOW_COPY, false); 
stamper.close();
reader.close();

2.解密

PdfReader reader = new PdfReader(despath,ownerPassWord.getBytes());
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(srcpath));  
stamper.setEncryption(null, null, PdfWriter.ALLOW_MODIFY_CONTENTS, true); 
stamper.setEncryption(null, null, PdfWriter.ALLOW_COPY, true); 
stamper.close();
reader.close();

你可能感兴趣的:(加解密)