pdfbox加密解密PDF文件

非原创,参考网址点击打开链接,记载是为了以后自己方便查找


所需jar包:pdfbox-2.0.5.jar fontbox-2.0.5.jar commons-logging-1.1.1.jar 

maven依赖:

  <dependency>  
                   <groupId>org.apache.pdfbox</groupId>  
                   <artifactId>pdfbox</artifactId>  
               <version>2.0.5</version>  
        </dependency>  
        <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.1.1</version>
</dependency>
<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>fontbox</artifactId>
   <version>2.0.5</version>
</dependency>

加密代码:

public String index() throws InvalidPasswordException, IOException {//加密后的pdf文件会存至2.pdf
    	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);
        return "Greetings from Spring Boot!";
    }
解密代码
 public void indexs(HttpServletResponse response,HttpServletRequest request) throws InvalidPasswordException, IOException {
    	String despath = "d:/2.pdf";
    	String ownerPassWord = "123";
    	//String srcpath = "d:/3.pdf";
    	File file = new File(despath);
    	PDDocument load = PDDocument.load(file, ownerPassWord);
    	load.setAllSecurityToBeRemoved(true);
    	//load.save(srcpath );
    	 //判断文件类型
        //String mimeType = URLConnection.guessContentTypeFromName(file.getName());
    	String mimeType = "application/pdf";
        response.setContentType(mimeType);
         
        //设置文件响应大小
      //  response.setContentLength((int)file.length());
         
        //文件名编码,解决乱码问题
        String fileName ="4.pdf";
        //设置Content-Disposition响应头,一方面可以指定下载的文件名,另一方面可以引导浏览器弹出文件下载窗口
	//inline 解密后在线预览
        response.setHeader("Content-Disposition", "inline;" + encodeFileName(request,fileName));
        load.save(response.getOutputStream());
    }
    
    public static String encodeFileName(HttpServletRequest request, String fileName) {
    	String userAgent = request.getHeader("User-Agent");
    	String rtn = "";
    	try {
    		String new_filename = URLEncoder.encode(fileName, "UTF8");
    		// 如果没有UA,则默认使用IE的方式进行编码,因为毕竟IE还是占多数的
    		rtn = "filename=\"" + new_filename + "\"";
    		if (userAgent != null) {
    			userAgent = userAgent.toLowerCase();
    			// IE浏览器,只能采用URLEncoder编码
    			if (userAgent.indexOf("msie") != -1) {
    				rtn = "filename=\"" + new_filename + "\"";
    			}
    			// Opera浏览器只能采用filename*
    			else if (userAgent.indexOf("opera") != -1) {
    				rtn = "filename*=UTF-8''" + new_filename;
    			}
    			// Safari浏览器,只能采用ISO编码的中文输出
    			else if (userAgent.indexOf("safari") != -1) {
    				rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
    			}
    			// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出
    			else if (userAgent.indexOf("applewebkit") != -1) {
    			//	new_filename = MimeUtility.encodeText(fileName, "UTF8", "B");
    				rtn = "filename=\"" + new_filename + "\"";
    			}
    			// FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出
    			else if (userAgent.indexOf("mozilla") != -1) {
    				rtn = "filename*=UTF-8''" + new_filename;
    			}
    			else
    			{
    				rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
    			}
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return rtn;
    }


解密时 PDDocument load = PDDocument.load(file, ownerPassWord);有可能会抛异常
 

java.lang.NotClassFoundError:org/bouncycastle/jce/provider/BouncyCastleProvider


解决方案:
maven添加依赖

<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 -->
<dependency>
   <groupId>org.bouncycastle</groupId>
   <artifactId>bcprov-jdk16</artifactId>
   <version>1.46</version>
</dependency>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值