The Wayback Machine - https://web.archive.org/web/20240624032553/https://www.geeksforgeeks.org/how-to-generate-a-pdf-file-in-android-app/
Open In App

How to Generate a PDF file in Android App?

Last Updated : 20 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There are many apps in which data from the app is provided to users in the downloadable PDF file format. So in this case we have to create a PDF file from the data present inside our app and represent that data properly inside our app. So by using this technique we can easily create a new PDF according to our requirement. In this article, we will take a look at creating a new PDF file from the data present inside your Android app and saving that PDF file in the external storage of the users’ device. So for generating a new PDF file from the data present inside our Android app we will be using Canvas. Canvas is a predefined class in Android which is used to make 2D drawings of the different object on our screen. So in this article, we will be using canvas to draw our data inside our canvas, and then we will store that canvas in the form of a PDF. Now we will move towards the implementation of our project. 

Example of Generating a PDF File

Below is the sample GIF in which we will get to know what we are going to build in this article. Note that this application is built using Java language. In this project, we are going to display a simple button. After clicking the button our PDF file will be generated and we can see this PDF file saved in our files. 

Generate a PDF file in Android App

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--Button for generating the PDF file-->
    <Button
        android:id="@+id/idBtnGeneratePDF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Generate PDF" />
     
</RelativeLayout>


 
Step 3: Add permission for reading and writing in the External Storage

Navigate to the app > AndroifManifest.xml file and add the below permissions to it.  

XML




<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


 
Step 4: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. 

Java




import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
 
public class MainActivity extends AppCompatActivity {
 
    // variables for our buttons.
    Button generatePDFbtn;
     
    // declaring width and height
    // for our PDF file.
    int pageHeight = 1120;
    int pagewidth = 792;
     
    // creating a bitmap variable
    // for storing our images
    Bitmap bmp, scaledbmp;
     
    // constant code for runtime permissions
    private static final int PERMISSION_REQUEST_CODE = 200;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing our variables.
        generatePDFbtn = findViewById(R.id.idBtnGeneratePDF);
        bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gfgimage);
        scaledbmp = Bitmap.createScaledBitmap(bmp, 140, 140, false);
 
        // below code is used for
          // checking our permissions.
        if (checkPermission()) {
            Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
        } else {
            requestPermission();
        }
 
        generatePDFbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method to
                  // generate our PDF file.
                generatePDF();
            }
        });
    }
 
    private void generatePDF() {
        // creating an object variable
        // for our PDF document.
        PdfDocument pdfDocument = new PdfDocument();
         
        // two variables for paint "paint" is used
        // for drawing shapes and we will use "title"
        // for adding text in our PDF file.
        Paint paint = new Paint();
        Paint title = new 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.
        PdfDocument.PageInfo mypageInfo = new PdfDocument.PageInfo.Builder(pagewidth, pageHeight, 1).create();
         
        // below line is used for setting
        // start page for our PDF file.
        PdfDocument.Page myPage = pdfDocument.startPage(mypageInfo);
         
        // creating a variable for canvas
        // from our page of PDF.
        Canvas canvas = myPage.getCanvas();
         
        // 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, 56, 40, 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.setTextSize(15);
         
        // 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.", 209, 100, title);
        canvas.drawText("Geeks for Geeks", 209, 80, title);
 
        // similarly we are creating another text and in this
        // we are aligning this text to center of our PDF file.
        title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        title.setColor(ContextCompat.getColor(this, R.color.purple_200));
        title.setTextSize(15);
         
        // below line is used for setting
        // our text to center of PDF.
        title.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("This is sample document which we have created.", 396, 560, 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.
        File file = new File(Environment.getExternalStorageDirectory(), "GFG.pdf");
 
        try {
            // after creating a file name we will
            // write our PDF file to that location.
            pdfDocument.writeTo(new FileOutputStream(file));
             
            // below line is to print toast message
            // on completion of PDF generation.
            Toast.makeText(MainActivity.this, "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // below line is used
            // to handle error
            e.printStackTrace();
        }
        // after storing our pdf to that
        // location we are closing our PDF file.
        pdfDocument.close();
    }
 
    private boolean checkPermission() {
        // checking of permissions.
        int permission1 = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
        int permission2 = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
        return permission1 == PackageManager.PERMISSION_GRANTED && permission2 == PackageManager.PERMISSION_GRANTED;
    }
 
    private void requestPermission() {
        // requesting permissions if not provided.
        ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0) {
                 
                // after requesting permissions we are showing
                // users a toast message of permission granted.
                boolean writeStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean readStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
 
                if (writeStorage && readStorage) {
                    Toast.makeText(this, "Permission Granted..", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Permission Denied.", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }
}


Output:

 



Similar Reads

Generate PDF File in Android using Kotlin
Most of the applications provide users with the facility of bills to be downloaded from the mobile applications. This type of application gets the data from the APIS or data within the application and this data is used to generate the PDF files. PDF files within android are generated using canvas. In this article, we will take a look at How to gene
7 min read
Generate PDF File in Android using Jetpack Compose
There are many apps in which data from the app is provided to users in the downloadable PDF file format. So in this case we have to create a PDF file from the data present inside our app and represent that data properly inside our app. So by using this technique we can easily create a new PDF according to our requirements. In this article, we will
10 min read
How to Build PDF Downloader App in Android with Kotlin?
If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-content/uploads/202210
4 min read
Extract Data From PDF File using Android Jetpack Compose
PDF files are used in many android applications for displaying data in the form of images, text as well as graphics. Many applications are also required to get the data from this PDF file and display this data within the android application. So for extracting the data from PDF file pdf reader is used which is used to read pdf and get the data from
6 min read
How to Extract Data from PDF file in Android?
PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the PDF file and to display that data inside our app.
4 min read
How to Retrieve PDF File From Firebase Realtime Database in Android?
When we are creating an android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from firebase. Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, datab
8 min read
Extract Data From PDF File in Android using Kotlin
PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched to overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the PDF file and display that data inside our app.
5 min read
How to Integrate In-App Review API into Android App?
Once we publish our app over the PlayStore and as it became live there, app rating and reviews become very crucial to driving audience and downloads to your app. In order to increase this, we ask our users to rate the app through a popup window and redirecting them to the PlayStore. But this nowadays creates little problems, once users went to Play
3 min read
How to Share Text of Your App with Another App and Vice Versa in Android?
Most of the time while using an app we want to share text from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android intent resolver is used when sending data to another app as part of a well-defined task flow. To use the Android
5 min read
How to Share Image of Your App with Another App in Android?
Most of the time while using an app we want to share images from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android Intent resolver is used when sending data to another app as part of a well-defined task flow. To use the Androi
4 min read
three90RightbarBannerImg