Open In App

Convert WebView to PDF in Android with Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes the user has to save some article that is being displayed on the web browser. So for saving that article or a blog users can simply save that specific web page in the form of a PDF on their device. We can implement this feature to save the pdf format of the web page which is being displayed in the WebView. In this article, we will take a look at How we can convert WebView to PDF in Android in Kotlin. 

Note: If you want to Convert Webview to PDF in Android using Java. Check out the following article: How to convert Webview to PDF in Android using JAVA.  

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?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">
 
    <!-- on below line we are creating a
          webview for loading web page  -->
    <WebView
        android:id="@+id/idWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
    <!-- on below line we are creating
         a button for saving a PDF -->
    <Button
        android:id="@+id/idBtnSavePDF"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Convert WebPage To PDF"
        android:textAllCaps="false" />
   
</RelativeLayout>


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintJob
import android.print.PrintManager
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
 
class MainActivity : AppCompatActivity() {
    // on below line we are creating variables for web view,
    // button and print job as well as
    // boolean variable for button pressed.
    lateinit var webView: WebView
    lateinit var savePDFBtn: Button
    lateinit var printJob: PrintJob
 
    // on below line we are initializing
    // button pressed variable as false
    var printBtnPressed = false
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // initializing variables of web view and
        // save button with their ids on below line.
        webView = findViewById(R.id.idWebView)
        savePDFBtn = findViewById(R.id.idBtnSavePDF)
         
        // on below line we are specifying
        // url to load in our web view.
        webView.loadUrl("https://www.google.com")
         
        // on below line we are specifying web view client.
        webView.setWebViewClient(object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                // initializing the webview Object on below line.
                webView = view
            }
        })
        // on below line we are adding click
        // listener for our save pdf button.
        savePDFBtn.setOnClickListener {
            // on below line we are checking
            // if web view is null or not.
            if (webView != null) {
                // if web view is not null we are calling
                // print web page method to generate pdf.
                printWebPage(webView)
            } else {
                // in else condition we are simply displaying a toast message
                Toast.makeText(this, "Webpage not loaded..", Toast.LENGTH_SHORT).show()
            }
        }
    }
 
    // on below line we are creating a print
    // web page method to print the web page.
    fun printWebPage(webview: WebView) {
        // on below line we are initializing
        // print button pressed variable to true.
        printBtnPressed = true
        // on below line we are initializing
        // our print manager variable.
        val printManager =
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                this
                    .getSystemService(Context.PRINT_SERVICE) as PrintManager
            } else {
                TODO("VERSION.SDK_INT < KITKAT")
            }
 
        // on below line we are creating a variable for job name
        val jobName = " webpage" + webView.url
        // on below line we are initializing our print adapter.
        val printAdapter =
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                // on below line we are creating
                // our print document adapter.
                webView.createPrintDocumentAdapter(jobName)
            } else {
                TODO("VERSION.SDK_INT < LOLLIPOP")
            }
        // on below line we are checking id
        // print manager is not null
        assert(printManager != null)
         
        // on below line we are initializing
        // our print job with print manager
        printJob = printManager.print(
            jobName, printAdapter,
            // on below line we are calling
            // build method for print attributes.
            PrintAttributes.Builder().build()
        )
    }
 
 
    @RequiresApi(Build.VERSION_CODES.KITKAT)
    override fun onResume() {
        super.onResume()
         
        // on below line we are checking
        // if print button is pressed.
        if (printBtnPressed) {
            // in this case we are simply checking
            // if the print job is completed.
            if (printJob.isCompleted) {
                // in this case we are simply displaying a completed toast message
                Toast.makeText(this, "Completed..", Toast.LENGTH_SHORT).show()
            }
             
            // below method is called if the print job has started.
            else if (printJob.isStarted) {
                Toast.makeText(this, "Started..", Toast.LENGTH_SHORT).show()
            }
             
            // below method is called if print job has blocked.
            else if (printJob.isBlocked) {
                Toast.makeText(this, "Blocked..", Toast.LENGTH_SHORT).show()
            }
             
            // below method is called if print job has cancelled.
            else if (printJob.isCancelled) {
                Toast.makeText(this, "Cancelled..", Toast.LENGTH_SHORT).show()
            }
             
            // below method is called is print job is failed.
            else if (printJob.isFailed) {
                Toast.makeText(this, "Failed..", Toast.LENGTH_SHORT).show()
            }
             
            // below method is called if print job is queued.
            else if (printJob.isQueued) {
                Toast.makeText(this, "Jon Queued..", Toast.LENGTH_SHORT).show()
            }
             
            // on below line we are simply initializing
            // our print button pressed as false
            printBtnPressed = false
        }
    }
}


Step 4: Adding internet permissions in AndroidManifest.xml

Navigate to app > manifest > AndroidManifest.xml and add the below permissions in it. Comments are added in the code to get to know in detail. 

XML




<!--on below line we are adding internet permissions-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Now run your application to see the output of it. 

Output:



Last Updated : 02 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads