La mayoría de las aplicaciones brindan a los usuarios la posibilidad de descargar facturas desde las aplicaciones móviles. Este tipo de aplicación obtiene los datos de APIS o datos dentro de la aplicación y estos datos se utilizan para generar los archivos PDF. Los archivos PDF dentro de Android se generan usando canvas. En este artículo, veremos cómo generar un archivo PDF en Android usando Kotlin.
Nota : si está buscando generar archivos PDF en una aplicación de Android usando Java. Consulte el siguiente artículo: Cómo generar archivos PDF en Android usando Java
Implementación paso a paso
Paso 1: crea un nuevo proyecto en Android Studio
Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Tenga en cuenta que seleccione Kotlin como lenguaje de programación.
Paso 2: trabajar con el archivo activity_main.xml
Vaya a la aplicación > res > diseño > actividad_principal.xml y agregue el siguiente código a ese archivo. A continuación se muestra el código para el archivo activity_main.xml . Se agregan comentarios dentro del código para comprender el código con más detalle.
XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--on below line we are creating a simple text view for heading--> <TextView android:id="@+id/idTVHead" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="50dp" android:layout_marginEnd="20dp" android:gravity="center" android:padding="8dp" android:text="PDF Generator" android:textAlignment="center" android:textColor="@color/purple_200" android:textSize="20sp" android:textStyle="bold" /> <!--on below line we are creating a button to generate a pdf file--> <Button android:id="@+id/idBtnGeneratePdf" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="20dp" android:padding="4dp" android:text="Generate PDF" android:textAllCaps="false" /> </RelativeLayout>
Paso 3: agregue permiso para leer y escribir en el almacenamiento externo
Vaya a la aplicación > archivo AndroifManifest.xml y agréguele los siguientes permisos.
XML
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Paso 4: agregar imágenes a la carpeta dibujable
Copie su imagen y luego navegue a la aplicación> res> dibujable> Haga clic con el botón derecho en ella y simplemente pegue sus imágenes dentro de la carpeta dibujable.
Paso 5: trabajar con el archivo MainActivity.kt
Vaya al archivo MainActivity.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.
Kotlin
package com.gtappdevelopers.kotlingfgproject import android.Manifest.permission.READ_EXTERNAL_STORAGE import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.content.pm.PackageManager import android.graphics.* import android.graphics.pdf.PdfDocument import android.os.Build import android.os.Bundle import android.os.Environment import android.widget.Button import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import java.io.File import java.io.FileOutputStream class MainActivity : AppCompatActivity() { // on below line we are creating // a variable for our image view. lateinit var generatePDFBtn: Button // declaring width and height // for our PDF file. var pageHeight = 1120 var pageWidth = 792 // creating a bitmap variable // for storing our images lateinit var bmp: Bitmap lateinit var scaledbmp: Bitmap // on below line we are creating a // constant code for runtime permissions. var PERMISSION_CODE = 101 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // on below line we are initializing our button with its id. generatePDFBtn = findViewById(R.id.idBtnGeneratePdf) // on below line we are initializing our bitmap and scaled bitmap. bmp = BitmapFactory.decodeResource(resources, R.drawable.android) scaledbmp = Bitmap.createScaledBitmap(bmp, 140, 140, false) // on below line we are checking permission if (checkPermissions()) { // if permission is granted we are displaying a toast message. Toast.makeText(this, "Permissions Granted..", Toast.LENGTH_SHORT).show() } else { // if the permission is not granted // we are calling request permission method. requestPermission() } // on below line we are adding on click listener for our generate button. generatePDFBtn.setOnClickListener { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { // on below line we are calling generate // PDF method to generate our PDF file. generatePDF() } } } // on below line we are creating a generate PDF method // which is use to generate our PDF file. @RequiresApi(Build.VERSION_CODES.KITKAT) fun generatePDF() { // creating an object variable // for our PDF document. var pdfDocument: PdfDocument = PdfDocument() // two variables for paint "paint" is used // for drawing shapes and we will use "title" // for adding text in our PDF file. var paint: Paint = Paint() var title: Paint = Paint() // we are adding page info to our PDF file // in which we will be passing our pageWidth, // pageHeight and number of pages and after that // we are calling it to create our PDF. var myPageInfo: PdfDocument.PageInfo? = PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create() // below line is used for setting // start page for our PDF file. var myPage: PdfDocument.Page = pdfDocument.startPage(myPageInfo) // creating a variable for canvas // from our page of PDF. var canvas: Canvas = myPage.canvas // below line is used to draw our image on our PDF file. // the first parameter of our drawbitmap method is // our bitmap // second parameter is position from left // third parameter is position from top and last // one is our variable for paint. canvas.drawBitmap(scaledbmp, 56F, 40F, paint) // below line is used for adding typeface for // our text which we will be adding in our PDF file. title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)) // below line is used for setting text size // which we will be displaying in our PDF file. title.textSize = 15F // below line is sued for setting color // of our text inside our PDF file. title.setColor(ContextCompat.getColor(this, R.color.purple_200)) // below line is used to draw text in our PDF file. // the first parameter is our text, second parameter // is position from start, third parameter is position from top // and then we are passing our variable of paint which is title. canvas.drawText("A portal for IT professionals.", 209F, 100F, title) canvas.drawText("Geeks for Geeks", 209F, 80F, title) title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)) title.setColor(ContextCompat.getColor(this, R.color.purple_200)) title.textSize = 15F // below line is used for setting // our text to center of PDF. title.textAlign = Paint.Align.CENTER canvas.drawText("This is sample document which we have created.", 396F, 560F, title) // after adding all attributes to our // PDF file we will be finishing our page. pdfDocument.finishPage(myPage) // below line is used to set the name of // our PDF file and its path. val file: File = File(Environment.getExternalStorageDirectory(), "GFG.pdf") try { // after creating a file name we will // write our PDF file to that location. pdfDocument.writeTo(FileOutputStream(file)) // on below line we are displaying a toast message as PDF file generated.. Toast.makeText(applicationContext, "PDF file generated..", Toast.LENGTH_SHORT).show() } catch (e: Exception) { // below line is used // to handle error e.printStackTrace() // on below line we are displaying a toast message as fail to generate PDF Toast.makeText(applicationContext, "Fail to generate PDF file..", Toast.LENGTH_SHORT) .show() } // after storing our pdf to that // location we are closing our PDF file. pdfDocument.close() } fun checkPermissions(): Boolean { // on below line we are creating a variable for both of our permissions. // on below line we are creating a variable for // writing to external storage permission var writeStoragePermission = ContextCompat.checkSelfPermission( applicationContext, WRITE_EXTERNAL_STORAGE ) // on below line we are creating a variable // for reading external storage permission var readStoragePermission = ContextCompat.checkSelfPermission( applicationContext, READ_EXTERNAL_STORAGE ) // on below line we are returning true if both the // permissions are granted anf returning false // if permissions are not granted. return writeStoragePermission == PackageManager.PERMISSION_GRANTED && readStoragePermission == PackageManager.PERMISSION_GRANTED } // on below line we are creating a function to request permission. fun requestPermission() { // on below line we are requesting read and write to // storage permission for our application. ActivityCompat.requestPermissions( this, arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE), PERMISSION_CODE ) } // on below line we are calling // on request permission result. override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) // on below line we are checking if the // request code is equal to permission code. if (requestCode == PERMISSION_CODE) { // on below line we are checking if result size is > 0 if (grantResults.size > 0) { // on below line we are checking // if both the permissions are granted. if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // if permissions are granted we are displaying a toast message. Toast.makeText(this, "Permission Granted..", Toast.LENGTH_SHORT).show() } else { // if permissions are not granted we are // displaying a toast message as permission denied. Toast.makeText(this, "Permission Denied..", Toast.LENGTH_SHORT).show() finish() } } } } }
Ahora ejecute su aplicación para ver el resultado.
Salida :
Publicación traducida automáticamente
Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA