Choose Your Language

Thursday 27 June 2013

How to Generate a Password Protected PDF Document Uing java

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

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.util.Calendar;
import java.util.Locale;
import org.joda.time.DateTime;

public class GeneratePDFWithPassword {
   
private static String USER_PASS = "aravind";

private static String OWNER_PASS = "aravind";    
    
    public static void main(String[] args) {
        try {
       
            DateTime dateTime = new DateTime();
           
            String hour =String.valueOf(dateTime.getHourOfDay());
            String minute =String.valueOf(dateTime.getMinuteOfHour());
            String second =String.valueOf(dateTime.getSecondOfMinute());
            String millisecond =String.valueOf(dateTime.getMillisOfSecond());
           
            String day = dateTime.dayOfMonth().getAsText();           
            String monthName = dateTime.monthOfYear().getAsText();
            String yearName = dateTime.year().getAsText();
           
            String date=day+"-"+monthName+"-"+yearName+"  "+hour+"hrs-"+minute+"min-"+second+"sec-"+millisecond+"msec";           
           
             OutputStream file = new FileOutputStream(new File("C:\\folderName\\report_"+date+".pdf"));

            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, file);

            writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);

            document.open();
            document.add(new Paragraph("Welcome Aravind"));           
            document.add(new Paragraph(new Date().toString()));

            document.close();
            file.close();
       
    }
       
        catch (Exception e) {

            e.printStackTrace();
        }
    }
}

jar file needed:
itextpdf-5.2.1
bcmail-jdk16-1.46.jar
bcprov-jdk16-1.46.jar
bctsp-jdk16-1.46.jar

joda-time-2.2.jar
joda-time-2.2-javadoc.jar
joda-time-2.2-sources


3 comments:

  1. I cant find "joda-time-2.2-javadoc.jar".

    ReplyDelete
    Replies
    1. u need to add these jar files only...
      itextpdf-5.2.1
      bcmail-jdk16-1.46.jar
      bcprov-jdk16-1.46.jar
      bctsp-jdk16-1.46.jar
      joda-time-2.2.jar

      Delete
  2. Wow, I did not even know this was possible! Thanks for helping protect my documents :) Great post!

    ReplyDelete