Generate a PDF file in Android 10 Plus Version Working App

 

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 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:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="@+id/btn_generatePDF"
android:layout_height="wrap_content"
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.  

<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. 

package com.example.meyepro.TeacherDashBoard.CHR;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.ContextWrapper;
import android.content.Intent;
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.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.meyepro.R;
import com.example.meyepro.databinding.ActivityTeacherSelectTimTableChractivityBinding;

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 TeacherSelectTimTableCHRActivity extends AppCompatActivity {
ActivityTeacherSelectTimTableChractivityBinding binding;

// 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);
binding= ActivityTeacherSelectTimTableChractivityBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());

// initializing our variables.
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon_dvr_camera_setting);
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();
}
binding.btnGeneratePDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// calling method to
// generate our PDF file.
generatePDF();
write("hello");
}
});

// Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
}
private void write(String message) {
try {
FileOutputStream fileOut = openFileOutput("ali_u.txt", MODE_PRIVATE);
fileOut.write(message.getBytes());
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}

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.

// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
//
// }
// else
// {
//
//
// }
ContextWrapper cw = new ContextWrapper(getApplicationContext());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
// The app has been granted the MANAGE_EXTERNAL_STORAGE permission
File file = new File(String.valueOf(Environment.getExternalStorageDirectory()), "muzamil.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(this, "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// below line is used
// to handle error
e.printStackTrace();
binding.txtCourse.setText(e.toString());
Toast.makeText(this, ""+e.toString(), Toast.LENGTH_SHORT).show();
}
} else {
// The app has not been granted the MANAGE_EXTERNAL_STORAGE permission
// Request the permission from the user
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
}



// 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) {
super.onRequestPermissionsResult(requestCode, permissions, 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();
}
}
}
}
}

 Custom Design Create code  PDF 



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.