Does any one have an idea about how to set password to existing pdf using openpdf java lib?

1.4k Views Asked by At

how to set password to existing PDF using OpenPdf java lib? I have tried by below code but that is created new pdf with no content

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class PasswordProtectedPDF {
  public static final String ENCRYPTED_PDF = "F://knpcode//result//OpenPDF//PP.pdf";
  // User and owner password
  final static String USER_PASSWORD = "user";
  final static String OWNER_PASSWORD = "owner";
  public static void main(String[] args) {
    try {
      Document doc = new Document();
      PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(ENCRYPTED_PDF));
      // set password, user permissions and encryption
      writer.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); 
      doc.open();
 
     
      doc.close();
      writer.close();
    } catch (DocumentException | FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
2

There are 2 best solutions below

4
On BEST ANSWER

To add password to a new PDF, we use PdfWriter.setEncryption() method.

PdfStamper API is used when we need to protect existing PDF. While instantiating PdfStamper, it accepts source file as PdfReader and destination file as OutputStream. PdfStamper can add some extra content in PDF while writing to destination file. PdfStamper.setEncryption uses the same arguments as PdfWriter.setEncryption while setting the encryption to existing PDF.

Have updated your code to use PDFStamper instead of PDFWriter.


    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.pdf.PdfStamper;
    
    public class PasswordProtectedPDF {
      // User and owner password
      final static String USER_PASSWORD = "user";
      final static String OWNER_PASSWORD = "owner";
      public static void main(String[] args) {
        try {
          File f = new File("F://knpcode//result//OpenPDF//ENCRYPTED_PP.pdf");
          FileOutputStream out = new FileOutputStream(f);
          PdfReader reader = new PdfReader("F://knpcode//result//OpenPDF//PP.pdf");
          PdfStamper stamper = new PdfStamper(reader, out);
          
          // set password, user permissions and encryption
          stamper.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);

          // Don't forget to add this line as no bytes are written to that output stream up until you close the PdfStamper instance. 
          stamper.close();

        } catch ( IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }

1
On

Using Google "java openpdf password example" I found this website: https://knpcode.com/java-programs/password-protected-pdf-using-openpdf-java/ with some information about your question.

Here are two sample programs (just copy/pasted them, not test). Don't forget to include Bouncy Castle as security provider.

Encrypt ("secure") a PDF:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class PasswordProtectedPDF {
  public static final String ENCRYPTED_PDF = "F://knpcode//result//OpenPDF//PP.pdf";
  // User and owner password
  final static String USER_PASSWORD = "user";
  final static String OWNER_PASSWORD = "owner";
  public static void main(String[] args) {
    try {
      Document doc = new Document();
      PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(ENCRYPTED_PDF));
      // set password, user permissions and encryption
      writer.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); 
      doc.open();
      Paragraph para = new Paragraph("Password protected PDF where only content printing is permitted content can't be copied.");
      doc.add(para);
      doc.close();
      writer.close();
    } catch (DocumentException | FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Reading Password protected PDF using OpenPDF:

import java.io.IOException;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.parser.PdfTextExtractor;

public class ReadPDF {
  // PDF to be read
  public static final String READ_PDF = "F://knpcode//result//OpenPDF//PP.pdf";
  final static String OWNER_PASSWORD = "owner";
  public static void main(String[] args) {
    PdfReader pdfreader = null;
    try {
      pdfreader = new PdfReader(READ_PDF, OWNER_PASSWORD.getBytes());
      // get pages in PDF
      int pages = pdfreader.getNumberOfPages();
      PdfTextExtractor pdfTextExtractor = new PdfTextExtractor(pdfreader);
      // Iterate through pages to read content
      for(int i = 1; i <= pages; i++) {
        // Extract content of each page
        String contentOfPage = pdfTextExtractor.getTextFromPage(i, true);
        System.out.println(contentOfPage );
      }         
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally {
      if(pdfreader != null) {
        pdfreader.close();
      }
    }   
  }
}