Jetpack Compose

How to Generate PDF Files using Jetpack Compose

Generate PDF Files using Jetpack Compose example
460views

How to Generate PDF Files using Jetpack Compose. Hi everyone in this android jetpack tutorial I make an example to generate the PDF file. here we design a PDF file format including the logo in the left corner and the site title in the right corner. And Also add directions in the center of the PDF.

So let’s make to start a customer PDF file generate using jetpack compose. Start your Android studio and make a new project choose jetpack activity. after that follow the below steps.

Generate PDF Files using Jetpack Compose example

Step 1:- Gradle Build dependency

dependencies {

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
implementation 'androidx.activity:activity-compose:1.4.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}

match your grade dependency with the Above if there is any missing Please build to syn your project.

Step 2:- Create a Kotlin Class With the Name of generatePdf.

In the Kotlin class, we create Custome UI for the PFD so I try to add images and text in the see below full source code.

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.pdf.PdfDocument
import android.graphics.pdf.PdfDocument.PageInfo
import android.widget.Toast
import androidx.core.content.ContextCompat
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

fun generatePDF(context: Context, directory: File) {
val pageHeight = 1120
val pageWidth = 792
val pdfDocument = PdfDocument()
val paint = Paint()
val title = Paint()
val myPageInfo = PageInfo.Builder(pageWidth, pageHeight, 1).create()
val myPage = pdfDocument.startPage(myPageInfo)
val canvas: Canvas = myPage.canvas
val bitmap: Bitmap? = drawableToBitmap(context.resources.getDrawable(R.drawable.logo))
val scaleBitmap: Bitmap? = Bitmap.createScaledBitmap(bitmap!!, 120, 120, false)
canvas.drawBitmap(scaleBitmap!!, 40f, 40f, paint)
title.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)
title.textSize = 15f
title.color = ContextCompat.getColor(context, R.color.purple_200)
canvas.drawText("Jetpack Compose Tutorial", 400f, 100f, title)
canvas.drawText("Codeplayon Learn share and Explore ", 400f, 80f, title)
title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
title.color = ContextCompat.getColor(context, R.color.purple_200)
title.textSize = 15f
title.textAlign = Paint.Align.CENTER
canvas.drawText("This is sample document which we have created.", 396f, 560f, title)
pdfDocument.finishPage(myPage)
val file = File(directory, "codeplayon.pdf")

try {
pdfDocument.writeTo(FileOutputStream(file))
Toast.makeText(context, "PDF file generated successfylly", Toast.LENGTH_SHORT).show()
} catch (ex: IOException) {
ex.printStackTrace()
}
pdfDocument.close()
}

fun drawableToBitmap(drawable: Drawable): Bitmap? {
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}

Step 3:- Main Activity file Souce code.

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import com.jetpack.generatefilepdf.ui.theme.GenerateFilePDFTheme
import com.jetpack.generatefilepdf.ui.theme.Purple500
import java.io.File

private const val REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE = 34

private fun foregroundPermissionApproved(context: Context): Boolean {
val writePermissionFlag = PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
context, Manifest.permission.WRITE_EXTERNAL_STORAGE
)
val readPermissionFlag = PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
context, Manifest.permission.READ_EXTERNAL_STORAGE
)

return writePermissionFlag && readPermissionFlag
}

private fun requestForegroundPermission(context: Context) {
val provideRationale = foregroundPermissionApproved(context = context)
if (provideRationale) {
ActivityCompat.requestPermissions(
context as Activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
)
} else {
ActivityCompat.requestPermissions(
context as Activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
)
}
}

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GenerateFilePDFTheme {
val context = LocalContext.current
requestForegroundPermission(context)
Surface(color = MaterialTheme.colors.background) {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = "Jetpack Compose Generate PDF File",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Left
)
}
)
}
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(
onClick = {
generatePDF(context, getDirectory())
},
modifier = Modifier
.fillMaxWidth(0.5f)
.height(60.dp)
.padding(10.dp),
shape = RoundedCornerShape(5.dp),
colors = ButtonDefaults.buttonColors(Purple500)
) {
Text(
text = "Submit",
color = Color.White,
fontSize = 13.sp
)
}
}
}
}
}
}
}

private fun getDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() }
}
return if (mediaDir != null && mediaDir.exists()) mediaDir else filesDir
}
}

after implementing the code let’s test Generate PDF Files using the Jetpack Compose example to run your project and see the output. After generating the pdf you can find the pdf on this location on your phone.

How to Generate PDF Files using Jetpack Compose

PDF Location Phone memory Android package name data folder and see with the name codeplayon pdf file

Read More Tutorial