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.
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.
👉 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) } }
👉 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.
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.
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.
Register Now for the Masterclass to Epic Integration with SMART on FHIR Webinar on Thursday, 10th April 2025 at: 11:00 AM EDT
Register NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork