The Wayback Machine - https://web.archive.org/web/20240613170613/https://www.geeksforgeeks.org/convert-webview-to-pdf-in-android-with-kotlin/
Open In App

Convert WebView to PDF in Android with Kotlin

Last Updated : 02 Jun, 2022
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:



Similar Reads

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 amazin
6 min read
Android WebView in Kotlin
WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let's display the https://www.geeksforgeeks.org/ inside the Android Application using Kotlin. Note: To implement Android WebView in Java please refer How to use WebView in Android using Java. Class Hierarchy kotlin.
2 min read
WebView in Android using Jetpack Compose
In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show or a preview of a browser as it lacks most functio
3 min read
How to Use WebView in Android?
WebView is a view that displays web pages inside the application. It is used to turn the application into a web application. public class WebView extends AbsoluteLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener Class Hierarchy: java.lang.Object â†ģ android.view.View â†ģ android.view.ViewGroup â†ģ android
2 min read
How to Create Dynamic WebView in Android with Firebase?
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView which we have to load. So if you are looking for loading a website into your app which can be changed dyna
6 min read
How to Display Progress in ProgressBar While Loading URL in WebView in Android?
ProgressBar in Android is a UI element that displays the status of some work being done in the background in the form of some animation. It can be anything, like computing, loading, searching, fetching, downloading, etc. ProgressBar broadly has two types namely spinning wheel and horizontal bar. In this article, we want to show you how you could im
2 min read
How to Build a News App Using WebView Controller in Android Studio?
In this article, we are going to make a News App with help of a WebView Controller in Android Studio. By making this application we will learn how to access Internet Permission in our android application and how to use WebView with its class named WebView Controller. After making this application you will also be aware of Navigation Drawer activity
7 min read
Android WebView with JavaScript Interface
JavascriptInterface Annotation provides the facility to create any method as the javascript Interface which means that method can be used by web components to communicate with Android. For example: To store the web-based data in Android Shared Preference, or in a local Database.To show a customized dialog box. Storing the web content in Android Cli
3 min read
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading a website into your app which can be changed dynam
8 min read
Android - Search a Text in WebView
WebView allows you to display web content in your activity layout or Fragment but lacks some of the features of fully-developed browsers. A WebView is useful when you need to increase control over the UI and advanced configuration options that will allow you to embed web pages in a specially-designed environment for your app. Note: To know more abo
7 min read
Article Tags :