![]()
I came across some issues with processing secured PDF's. These PDF files were encrypted. After reading the following documentation: http://publib.boulder.ibm.com/infocenter/zos/v1r11/index.jsp?topic=/com…, I tried securing one of my own PDF's.
Goal
Encrypting the PDF so text cannot be copy/pasted and the PDF could not be printed
Requirements
- iText
- BouncyCastle jars
Libraries used
- iText: 5.3.5
- BouncyCastle: bcprov-jdk14-1.47.jar and bcprov-ext-jdk14-1.47.jar
Code
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(), 0, PdfWriter.STANDARD_ENCRYPTION_128); } catch (Exception ex) { ex.printStackTrace(); } finally { if (stamper != null) { try { stamper.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (reader != null) { try { reader.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (out != null) { try { out.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } }
Extra
You can also play with the permissions by providing PdfWriter perms instead of the value "0".
stamper.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY, PdfWriter.STANDARD_ENCRYPTION_128);
Check if PDF is secured
- When opening the PDF with Acrobat Reader, the title should end with: (SECURED)
- Open the properties of the PDF in Acrobat Reader ( ⌘ + D on a Mac ) and look at Document Restrictions Summary
Comments
hello.. thanks, it works..but do you have source to enable copy and print?
Add new comment