How to convert android LinearLayout to PDF in android

Convert LinearLayout to PDF view without using the external library in android studio

Overview

we’ll make such an app that you can convert LinearLayout to a PDF file.

We’ll use two images and three TextView under LinearLayout.

When clicking on the button PDF file automatically download and open it.

We’ll convert LinearLayout to PDF files easily. 

What is covered in this app?

In this tutorial, we’ll convert LinearLayout view to a PDF file.

We’ll use some components in XML and java programmatically.

such as Some image and text views.

ImageButton as download.

Also Read: show popup DatePicker when clicking on EditText android

Java method and user permission.

Quick overview of the app

When you click on the download button, the PDF file is automatically downloaded.

Not only does it get downloaded but will also open automatically.

You can use any number of Images or TextView under LinearLayout.

Note: Make sure your device has a PDF viewer.

Let us understand with step by step example.

How to LinearLayout convert it into a PDF file and open it?

Step 1:

In this step, we will open Android Studio and start a new Android Studio project.

Step 2:

In this step, fill all the basic required fields especially project name and minimum SDK.

Step 3:

Now, start converting LinearLayout to a PDF file.

First, we will create a UI design.

Open activity_main.xml.

Change the view ConstraintLayout to LinearLayout.

Next, use the ImageButton as a download.

The code of ImageButton is given below.

<ImageButton
        android:id="@+id/btnd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#FF5722"
        app:srcCompat="@android:drawable/stat_sys_download" />

Then after we’ll use the scroll view

below is given scroll view XML code.

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff">

Now, we’ll use Main download LinearLayout.

    <LinearLayout
            android:id="@+id/lineard"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            android:orientation="vertical">

Under Linear Layout you can use any components like image button text or more any things that you like.

In this tutorial app, we will use two images and two TextView.

Also Read: Toast Message in android

Below code of ImageView and TextView.

        <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:textSize="25sp" />

            <ImageView
                android:paddingTop="30dp"
                android:id="@+id/imageView"
                android:layout_width="250sp"
                android:layout_height="250sp"
                android:layout_gravity="center"/>
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:layout_marginLeft="10dp"
                android:text="view Download"
                android:textSize="25sp" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="250sp"
                android:layout_height="250sp"
                android:layout_gravity="center"
                android:layout_marginTop="25sp"/>
            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:layout_marginLeft="10dp"
                android:text="view Download"
                android:textSize="25sp" />

Let’s view the full code of the activity_main.xml file

App -> res -> Layout ->activity_main.xml

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/btnd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#FF5722"
        app:srcCompat="@android:drawable/stat_sys_download" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff">

        <LinearLayout
            android:id="@+id/lineard"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:textSize="25sp" />

            <ImageView
                android:paddingTop="30dp"
                android:id="@+id/imageView"
                android:layout_width="250sp"
                android:layout_height="250sp"
                android:layout_gravity="center"/>
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:layout_marginLeft="10dp"
                android:text="view Download"
                android:textSize="25sp" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="250sp"
                android:layout_height="250sp"
                android:layout_gravity="center"
                android:layout_marginTop="25sp"/>
            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:layout_marginLeft="10dp"
                android:text="view Download"
                android:textSize="25sp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Step 4:

Open “AndroidManifest.xml” file.

In this file, we will add some user permissions like read and write to external storage.

You are downloading or opening files so permission is required.

Add below permission.

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

The below code shows you the “AndroidManifest.xml” file.

App -> manifests -> AndroidManifest.xml

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pd.downloadpdf" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.DownloadPdf" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 5:

Now, start java code.

Now, create a PDF file on button click.

Below code of button click listener. And pass the object to create a pdf file.

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("size", "" + linear.getWidth() + " " + linear.getWidth());
                bitmap = LoadBitmap(linear, linear.getWidth(), linear.getHeight());
                createPdf();
            }
        });
    }

Then after we need to decode the file using BitmapFactory.

Because PDF file degrade your app’s performance.

Most of BitmapFactory uses in imagefile.

Also Read: Share app links

Bitmaps can very easily exhaust an app’s memory budget.

The bitmap’s code is given below.

private Bitmap LoadBitmap(View v, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

  Let’s understand by full example.

App -> Java -> package name -> MainActivity.xml

MainActivity.java

package com.pd.downloadpdf;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.CalendarView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private ImageButton btn;
    private LinearLayout linear;
    private Bitmap bitmap;
private TextView textView,textView2,textView3;
private ImageView imageView,imageView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //for displaying image in imageview
        imageView=findViewById(R.id.imageView);
        imageView2=findViewById(R.id.imageView2);


        imageView.setImageResource(R.drawable.ic_launcher_background);
        imageView2.setImageResource(R.drawable.ic_launcher_background);



        //for displaying text in textview
        textView2=findViewById(R.id.textView);
        textView3=findViewById(R.id.textView3);
        textView2.setBackgroundColor(Color.BLUE);
        textView2.setTextColor(Color.WHITE);
        textView2.setText("\u2605PDF file\u2605");
        textView=findViewById(R.id.textView2);

        textView3.setText("LinearLayout a PDF download\n\u2192 Click on a button to download");
        textView.setText("Once downloaded file \n\u2192It open automatically");

        //find id
        linear = findViewById(R.id.lineard);
        btn = findViewById(R.id.btnd);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("size", "" + linear.getWidth() + " " + linear.getWidth());
                bitmap = LoadBitmap(linear, linear.getWidth(), linear.getHeight());
                createPdf();
            }
        });
    }

    private Bitmap LoadBitmap(View v, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

    private void createPdf() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        //  Display display = wm.getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels;
        float width = displaymetrics.widthPixels;

        int convertHighet = (int) hight, convertWidth = (int) width;

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        canvas.drawPaint(paint);

        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        document.finishPage(page);

        // write the document content
        String targetPdf = "/sdcard/page.pdf";
        File filePath;
        filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }////////////////////

        // close the document
        document.close();
        Toast.makeText(this, "successfully pdf created", Toast.LENGTH_SHORT).show();

        openPdf();

    }

    private void openPdf() {
        File file = new File("/sdcard/page.pdf");
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "No Application for pdf view", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

We’ll create a PDF document and pass an object.

        PdfDocument document = new PdfDocument();

Add PDF file description

PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();

Start create a PDF page

PdfDocument.Page page = document.startPage(pageInfo);

We’ll use canvas class to draw calls and paint text, color and other components.

Also, use scalable PDF file specified height and width.

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        canvas.drawPaint(paint);

        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        document.finishPage(page);

Now, set file directory

        // write the document content
        String targetPdf = "/sdcard/page.pdf";
        File filePath;
        filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }////////////////////

        // close the document
        document.close();
        Toast.makeText(this, "successfully pdf created", Toast.LENGTH_SHORT).show();

        openPdf();

document.writeTo(new FileOutputStream(filePath));

Creates a file output stream to write to the file represented by the specified File object.

After generating PDF, now we’ll call the openpdf method to open the PDF file when downloading is complete.

    private void openPdf() {
        File file = new File("/sdcard/page.pdf");
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "No Application for pdf view", Toast.LENGTH_SHORT).show();
            }
        }
    }

Now, let’s see the output of the PDF app.

Like below image shows the output of the Leaner layout to the PDF file.

convert LinearLayout to PDF file
convert View

Watch the same video on YouTube

Leave a Reply