I tried this code to encrypt my PDF so users cannot copy content from the PDF (just for testing, I know there’s something as OCR’ing :p)
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();
}
}
}
}
}
… But when I open the PDF, I can still select content from it. I’m using iText 5.0.2.
Any idea’s on what I’m doing wrong?
As mentioned in my comment to the question, running the example code as is results in a
NullPointerExceptionduringstamper.close()— which is quite natural as you first close thePdfReaderand afterwards thePdfStamper,but the latterclose()method accesses thePdfReader(already closed now) for its work.When I run your code with the order of closing the
PdfReaderand thePdfWriterreversed, though, I get a proper result file with the access rights as required:PS: I’m using iText version 5.3.5; if reversing the order of the
close()calls does not help in your case, you may want to update from your version 5.0.2.