Merge multiple files into one PDF file in Android

marouene khadhraoui
2 min readNov 3, 2021

Handling files is one of the most intriquet tasks in Android Developement . Often done on the backend side , we sometimes encounter the need to dot it on the Android side . One of the trickest parts is to merge multiple files (pdf , jpg , jpeg , png … ) in one single pdf file . In this article i will present to you my way of doing it , with Kotlin and apache PDFBox open source library .

First of all we need to add the PDF box library to our app level build file :

Now we need the list of files we want to merge :

We start by declaring a list of type FileModel . Each item of this list has to have a uri to access it and a type : PDF or IMAGE .

NB : It is very important to know the type of each file , the process of merge is different for pdf files and images .

Now that we have our list of files ready to merge we proceed to loop through to list and test the type of the current item . But first of all we need to create the final pdf file where we will merge all our files .

Now that we created our file , we can start looping through our list . As mentionned before the process for images and pdf files is different . The idea is to add all the images to a pdf with an image in each page .

Now that we have our first pdf document containing all the images , we have to write it into a pdf utility merger that we created beforehand by converting it into an InputStream .

At this stage we have a pdf file with all the images from out list . Its time to merge all the pdf files . Lets iterate through the list like the first time and merge all the files into the original pdf utility .

All the pdf files are merged into the pdf merger utility “ut” . The last step is to convert this pdf utility merger into a file .

We end up with file2 as a file containing all the files from the list .

Thank you for reading , Share the article and leave a comment . Every interaction is deeply appreciated .

--

--