如何在java中加密现有的PDF文件

时间:2013-06-10 07:55:18

标签: java

我正在尝试使用java代码加密我现有的pdf文件,但是此代码将创建新的pdf文件,任何人都可以告诉我如何加密pdf文件而不更改其内容?

    import java.io.*; 
    import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.*;
    public class PasswordProtectPDF {    
           public static byte[] UserPassword= "UserPassword".getBytes();    
           public static byte[] OwnerPassword = "OwnerPassword".getBytes();
           public static void main(String[] args){
                  try {
                      String filename=new String();
                      filename="C:\\Agam_341238\\E-Books\\test123.pdf";
                      Document Document_For_Protection = new Document();
                      PdfWriter EncryptPDF=PdfWriter.getInstance(Document_For_Protection, new FileOutputStream(filename));
                      EncryptPDF.setEncryption(UserPassword, OwnerPassword,
                ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING), PdfWriter.STANDARD_ENCRYPTION_128);

        EncryptPDF.createXmpMetadata();
        Document_For_Protection.open();
        Document_For_Protection.add(new Paragraph("Some Contents"));
        Document_For_Protection.close();
        System.out.println("Done");
    }
    catch (Exception i)
    {
        System.out.println(i);
    }
}

}

2 个答案:

答案 0 :(得分:0)

您可以使用压模。请查看详细信息http://what-when-how.com/itext-5/encrypting-a-pdf-document-itext-5/

答案 1 :(得分:-1)

您需要像这样传递输入文件

    File filename; 
    File outputFile;
    String userPassword;
    String ownerPassword;
    PdfReader reader = new PdfReader(filename);
    PdfEncryptor.encrypt(reader, new FileOutputStream(outputFile),
          ENCRYPTION_AES128, userPassword, ownerPassword, 
          permissions);