Android merge pdf files

In the Split Pdf file tutorial, I showed you how to split a Pdf file into multiple Pdf files using iTextG library. Sometimes, you wish to merge multiple Pdf files into a sing Pdf file. In iTextG, merging Pdf files can be done simply as splitting a Pdf file.
To achieve the goal, first you need to have a list of paths of the source Pdf files. Then you use the PdfReader to read all pages of every source Pdf file and add the pages to a PdfCopy object. In the example application below, you can merge two Pdf files into one Pdf file called meragedresult.pdf. The user is able to select the Pdf files from his/her device by clicking the browser button (...) next to the text boxes. In your phone, you need to install a File Explorer app so that you will be able to choose a Pdf file once you press the browse buttons.



Now let start with the example application. You create a new Android project. Then add two EditTexts, and three Buttons.
<TableLayout xmlns:android= "http://schemas.android.com/apk/res/android"
   xmlns:tools= "http://schemas.android.com/tools"
   android:layout_width= "match_parent"
   android:layout_height= "wrap_content"
   android:stretchColumns="*"
   android:layout_gravity= "center_vertical"
   android:background="#3f18c1d2"
   >

   <TableRow>
     <EditText
        android:id="@+id/txtfirstpdf"
        android:text="Pdf file"
        android:padding="5dip"

        android:layout_span="4" />
     <Button
        android:id="@+id/bt1"
        android:text="..."
        android:tag="fbt"
        android:maxWidth="30dp"
        android:padding="5dip"

        />

   </TableRow>

   <TableRow>
     <EditText
        android:id="@+id/txtsecondpdf"
        android:text="Pdf file"
        android:padding="5dip"
        android:layout_span="4" />
     <Button
        android:id="@+id/bt2"
        android:text="..."
        android:tag="sbt"
        android:padding="5dip"

        />

   </TableRow>

   <TableRow>

     <Button
        android:id="@+id/btmerge"
        android:layout_span="5"
        android:text="Merge"
        android:padding="5dip"
        android:onClick="mergePdfFiles"

        />

   </TableRow>

</TableLayout>


Here is the code written in the MainActivity class to allow the user to select Pdf files from the device and merge them. The result file is in the sdcard directory. Do not forget to declare WRITE_EXTERNAL_STORAGE permission in the AndroidManifest.xml file.

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;

public class MainActivity extends FragmentActivity {
   private EditText txt1,txt2;
   private Button bt1,bt2;
   private Handler handler;
   private final int PICKFILE_RESULT_CODE=10;
   private String btTag="";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     txt1=(EditText)findViewById(R.id.txtfirstpdf);
     txt2=(EditText)findViewById(R.id.txtsecondpdf);
     bt1=(Button)findViewById(R.id.bt1);
     bt2=(Button)findViewById(R.id.bt2);
     bt1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             btTag=((Button)v).getTag().toString();
             showFileChooser();
            
        }
     });
     bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             btTag=((Button)v).getTag().toString();
             showFileChooser();
            
        }
     });


   public void mergePdfFiles(View view){
     try {
        String[] srcs = {txt1.getText().toString(), txt2.getText().toString()};
        mergePdf(srcs);
     }catch (Exception e){e.printStackTrace();}
   }

   public void mergePdf(String[] srcs){
     try{
        // Create document object
        Document document = new Document();
        // Create pdf copy object to copy current document to the output mergedresult file
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(Environment.getExternalStorageDirectory()+"/mergedresult.pdf"));
        // Open the document
        document.open();
        PdfReader pr;
        int n;
        for (int i = 0; i < srcs.length; i++) {
           // Create pdf reader object to read each input pdf file
           pr = new PdfReader(srcs[i].toString());
           // Get the number of pages of the pdf file
           n = pr.getNumberOfPages();
           for (int page = 1; page <=n;page++) {
             // Import all pages from the file to PdfCopy
             copy.addPage( copy.getImportedPage(pr,page));
           }
        }
        document.close(); // close the document

     }catch(Exception e){e.printStackTrace();}
   }


   @Override
   // Save tag of the clicked button
   // It is used to identify the button has been pressed
   public void onSaveInstanceState( Bundle outState) {
     super.onSaveInstanceState(outState);
     outState.putString("savText", btTag);
    

   }

   @Override
   // Restore the tag
   protected void onRestoreInstanceState( Bundle savedInstanceState) {
     super.onRestoreInstanceState( savedInstanceState);
     btTag=savedInstanceState.getString( "savText");
    
   }

   private void showFileChooser(){
     Log.e("AA","bttag="+btTag);
     String folderPath = Environment. getExternalStorageDirectory()+"/";
     Intent intent = new Intent();
     intent.setAction( Intent.ACTION_GET_CONTENT);
     Uri myUri = Uri.parse(folderPath);
     intent.setDataAndType( myUri ,"file/*");
     Intent intentChooser = Intent.createChooser(intent, "Select a file");
     startActivityForResult(intentChooser, PICKFILE_RESULT_CODE);
   }

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {

     if (data != null) {
        if (requestCode == PICKFILE_RESULT_CODE) {
           if (resultCode == RESULT_OK) {
             String FilePath = data.getData().getPath();
             if(bt1.getTag().toString().equals(btTag))
                txt1.setText(FilePath);
             else
                txt2.setText(FilePath);

           }
        }
     }
   }
  
}

Android-merge-pdf-files

Posted by: Dara | post date: 03-05-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.