Kotlin Generate PDF With Images

Pdf generation is the most commonly used function in most native applications. To create documents, we can easily use the library to generate PDF. After a long time, I have worked with itext-PDF.

The most difficult part of the pdf creation process is creating and downloading PDF in the background process. And on top of that, if we have to show images in PDF, that creates a PDF in the background, it’s too difficult to handle.

ūüĒĻ Add Library

implementation 'com.itextpdf:itext7-core:7.1.13'

Add this library to create a PDF; one more library can be added to work in the background.

implementation 'androidx.work:work-runtime-ktx:2.6.0'

These two main libraries are used to generate and download the PDF (save) simultaneously.

ūüĒĻ Source File


ūüĎČ In this activity, firstly, we will show the data with an image and the download button to generate and save the PDF on the device.¬†

ūüĎČ To create and save the PDF in the background process here, we will use a work manager who will work as a service class.

ūüĎČ Before generating the PDF, we will check for the permissions and then allow how to generate the PDF. As we can see, we have a model class in which we are storing data, and the same data will be serialized in a string and will send over the request to the download class.¬†

class MainActivity : AppCompatActivity() {

   lateinit var binder: ActivityMainBinding

   var pdfResultModel = PdfResultModel()


   val STORAGE = arrayOf(




   override fun onCreate(savedInstanceState: Bundle?) {


       binder = DataBindingUtil.setContentView(this, R.layout.activity_main)



   private fun initialization() {

       pdfResultModel = PdfResultModel(

           "PDF generate",

           "check the pdf download",

           "Generate pdf with image and save in folder",



       binder.pdfResult = pdfResultModel




       binder.download.setOnClickListener {




   private fun setupPermissions() {

       val permission = ContextCompat.checkSelfPermission(




       if (permission != PackageManager.PERMISSION_GRANTED) {


       } else {




   private fun makeRequest() {







   override fun onRequestPermissionsResult(

       requestCode: Int,

       permissions: Array<out String>,

       grantResults: IntArray

   ) {

       super.onRequestPermissionsResult(requestCode, permissions, grantResults)

       when (requestCode) {

           RECORD_REQUEST_CODE -> {

               if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {

                   Log.i("Pdf", "Permission has been denied by user")

               } else {

                   Log.i("pdf", "Permission has been granted by user")

                   //   showToast(resources.getString(androidx.work.R.string.downloading_file))






   // Serialize a single object.

   fun serializeToJson(any: Any): String {

       val gson = Gson();

       return gson.toJson(any);


   fun callVisitDownload() {

       val pdfString: String = serializeToJson(pdfResultModel)

       val data = Data.Builder()

           .putString("data", pdfString)


       val constraints = Constraints.Builder()


       val oneTimeRequest =









ūüĎČ To create a PDF, we are using¬†the itext PDF library, which is very easy and simple to implement.

ūüĎČ In the download manager class, firstly, we will check if there is any input data from the request and will deserialize data into the model class.

ūüĎČ To generate a PDF with the image, firstly, we must make sure that the image is already in the folder, or if it is in the URL form, then we need to download it to the particular folder. After downloading it, only we can use that image to generate the PDF.

ūüĎČ It means that the image should already be in the folder to generate a PDF with the images.¬†

ūüĎČ We cannot directly use the image URL to create the PDF document.¬†

ūüĎČ So to check whether the image has been downloaded in the folder or not, we have created a method download file in a device in which we will return the count of the image path so that we can check whether the image is downloaded or not and then from that counts we will call the create PDF method.¬†

Hire Android App Developer

class DownloadImageMangerPDF(private val mContext: Context, workerParameters: WorkerParameters) :

   Worker(mContext, workerParameters) {

   val Tags = DownloadImageMangerPDF::class.java.simpleName

   val directoryPath = Environment.DIRECTORY_DOWNLOADS +

           "/PDF/" + "temp/"

   private val re = Regex("[^A-Za-z0-9 ]")

   override fun doWork(): Result {

       try {

           val data: Data = inputData

           val pdfString: String = data.getString("data").toString()

           Log.i("visit","pdf $pdfString")

           if (pdfString != null) {

               val pdfResult = pdfString.let { deserializeFromJsonNote(it) }

               var cnt = pdfResult.image?.let { it1 ->     downloadFileInDevice1(it1) }


               val imagePath: ArrayList<String> by lazy { ArrayList() }

               if (pdfResult.image != null) {


                   val path = Environment.getExternalStoragePublicDirectory(

                       directoryPath + getFileName(pdfResult.image)




               if (cnt == imagePath.size) {

                   val resultVisit = createAndDownLoadPdf(






           return Result.success()

       } catch (e: Exception) {

           return Result.failure()



   fun createAndDownLoadPdf(

       pdfResult: PdfResultModel,

       signpath: List<String>

   ): String {

       try {

           val path = Environment.getExternalStoragePublicDirectory(

               Environment.DIRECTORY_DOWNLOADS + "/PDF/"


           val tsLong = System.currentTimeMillis() / 1000

           val ts = tsLong.toString()

           if (!path.exists()) path.mkdirs()

           val file = File(path, pdfResult.txtNoteName?.replace(re, "_") + "_"  + ts + ".pdf")

           val fOut = FileOutputStream(file)

           val pdfWriter = PdfWriter(fOut)

           val pdfDocument = PdfDocument(pdfWriter)

           val document = Document(pdfDocument)

¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†val font = PdfFontFactory.createFont(‚Äúyour desired font‚ÄĚ)

           val mValueFontSize = 12.0f

           val mHeadingFontSize = 16.0f

           val fixed = 2f

           val multiplied = 0f

           //note name

           val colon = " :"

           val text1 = Text("Note name" + colon).setFont(font)


           val mTitleParagraph = Paragraph()




 val text =  Text(pdfResult.txtNoteName).setFont(font).


           val mNoteNamedParagraph1 = Paragraph()




           val text17 = Text("notes" + colon).setFont(font)


           val mNotesParagraph = Paragraph()




   val text18 = Text(pdfResult.txtNoteData).setFont(font)


           val mNotesValueParagraph = Paragraph()





           val text23 = Text("Comments" + colon).setFont(font)


           val mCommentParagraph = Paragraph()





           val text24 = Text(pdfResult.txtCommentData).setFont(font)


           val mCommentValueParagraph = Paragraph()



           for (element in signpath) {

               try {



                   val data1: ImageData = ImageDataFactory.create(element)

                   val img1 = Image(data1)

                   img1.scaleToFit(200f, 200f)


               } catch (ex: Exception) {





           return "pdf"

       } catch (e: IOException) {

           return ("error_download")



   fun downloadFileInDevice1(

       stringUrl: String,

   ): Int {

       var count: Int

       val urgiDocPath = Environment.getExternalStoragePublicDirectory(



       if (!urgiDocPath.exists()) urgiDocPath.mkdirs()

       if (stringUrl.contains("https")) {

           val path = Environment.getExternalStoragePublicDirectory(

               directoryPath + getFileName(stringUrl)


           try {

               val url = URL(stringUrl)

               val conection: URLConnection = url.openConnection()


               // download the file

val input: InputStream = BufferedInputStream(url.openStream(),  8192)

               // Output stream

               val output: OutputStream = FileOutputStream(path)

               val data = ByteArray(1024)

               var total: Long = 0

               while (input.read(data).also { count = it } !== -1) {

                   total += count

                   output.write(data, 0, count)





               return 1

           } catch (e: Exception) {




       return 0


   // Deserialize a single object.

   fun deserializeFromJsonNote(str: String): PdfResultModel {

       val gson = Gson();

       return gson.fromJson(str, PdfResultModel::class.java)


   fun getFileName(url: String?): String {

       val splitArray = url?.split("/")

       return splitArray?.get(splitArray.size - 1) ?: ""



You can also check the source code here.



In this blog, we have seen kotlin generate PDF in android, using the itextPdf library. And this could help developers to generate PDFs in the background thread. So here we conclude the tutorial on how to work on PDF in android.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!