How to generate pdf file from xml linear layout with scroll view

How to generate pdf file from xml linear layout with scroll view.

how it works
when the user clicks on the download button, XML file convert in pdf with scroll file and after download, it open automatically.

Bitmap

Everything that is drawn in android that is a Bitmap.

We can create a Bitmap from an image or a file or a resource by using the BitmapFactory class.

Why used

For handle images. Found under android.graphics.bitmap

 

log.d

The log.d() method is used to log debug messages.

 

ARGB_8888

(ARGB)Alpha,Red,Green and Blue to convert Bitmap object into a drawable.

You can create pixel with four channels.

Each pixel is stored on 4 bytes.

Each channel is stored with 8 bits of precision

 

Draw()

Store various shapes like color and style.

 

WindowManager

Managing the window for a different particular display

 

getSystemService(Context.WINDOW_SERVICE)

access device services

 

DisplayMettrics

Display different information about the screen such as its size, density and font scaling

 

PdfDocument()

Generating pdf document

 

PdfDocument.PageInfo.Builder();

Page info like height, width, size etc.

 

Canvas

Draw graphics on to the screen

 

Paint

This class  used to canvas to draw objects and display color and style with 2d display graphics.

 

FileOutputStream()

File create or save individual bytes

 

openGeneratePDF()

view generated pdf file

 

Uri

Identify a resource

 

setDataAndType

Download Layout PDF


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

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="250sp"
                android:layout_height="250sp"
                android:layout_gravity="center"
                app:srcCompat="@drawable/ic_launcher_background" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="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"
                app:srcCompat="@drawable/ic_launcher_background" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="view Download"
                android:textSize="25sp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>


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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

//        Resources mResources = getResources();
//        Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot);

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

watch video
https://youtu.be/4ZMAK6mUI8Q
SUBSCRIBE to download

Download Source code
Post a Comment (0)
Previous Post Next Post