Android developmentAndroid tutorial

How to create PDF file in Android and save to phone 2022

How to create PDF file in Android
237views

How to create PDF file in Android. There are numerous apps in which the data in the app is made available to users as PDF format that can be downloaded. In this instance, we must create a PDF file using the data contained within the app and display the information in a proper manner within our application. This way, we can create an entirely new PDF based on our requirements. This article we’ll examine the process of making a brand new PDF by using the data in the Android application and saving the PDF file to the external storage on the device used by the user.

To create a new PDF file using the information contained in our Android application, we’ll use Canvas. Canvas is a predefined class within Android that is used to draw 2D images of different objects that we see on our screens. In this post we will use canvas to draw the data we want to display on the canvas. Then, we will save that canvas as the form of a PDF. We will now move on to the actualization of our idea.

Example for create PDF file in Android

Below is the example GIF in which we’ll discover what we will create within this post. It is important to note that this application was constructed using the Java technology. In this application we’ll show a button that is simple. After pressing the button, the PDF will get created and we will be able to view this PDF file within our files

How to create PDF file in Android with Example

Step 1: Create a New Project

To create a brand new project using Android Studio Please refer to How to Start an A New Project using Android Studio. Make sure you choose Java for the language of programming. create PDF file in Android.

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

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

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

Step 3  activity_main.xml file for Making UI

Visit your activity_main.xml file and reference the following code. Here i add a button when click in buton create PDF file in Android and save in your device.

 

<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--Button for Create the PDF file-->
<Button
    android:id="@+id/BtnCreatePDF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="Generate PDF" />

</RelativeLayout>

Step 4:  MainActivity.java file 

Navigate to your MainActivity.java file and reference the code below. Here is the source code of the MainActivity.java file. Commentary is added to the code to help understand the code better. Here i impliment s and create PDF file UI and adding text in pdf, Image and paragrap also.

 

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;

    int pageHeight = 1120;
    int pagewidth = 792;

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

        if (checkPermission()) {
            Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
        } else {
            requestPermission();
        }

        generatePDFbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                generatePDF();
            }
        });
    }

    private void generatePDF() {
        PdfDocument pdfDocument = new PdfDocument();
        Paint paint = new Paint();
        Paint title = new Paint();

        PdfDocument.PageInfo mypageInfo = new 
PdfDocument.PageInfo.Builder(pagewidth, pageHeight, 1).create();
        PdfDocument.Page myPage = pdfDocument.startPage(mypageInfo);

        Canvas canvas = myPage.getCanvas();
        canvas.drawBitmap(scaledbmp, 56, 40, paint);
        title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
        title.setTextSize(15);
        title.setColor(ContextCompat.getColor(this, R.color.purple_200));
        canvas.drawText("Codeplayon", 209, 100, title);
        canvas.drawText("simple learn share and explore ", 209, 80, title);
        title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        title.setColor(ContextCompat.getColor(this, R.color.purple_200));
        title.setTextSize(15);
        title.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("This is sample document which we have created.", 
396, 560, title);
        pdfDocument.finishPage(myPage);
        File file = new File(Environment.getExternalStorageDirectory(), "codeplayon.pdf");

        try {
 
            pdfDocument.writeTo(new FileOutputStream(file));

            Toast.makeText(this, "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
       
            e.printStackTrace();
        }
        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) {

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

 

now your example App create PDF file in Android is ready run your App and check it. In the Next Blog i will share to create PDF with table Data and add data from the API call.

Read More Tutorial