Convert WebView to PDF in Android with Kotlin
Last Updated :
02 Jun, 2022
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:android="http://schemas.android.com/apk/res/android"
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
6 min read
Calendar View App in Android with Kotlin
Calendar View is seen in most travel booking applications in which the user has to select the date of the journey. For the selection of the date, this view is used. In this article, we will take a look at How to implement Calendar View within our Android application using Kotlin. A sample video is g
3 min read
SearchView in Android with Kotlin
SearchView is a widget in android which provides a search interface with the help of which users can be able to make searches within the given list of data. In this search view, the user has to specify the search query. According to the search, query results will be populated within the listview. In
4 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 WebV
2 min read
Chrome Custom Tabs in Android with Kotlin
As developers, we have the option of displaying web content to a user in their browser or via WebViews, but both have their own limitations: starting the browser is a large, non-customizable context transition for users, whereas WebViews don't support all aspects of the web platform. To address this
3 min read
How to Build PDF Downloader App in Android with Kotlin?
If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. A sample video is given below to get an idea about what we are going to do in this article. In this article, we
3 min read
Load PDF From URL in Android with Kotlin
PDF View is most of the applications to display the PDF files within the application to display the pdf within our own application rather than redirecting to another application. If we want to display multiple pdf files within our application we have to host these files and then access these files w
4 min read
ViewFlipper in Android with Kotlin
View Flipper is a UI component in Android which is used to flip the view within the screen in the android application. The View Flipper class is an extension of ViewAnimator class. With the help of this, we can simply flip the views. In this article, we will take a look at How we can use ViewFlipper
4 min read
How to Create Dynamic PDF Viewer in Android with Firebase?
If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Androi
7 min read
How to Convert Text to Speech in Android using Kotlin?
Text to Speech App converts the text written on the screen to speech like you have written âHello Worldâ on the screen and when you press the button it will speak âHello Worldâ. Text-to-speech is commonly used as an accessibility feature to help people who have trouble reading on-screen text, but it
3 min read