Related Articles

Related Articles

How to Convert WebView to PDF in Android?
  • Last Updated : 14 Sep, 2020

Sometimes there is a need to save some articles available on the internet in the form of PDF files. And to do so there are many ways, one can use any browser extension or any software or any website to do so. But in order to implement this feature in the android app, one can’t rely on other software or websites to do so. So to implement this amazing feature in the android app follow this tutorial. A sample GIF is given below to get an idea about what we are going to do in this article.

webview to pdf

Steps for Converting WebView to PDF 

Step 1: Creating 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 choose Java as the programming language though we are going to implement this project in Java language.

Step 2: Before going to the coding section first do some pre-task



<uses-permission android:name=”android.permission.INTERNET”/>

Step 3: Designing the UI 

In the activity_main.xml file, there is one WebView that is used to load the websites and one Button which is used to save the loaded webpage to PDF file. Here is the code for the activity_main.xml file.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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">
  
  <!-- WebView to load webPage  -->
  <WebView
      android:id="@+id/webViewMain"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>
  
  <!-- Button To save the Pdf file when clicked -->
  <Button
      android:layout_alignParentBottom="true"
      android:textColor="#ffffff"
      android:background="@color/colorPrimary"
      android:text="Convert WebPage To PDF"
      android:id="@+id/savePdfBtn"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>
  
</RelativeLayout>

chevron_right


Step 4: Working with MainActivity.java file

  • Open the MainActivity.java file there within the class, first create the object of the WebView class.

// creating object of WebView



WebView printWeb;

  • Now inside the onCreate() method, initialize the WebView and Button with their respective IDs that are given in the activity_main.xml file.

  // Initializing the WebView

  final WebView webView=(WebView)findViewById(R.id.webViewMain);

  // Initializing the Button

  Button savePdfBtn=(Button)findViewById(R.id.savePdfBtn);

  • Now setWebViewClient of the WebView and inside the onPageFinished() initializes the printWeb object with the WebView.

 // Setting WebView Client

 webView.setWebViewClient(new WebViewClient()

    {

           @Override

           public void onPageFinished(WebView view, String url) {



               super.onPageFinished(view, url);

               // initializing the printWeb Object

               printWeb=webView;

     }

});

  • Now load the URL

 // loading the URL

 webView.loadUrl(“https://www.google.com”);

  • Next, call the createWebPrintJob() method which is created later, inside the onClick(), and show the respective Toast Message.

 // setting clickListener for Save Pdf Button

 savePdfBtn.setOnClickListener(new View.OnClickListener() {

           @Override

           public void onClick(View view) {

               if(printWeb!=null)

               {

                   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

                       // Calling createWebPrintJob()

                       PrintTheWebPage(printWeb);

                   }else

                   {

                       // Showing Toast message to user

                       Toast.makeText(MainActivity.this, “Not available for device below Android LOLLIPOP”, 

                                                                                                             Toast.LENGTH_SHORT).show();                        

                   }

               }

               else

               {

                   // Showing Toast message to user

                   Toast.makeText(MainActivity.this, “WebPage not fully loaded”, Toast.LENGTH_SHORT).show();

               }

           }

  });

  • Create an object of PrintJob and create a boolean printBtnPressed which is used to check the status of the printing webpage.

 // object of print job

 PrintJob printJob;

 // a boolean to check the status of printing

 boolean printBtnPressed=false;

  • Now create a PrintTheWebPage() method inside MainActivity.java class and Below is the complete code of PrintTheWebPage() method.

   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

   private void PrintTheWebPage(WebView webView) {

       // set printBtnPressed true

       printBtnPressed=true;

       // Creating  PrintManager instance

       PrintManager printManager = (PrintManager) this

               .getSystemService(Context.PRINT_SERVICE);

       // setting the name of job

       String jobName = getString(R.string.app_name) + ” webpage”+webView.getUrl();

       // Creating  PrintDocumentAdapter instance

       PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);

       // Create a print job with name and adapter instance

       assert printManager != null;

        printJob = printManager.print(jobName, printAdapter,

               new PrintAttributes.Builder().build());

   }

  • Next, show the status of the Saving PDF, inside the onResume() method, and check for the status of printing. Below is the complete code of the onResume() method.

   @Override

   protected void onResume() {

       super.onResume();

       if(printJob!=null &&printBtnPressed) {

           if (printJob.isCompleted()) {

               // Showing Toast Message

               Toast.makeText(this, “Completed”, Toast.LENGTH_SHORT).show();

           } else if (printJob.isStarted()) {

               // Showing Toast Message

               Toast.makeText(this, “isStarted”, Toast.LENGTH_SHORT).show();

           } else if (printJob.isBlocked()) {

               // Showing Toast Message

               Toast.makeText(this, “isBlocked”, Toast.LENGTH_SHORT).show();

           } else if (printJob.isCancelled()) {

               // Showing Toast Message

               Toast.makeText(this, “isCancelled”, Toast.LENGTH_SHORT).show();

           } else if (printJob.isFailed()) {

               // Showing Toast Message

               Toast.makeText(this, “isFailed”, Toast.LENGTH_SHORT).show();

           } else if (printJob.isQueued()) {

               // Showing Toast Message

               Toast.makeText(this, “isQueued”, Toast.LENGTH_SHORT).show();

           }

           // set printBtnPressed false

           printBtnPressed=false;

       }

   }

  • Below is the complete code for the MainActivity.java file.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
      
    // creating object of WebView
    WebView printWeb;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initializing the WebView
        final WebView webView = (WebView) findViewById(R.id.webViewMain);
  
        // Initializing the Button
        Button savePdfBtn = (Button) findViewById(R.id.savePdfBtn);
  
        // Setting we View Client
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // initializing the printWeb Object
                printWeb = webView;
            }
        });
  
        // loading the URL
        webView.loadUrl("https://www.google.com");
  
        // setting clickListener for Save Pdf Button
        savePdfBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (printWeb != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        // Calling createWebPrintJob()
                        PrintTheWebPage(printWeb);
                    } else {
                        // Showing Toast message to user
                        Toast.makeText(MainActivity.this, "Not available for device below Android LOLLIPOP", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // Showing Toast message to user
                    Toast.makeText(MainActivity.this, "WebPage not fully loaded", Toast.LENGTH_SHORT).show();
                }
            }
        });
  
    }
  
    // object of print job
    PrintJob printJob;
  
    // a boolean to check the status of printing
    boolean printBtnPressed = false;
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void PrintTheWebPage(WebView webView) {
          
        // set printBtnPressed true
        printBtnPressed = true;
  
        // Creating  PrintManager instance
        PrintManager printManager = (PrintManager) this
                .getSystemService(Context.PRINT_SERVICE);
  
        // setting the name of job
        String jobName = getString(R.string.app_name) + " webpage" + webView.getUrl();
  
        // Creating  PrintDocumentAdapter instance
        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);
  
        // Create a print job with name and adapter instance
        assert printManager != null;
        printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        if (printJob != null && printBtnPressed) {
            if (printJob.isCompleted()) {
                // Showing Toast Message
                Toast.makeText(this, "Completed", Toast.LENGTH_SHORT).show();
            } else if (printJob.isStarted()) {
                // Showing Toast Message
                Toast.makeText(this, "isStarted", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isBlocked()) {
                // Showing Toast Message
                Toast.makeText(this, "isBlocked", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isCancelled()) {
                // Showing Toast Message
                Toast.makeText(this, "isCancelled", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isFailed()) {
                // Showing Toast Message
                Toast.makeText(this, "isFailed", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isQueued()) {
                // Showing Toast Message
                Toast.makeText(this, "isQueued", Toast.LENGTH_SHORT).show();
  
            }
            // set printBtnPressed false
            printBtnPressed = false;
        }
    }
}

chevron_right


Output: Run on Emulator

Resources:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :