Tutorials

Merge PDF Documents on Android

By ComPDFKit | Fri. 17 May. 2024
Document EditorJavaAndroid

We are going to talk about two ways to merge PDF files on Android platforms here. Most apps or systems don't focus on PDF technologies but want to provide the feature of merging PDFs. They can use the APIs or SDK from PDF manufacturers to merge PDF files. But, about Android apps, they have two choices - technology from Android systems or other manufacturers.

 

ComPDFKit is such a manufacturer that provides complete PDF features including viewing, editing (pages & content), annotating, form filling, signing, comparing, redacting, OCR, etc. Our topic is about merging PDFs, you can contact us for more information about other features.



Why Merge PDF Documents?

 

As people rely more and more on mobile devices for both personal and professional use, there come more and more practical feature needs like merging multiple PDF documents on the go. However, this can be a challenge because merging PDF documents is not a default function on most Android devices.

 

For personnel, merging PDF documents is a common feature when you deal with several documents like reports or project proposals. Rather than opening each individual document separately, merging them simplifies the process and makes it easier to track and manage documents.

 

Many app providers integrate PDF Editor into their apps, providing the features like PDF merging, improving user experience, and engaging more end users. A batch of PDF files merging like financial statements, reception vouchers, etc., is often needed by companies and organizations.



Enable Merge PDFs on Your Android System 

 

You can see how Android system merges PDFs in the following sample code. And there will be some problems if you rely on the Android system to merge PDFs. 

 

         - Poor Compatibility and Stability: Maybe a low version of the Android system does not support merging PDFs.

         - Fragmentation of the Android System: There may be some incompatibility problems with different Android devices.

         - Integration: It's hard to integrate and there are no clear document guides. 

         - Version: There might be no update for some versions.

 

List mergeFiles = new ArrayList<>();
   void addMergeFile(Uri pdfUri) {
    String absolutePath = TFileUtils.toPath(mContext, pdfUri);
    if (!TextUtils.isEmpty(absolutePath)) {
      mergeFiles.add(new File(absolutePath));
    }
  }

 

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
void mergePdfUseAndroidSystem() {
    AsyncTask<Void, Void, Boolean> asyncTask = new AsyncTask<Void, Void, Boolean>() {
      @Override
      protected Boolean doInBackground(Void... voids) {
		    addMergeFile(url1);
		    addMergeFile(url2);
		    addMergeFile(url3);

        
        // We need to keep track of the current page when creating the output PDF.
        int currentOutputPage = 0;
        float imageScale = 1.0f;

        
        PdfDocument outputDocument = new PdfDocument();
        Paint bitmapPaint = new Paint();
        Matrix scaleMatrix = new Matrix();
        scaleMatrix.postScale(imageScale, imageScale);

        
        for (File inputFile : mergeFiles) {
          PdfRenderer currentDocument = null;
          try {
            currentDocument = new PdfRenderer(ParcelFileDescriptor.open(inputFile,                                                                      ParcelFileDescriptor.MODE_READ_ONLY));
          } catch (IOException e) {
            throw new RuntimeException(e);
          }

          
          for (int pageIndex = 0; pageIndex < currentDocument.getPageCount(); pageIndex++) {
            PdfRenderer.Page currentPage = currentDocument.openPage(pageIndex);
            PdfDocument.PageInfo outputPageInfo = new    PdfDocument.PageInfo.Builder(currentPage.getWidth(), currentPage.getHeight(), currentOutputPage).create();
            PdfDocument.Page outputPage = outputDocument.startPage(outputPageInfo);

            
            Bitmap pageBitmap = Bitmap.createBitmap(
                (int)(outputPageInfo.getPageWidth() * imageScale),
                (int)(outputPageInfo.getPageWidth() * imageScale),
                Bitmap.Config.ARGB_8888);


            currentPage.render(pageBitmap,
                null,
                scaleMatrix,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);


            outputPage.getCanvas().drawBitmap(pageBitmap,
                new Rect(0, 0, pageBitmap.getWidth(), pageBitmap.getHeight()),
                outputPageInfo.getContentRect(), bitmapPaint);


            outputDocument.finishPage(outputPage);
            currentPage.close();
            ++currentOutputPage;
          }
        }

        
        // Once all pages are copied, write to the output file.
        String savePath = mContext.getCacheDir().getAbsolutePath() + File.separator + "mergeFile/" + System.currentTimeMillis() + ".pdf";
        File outputFile = new File(savePath);
        try {
          outputDocument.writeTo(new FileOutputStream(outputFile));
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
        return true;
      }
    };
    asyncTask.execute();
  }

 

 

Merge PDFs Supported by ComPDFKit 

 

ComPDFKit is a PDF SDK & API service provider that offers a solution to merge PDFs on any device including on your Android apps. It is feature-rich and provides all-in-one PDF technologies which reduces the complexity of integrating multiple SDKs. The merge function of ComPDFKit has a specific asynchronous operation, which allows for multi-thread operations, leading to significantly faster processing of merging.

 

ArrayList pdfFiles = new ArrayList<>();
CPDFDocument mergeDocument;


void openDocList(List list) {
    for (Uri pdfUri: list) {
      CPDFDocument openDocument = new CPDFDocument(mContext);
      CPDFDocument.PDFDocumentError error;
      error = openDocument.open(pdfUri, "");
      if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
        pdfFiles.add(openDocument);
      }
    }
  }

 

void mergePdf() {
   AsyncTask<Void, Void, Boolean> asyncTask = new AsyncTask<Void, Void, Boolea>() {
      @Override
      protected Boolean doInBackground(Void... voids) {
        List uriList = new ArrayList<>();
        uriList.add(uri1); 
        uriList.add(uri2);
        uriList.add(uri3);
		    openDocList(uriList);

		    
        boolean isMerge = false;
        mergeDocument = CPDFDocument.createDocument(mContext);
        for (CPDFDocument item : pdfFiles) {
          bool res = mergeDocument.importPages(item, 0, item.getPageCount() - 1, mergeDocument.getPageCount());
			   if (isMerge == false) {
				    isMerge = res;
			    }
        }
        for (CPDFDocument item : pdfFiles) {
          item.close();
        }
        return isMerge;
      }

      
      @Override
      protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (result) {
          String savePath = mContext.getCacheDir().getAbsolutePath() + File.separator + "mergeFile/" + System.currentTimeMillis() + ".pdf";
          try {
            mergeDocument.saveAs(savePath, false);
          } catch (CPDFDocumentException e) {
            e.printStackTrace();
          }
        }
      }
    };
    asyncTask.execute();
  }



Conclusion

 

Merging PDF documents on Android devices can be a hassle without proper tools. While the default method can be problematic in terms of compatibility, fragmentation, and integration. By using ComPDFKit’s small, highly efficient, and easy-to-integrate SDK, developers can allow users to merge PDF documents with ease, saving them precious time and effort.