Java iText中的PDF加密错误

时间:2014-05-19 02:16:07

标签: eclipse pdf encryption itext

我想加密我的PDF,但似乎有错误。我正在使用iText和Eclipse。

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.exceptions.InvalidPdfException;

public class EncryptionPdf {

    public static void main(String[] args) throws IOException, DocumentException 
    {
        PdfReader reader = new PdfReader("C:/Users/Binaday/Desktop/PDF RESULTS/Booking Form.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("C:/Users/Binaday/Desktop/PDF RESULTS/Booking Form2.pdf"));
        stamper.setEncryption("reader_password".getBytes(), "permission_password".getBytes(),   ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING ), PdfWriter.STANDARD_ENCRYPTION_128);
        stamper.close();
    }
}

这是错误:

  

线程“main”中的异常java.lang.NoClassDefFoundError:org / bouncycastle / asn1 / ASN1Encodable
  at com.itextpdf.text.pdf.PdfEncryption。(PdfEncryption.java:149)
  at com.itextpdf.text.pdf.PdfWriter.setEncryption(PdfWriter.java:2119)
  在EncryptionPdf.main(EncryptionPdf.java:16)
  引起:java.lang.ClassNotFoundException:org.bouncycastle.asn1.ASN1Encodable
  在java.net.URLClassLoader $ 1.run(未知来源)
  在java.net.URLClassLoader $ 1.run(未知来源)
  at java.security.AccessController.doPrivileged(Native Method)
  在java.net.URLClassLoader.findClass(未知来源)
  在java.lang.ClassLoader.loadClass(未知来源)
  at sun.misc.Launcher $ AppClassLoader.loadClass(Unknown Source)
  在java.lang.ClassLoader.loadClass(未知来源)
  ......还有3个

1 个答案:

答案 0 :(得分:0)

当您查看iText的POM文件时,您会看到以下依赖项:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.49</version>
    <type>jar</type>
    <scope>compile</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk15on</artifactId>
    <version>1.49</version>
    <type>jar</type>
    <scope>compile</scope>
    <optional>true</optional>
</dependency>

这意味着您需要bcprov和Bouncycastle的bcpkix jars版本1.49:http://bouncycastle.org/java.html

如果您不使用iText 5.5.0,请检查POM文件,因为旧版本的iText可能需要旧版本的BouncyCastle。