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

MainActivity.java

👉 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 RECORD_REQUEST_CODE = 1

   val STORAGE = arrayOf(

       Manifest.permission.READ_EXTERNAL_STORAGE,

       Manifest.permission.WRITE_EXTERNAL_STORAGE

   )


   override fun onCreate(savedInstanceState: Bundle?) {

       super.onCreate(savedInstanceState)

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

       initialization()

   }


   private fun initialization() {

       pdfResultModel = PdfResultModel(

           "PDF generate",

           "check the pdf download",

           "Generate pdf with image and save in folder",

           "https://developer.android.com/images/activity_lifecycle.png"

       )

       binder.pdfResult = pdfResultModel



       Glide.with(this)

           .load(pdfResultModel.image.toString())

           .into(binder.imgSignature)


       binder.download.setOnClickListener {

           setupPermissions()

       }

   }


   private fun setupPermissions() {

       val permission = ContextCompat.checkSelfPermission(

           this,

           STORAGE[0]

       )


       if (permission != PackageManager.PERMISSION_GRANTED) {

           makeRequest()

       } else {

           callVisitDownload()

       }

   }


   private fun makeRequest() {

       ActivityCompat.requestPermissions(

           this,

           STORAGE,

           RECORD_REQUEST_CODE

       )

   }


   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))

                   callVisitDownload()


               }

           }

       }

   }


   // 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)

           .build()


       val constraints = Constraints.Builder()

           .setRequiredNetworkType(NetworkType.CONNECTED)


       val oneTimeRequest =

           OneTimeWorkRequest.Builder(DownloadImageMangerPDF::class.java)

               .setInputData(data)

               .setConstraints(constraints.build())

               .addTag("visit")

               .build()


       WorkManager.getInstance(this).enqueue(oneTimeRequest)

   }
}

DownloadImageMangerPDF

👉 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) }


               Log.i("visit",cnt.toString())

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




               if (pdfResult.image != null) {

                   downloadFileInDevice1(pdfResult.image)

                   val path = Environment.getExternalStoragePublicDirectory(

                       directoryPath + getFileName(pdfResult.image)

                   )

                   imagePath.add(path.toString())

               }

               if (cnt == imagePath.size) {

                   val resultVisit = createAndDownLoadPdf(

                       pdfResult,

                       imagePath

                   )

               }

           }


           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)

               .setFontSize(mHeadingFontSize)

           val mTitleParagraph = Paragraph()

           mTitleParagraph.setFixedLeading(fixed)

           mTitleParagraph.add(text1)

           document.add(mTitleParagraph)


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

setFontSize(mValueFontSize)

           val mNoteNamedParagraph1 = Paragraph()

           mNoteNamedParagraph1.add(text)

           document.add(mNoteNamedParagraph1)


           //Notes

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

               .setFontSize(mHeadingFontSize)


           val mNotesParagraph = Paragraph()

           mNotesParagraph.add(text17)

           mNotesParagraph.setFixedLeading(fixed)

           document.add(mNotesParagraph)


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

               .setFontSize(mValueFontSize)

           val mNotesValueParagraph = Paragraph()

           mNotesValueParagraph.add(text18)

           document.add(mNotesValueParagraph)

           document.add(Paragraph())


           //comment

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

               .setFontSize(mHeadingFontSize)

           val mCommentParagraph = Paragraph()

           mCommentParagraph.setFixedLeading(fixed)

           mCommentParagraph.add(text23)

           document.add(mCommentParagraph)

           document.add(Paragraph())



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

               .setFontSize(mValueFontSize)

           val mCommentValueParagraph = Paragraph()

           mCommentValueParagraph.add(text24)

           document.add(mCommentValueParagraph)



           for (element in signpath) {

               try {

                   document.add(Paragraph())

                   document.add(Paragraph())

                   val data1: ImageData = ImageDataFactory.create(element)

                   val img1 = Image(data1)

                   img1.scaleToFit(200f, 200f)

                   document.add(img1)


               } catch (ex: Exception) {

                   ex.printStackTrace()




               }

           }


           document.close()

           return "pdf"


       } catch (e: IOException) {

           return ("error_download")


       }

   }


   fun downloadFileInDevice1(

       stringUrl: String,

   ): Int {

       var count: Int

       val urgiDocPath = Environment.getExternalStoragePublicDirectory(

           directoryPath

       )

       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()

               conection.connect()

               // 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)

               }

               output.flush()




               output.close()

               input.close()

               return 1




           } catch (e: Exception) {

               e.printStackTrace()

           }

       }



       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.

coma

Conclusion

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

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?