How to Convert WebView to PDF in Android?
Last Updated :
08 Aug, 2024
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
<?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">
<!-- 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
- 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;
}
});
// 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
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:
Similar Reads
Convert WebView to PDF in Android with Kotlin
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 displaye
5 min read
How to Convert Pixels to DP in Android?
Pixels are the building blocks of any modern display. They are tiny light sources that illuminate in conjunction to form the images visible on the screen. The quality of the image displayed on the screen depends on the number of pixels the display contains. A display with a higher number of pixels w
4 min read
How to Use WebView in Android?
WebView is a view that displays web pages as a part of the application layout. It is used to embed a complete website into an app. public class WebView extends AbsoluteLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListenerClass Hierarchy: java.lang.Object
2 min read
How to Convert Any Website to Android App in Android Studio?
Here, we are going to make an application for the "Wikipedia" website. By making this application we will be able to learn how we can convert a website to an Android Application just by following simple steps. You can use this concept for your personal website too and learn something new. Step by St
2 min read
How to Play Video from URL in Android?
In this article, you will see how to play a video from a URL on Android. For showing the video in our Android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can p
3 min read
How to Generate QR Code in Android?
QR codes are used in many apps to display data in machine-readable form. These codes are used to represent data in a secure manner that is readable only by machines and not by humans. We have seen many apps that provide QR codes and we can scan those QR codes with our mobile device. In this article,
4 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 yo
7 min read
How to Convert a Document to PDF in Java?
In software projects, there is quite often a requirement for conversion of a given file (HTML/TXT/etc.,) to a PDF file and similarly, any PDF file needs to get converted to HTML/TXT/etc., files. Even PDFs need to be stored as images of type PNG or GIF etc., Via a sample maven project, let us see the
6 min read
How to Use Custom Chrome Tabs in Android?
Many apps have to display different types of web pages inside their application. For displaying webpages in Android there are so many features with which we can display webpages in our Android app. Developers generally prefer to use WebView or redirect users to any browser inside their application.
3 min read
How to Load PDF from URL in Android?
Most of the apps require to include support to display PDF files in their app. So if we have to use multiple PDF files in our app it is practically not possible to add each PDF file inside our app because this approach may lead to an increase in the size of the app and no user would like to download
5 min read