Android protect pdf file by passwords

In Android, it is simple to protect a PDF document or file. In this Android tip, I am going to show you how to protect the PDF document using iTextG library. The iTextG library allows you to protect the PDF document by two passwords: user password and owner password. The user password protects the PDF document from being opened. It prompts to enter the user password when you open the protected PDF document in a PDF Viewer application. The owner password sets the permissions to the PDF document. For example, only copying and printing are allowed on the PDF document.



The iTextG library can be downloaded from the link: http://sourceforge.net/projects/itextg/. The extra jar files that you need to add to the libs folder of your project are core-1.51.0.0.jar, pkix-1.51.0.0.jar, and prov-1.51.0.0.jar. These extra jar files are available at GitHub repository (http://rtyley.github.io/spongycastle/).

Now to have an example application on protecting PDF document by passwords, you create a new Android project. Then in the activity_main.xml file, you add two EditTexts, a Button, and a TextView.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"  
   tools:context="com.example.examples.MainActivity"
   android:orientation="vertical"
   >
  
  
<EditText
android:id="@+id/txtuserpwd"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="Enter user password"
android:inputType="textPassword"
/>
   <EditText
android:id="@+id/txtownerpwd"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="Enter owner password"
      android:inputType="textPassword"
   />
   <Button
      android:id="@+id/btprotected"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Protect"
      android:onClick="protect"
     />
   <TextView
     android:id="@+id/txtstatus"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
   />

</LinearLayout>

Here is the code written in the MainActivity class to get the path of a PDF file selected from file explorer, apply passwords to the file, and save the protected PDF file.

public class MainActivity extends Activity{

   private String filepath="";
   private TextView txtStatus;
   private EditText txtUserPwd;
   private EditText txtOwnerPwd;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     txtStatus=(TextView)findViewById(R.id.txtstatus);
     txtUserPwd=(EditText)findViewById(R.id.txtuserpwd);
     txtOwnerPwd=(EditText)findViewById(R.id.txtownerpwd);
     Intent intent=getIntent();
     if(intent!=null){
     String action=intent.getAction();
     String type=intent.getType();
     if((Intent.ACTION_PICK.equals(action) || Intent.ACTION_VIEW.equals(action)) && type.endsWith("pdf")){
     //get the file path from the intent object
     filepath=intent.getData().getPath();
    
     }
     }
  
   }
  
   public void protect(View view){
   BackTask bt=new BackTask();
   if(!filepath.equals(""))
   bt.execute(filepath);
   else
   txtStatus.setText("No PDF file is selected.");
   }
  
   class BackTask extends AsyncTask<String,Void,Void>{
  
   protected void onPreExecute(){
     super.onPreExecute();
     txtStatus.setText("Processing...");
    
   }
   protected Void doInBackground(String...params){
   // User password
   byte[] USER =txtUserPwd.getText().toString().getBytes();
   // Owner password
     byte[] OWNER =txtOwnerPwd.getText().toString().getBytes();
     try {
     // Read the PDF document into PdfReader object
PdfReader reader = new PdfReader(params[0]);

File f=new File(params[0]);
// Create PdfStamper object to modify the existing PDF document
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(f.getParent()+"/protected_"+f.getName()));
// Protect pdf file
// Copying and printing are allowed
stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
stamper.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    
   return null;
   }
   protected void onPostExecute(Void result){
   txtStatus.setText("The Pdf file is protected.");
     }
   }

Before you run the example application, you need to declare WRITE_EXTERNAL_STORAGE permission to allow the application to save data in the device storage. You also declare an intent-filter to allow the application to receive path of the PDF file selected from the file explorer.

<intent-filter>
       <action android:name="android.intent.action.VIEW" />
       <action android:name="android.intent.action.PICK" />
       <category android:name="android.intent.category.DEFAULT" />
           <data android:scheme="file" />
       <data android:mimeType="application/pdf" />
       <data android:pathPattern=".*\\.pdf" />
       <data android:host="*" />
     </intent-filter>


Android-protect-pdf-file-by-passwords

Posted by: Dara | post date: 01-26-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.