2013-02-09 220 views
2

我想这个代码加密我的PDF格式,使用户无法从PDF复制内容(只是用于测试,我知道有一些为OCR'ing:P)加密PDF文件使用的iText不允许的内容复印和打印

import java.io.FileOutputStream; 

import com.itextpdf.text.pdf.PdfReader; 
import com.itextpdf.text.pdf.PdfStamper; 
import com.itextpdf.text.pdf.PdfWriter; 

public class EncryptPDF { 

private static final String INPUT_FILENAME = "/tmp/test.pdf"; 
private static final String OUTPUT_FILENAME = "/tmp/test_encrypted.pdf"; 
private static final String USER_PASSWORD = ""; 
private static final String OWNER_PASSWORD = "foobar"; 

public static void main(String[] args) { 
    PdfReader reader = null; 
    FileOutputStream out = null; 
    PdfStamper stamper = null; 

    try { 
     // Define input 
     reader = new PdfReader(INPUT_FILENAME); 

     // Define output 
     out = new FileOutputStream(OUTPUT_FILENAME); 

     // Encrypt document 
     stamper = new PdfStamper(reader, out); 
     stamper.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING), PdfWriter.STANDARD_ENCRYPTION_128); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 
     if (stamper != null) { 
      try { 
       stamper.close(); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 
     if (out != null) { 
      try { 
       out.close(); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 
    } 

} 
} 

...但是当我打开PDF时,我仍然可以从中选择内容。我正在使用iText 5.0.2。

任何想法对我做错了什么?

+0

另请提供您生成的PDF。 – mkl 2013-02-09 20:04:20

+0

只需提供您想要允许的权限,而不是否定OR-ed在一起的权限即可。你为什么在那里使用否定? – 2013-02-09 21:28:22

+0

@mkl:这是你可以使用的一个:http://www.selab.isti.cnr.it/ws-mate/example.pdf – 2013-02-10 18:18:02

回答

1

正如我在这个问题发表评论时提及,运行示例代码中stamper.close()作为处于NullPointerException结果---这是很自然的,因为你首先关闭PdfReader和事后PdfStamper,但后者close()方法访问PdfReader (现在已经关闭)的工作。

当我关闭PdfReader秩序,扭转了PdfWriter运行你的代码,但是,我得到的访问权限,正确的结果文件的要求:

document properties of protected PDF showing print and copy as disabled

PS:我使用iText 5.3.5版;如果逆转close()调用的顺序对您的情况没有帮助,则可能需要从5.0.2版更新。

+0

我没有得到与5.0.2 NPE,但我确实得到它与5.3.5。我仍然无法加密PDF,因为此错误: 引起:java.lang.ClassNotFoundException:org.bouncycastle.asn1.ASN1Primitive。我今晚会为Google解决这个问题 – 2013-02-11 14:49:58

+0

您使用哪种Bouncycastles JAR? – 2013-02-11 15:16:05

+1

没关系,可以使用:bcprov-jdk14-1.47.jar和bcprov-ext-jdk14-1.47.jar – 2013-02-11 15:52:42