Open In App

How to Convert WebView to PDF in Android?

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.



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

Step 4: Working with MainActivity.java file

// creating object of WebView

WebView printWeb;

  // Initializing the WebView

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

  // Initializing the Button

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

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

     }

});

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

       }

   }




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

Output: Run on Emulator

Resources:


Article Tags :