How To Convert Web Link To PDF Without Using iText Library In Android

In this article, we will learn how to convert a Website url to a pdf file in Android.

How To Convert Web Link To PDF Without Using iText Library In Android

Introduction

In this article, we will learn how to convert a Web url to a pdf file in Android. To create a PDF in Android, we ususally use a third party library but here we will not use any third party libraries.

iText Library

This library is awesome and very useful. But the iText Community licensed this library with the AGPL license. So, we need to license our own application under the AGPL license.

Reference Link - http://developers.itextpdf.com/

But Google provides a print API for Android to print any content directly from a mobile app. We can use the same Print API for generating and saving a web page content to a pdf file.

Reference Link - https://developer.android.com/training/printing/

Coding Part

I have detailed this article into the following 3 steps.

  • Step 1: Creating a New Project with Empty Activity.
  • Step 2: Setting up the project with Print Adapter Extension.
  • Step 3: Implementation of URL to PDF file generation.

 

Creating a New Project with Android Studio

  1. Open Android Studio and Select Create new project.
  2. Name the project as per your wish and select your activity template.

    How To Convert Web Link To PDF Without Using iText Library In Android

  3. Click finish button to create a new project in Android Studio.

Setting up the project with Print Adapter Extension

To create a pdf file, we need to use “PrintDocumentAdapter.LayoutResultCallback” and it cannot be used by any class. 
 
Create a class with package name “android.print” and class name “PdfPrint.java”.
 
Paste the following code with a callback interface.
 
  1. package android.print;  
  2.   
  3. import android.os.Build;  
  4. import android.os.CancellationSignal;  
  5. import android.os.ParcelFileDescriptor;  
  6. import android.support.annotation.RequiresApi;  
  7. import android.util.Log;  
  8.   
  9. import java.io.File;  
  10.   
  11. @SuppressWarnings("ALL")  
  12. public class PdfPrint {  
  13.     private static final String TAG = PdfPrint.class.getSimpleName();  
  14.     private final PrintAttributes printAttributes;  
  15.   
  16.     public PdfPrint(PrintAttributes printAttributes) {  
  17.         this.printAttributes = printAttributes;  
  18.     }  
  19.   
  20.     @RequiresApi(api = Build.VERSION_CODES.KITKAT)  
  21.     public void print(final PrintDocumentAdapter printAdapter, final File path, final String fileName,  
  22.                       final CallbackPrint callback) {  
  23.         printAdapter.onLayout(null, printAttributes, null,  
  24.                 new PrintDocumentAdapter.LayoutResultCallback() {  
  25.                     @Override  
  26.                     public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {  
  27.                         printAdapter.onWrite(new PageRange[]{PageRange.ALL_PAGES}, getOutputFile(path, fileName),  
  28.                                 new CancellationSignal(), new PrintDocumentAdapter.WriteResultCallback() {  
  29.                                     @Override  
  30.                                     public void onWriteFinished(PageRange[] pages) {  
  31.                                         super.onWriteFinished(pages);  
  32.                                         if (pages.length > 0) {  
  33.                                             File file = new File(path, fileName);  
  34.                                             String path = file.getAbsolutePath();  
  35.                                             callback.onSuccess(path);  
  36.                                         } else {  
  37.                                             callback.onFailure(new Exception("Pages length not found"));  
  38.                                         }  
  39.   
  40.                                     }  
  41.                                 });  
  42.                     }  
  43.                 }, null);  
  44.     }  
  45.   
  46.     private ParcelFileDescriptor getOutputFile(File path, String fileName) {  
  47.         if (!path.exists()) {  
  48.             path.mkdirs();  
  49.         }  
  50.         File file = new File(path, fileName);  
  51.         try {  
  52.             file.createNewFile();  
  53.             return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);  
  54.         } catch (Exception e) {  
  55.             Log.e(TAG, "Failed to open ParcelFileDescriptor", e);  
  56.         }  
  57.         return null;  
  58.     }  
  59.     public interface CallbackPrint {  
  60.         void onSuccess(String path);  
  61.         void onFailure(Exception ex);  
  62.     }  
  63. }  

Implementation of URL to PDF file generation

In this part, we will learn how to use the Printer Extension created in the last step to create a PDF file.

  1. Open your xml file and paste the following code.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     xmlns:tools="http://schemas.android.com/tools"  
    4.     android:layout_width="match_parent"  
    5.     android:layout_height="match_parent"  
    6.     tools:context="com.androimads.androidpdfmaker.MainActivity">  
    7.   
    8.     <WebView  
    9.         android:layout_width="match_parent"  
    10.         android:layout_height="match_parent"  
    11.         android:id="@+id/webView"  
    12.         android:layout_above="@id/textView"/>  
    13.   
    14.     <TextView  
    15.         android:visibility="gone"  
    16.         android:background="@color/colorBackground"  
    17.         android:padding="2dp"  
    18.         android:text="Saving..."  
    19.         android:gravity="center"  
    20.         android:textColor="#FFFFFF"  
    21.         android:layout_alignParentBottom="true"  
    22.         android:layout_width="match_parent"  
    23.         android:layout_height="wrap_content"  
    24.         android:id="@+id/textView"/>  
    25.   
    26. </RelativeLayout>  
  1. Open your Activity file, in my case “MainActivity.java” and initialize “WebView” as shown below.
    1. webView = findViewById(R.id.webView);  
    2. webView.loadUrl("https://www.androidmads.info/");  
    3. webView.setWebViewClient(new WebViewClient());  
  1. Create a pdf print adapter with print attributes what we need.
    1. String fileName = String.format("%s.pdf"new SimpleDateFormat("dd_MM_yyyyHH_mm_ss", Locale.US).format(new Date()));  
    2.             final PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(fileName);  
    3.             PrintAttributes printAttributes = new PrintAttributes.Builder()  
    4.                     .setMediaSize(PrintAttributes.MediaSize.ISO_A4)  
    5.                     .setResolution(new PrintAttributes.Resolution("pdf""pdf", 600, 600))  
    6.                     .setMinMargins(PrintAttributes.Margins.NO_MARGINS)  
    7.                     .build();  
    Here, I have used a default page size as “A4”.
  1. Call your extension method with the callback as shown below.
    1. new PdfPrint(printAttributes).print(  
    2.                     printAdapter,  
    3.                     file,  
    4.                     fileName,  
    5.                     new PdfPrint.CallbackPrint() {  
    6.                         @Override  
    7.                         public void onSuccess(String path) {  
    8.                         }  
    9.                         @Override  
    10.                         public void onFailure(Exception ex) {  
    11.                         }  
    12.                     });  
    The PdfPrint.Callback will return success or failure based on the extension method we created.

Full code of MainActivity 

The following listing is the full code of the MainActivity.java for generating a pdf file.

  1. @TargetApi(Build.VERSION_CODES.LOLLIPOP)  
  2. public class MainActivity extends AppCompatActivity {  
  3.   
  4.     private WebView webView;  
  5.     private TextView textView;  
  6.     private int PERMISSION_REQUEST = 0;  
  7.     private boolean allowSave = true;  
  8.   
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.activity_main);  
  13.   
  14.         textView = findViewById(R.id.textView);  
  15.         webView = findViewById(R.id.webView);  
  16.         webView.loadUrl("https://www.androidmads.info/");  
  17.         webView.setWebViewClient(new WebViewClient());  
  18.     }  
  19.   
  20.     @Override  
  21.     public boolean onCreateOptionsMenu(Menu menu) {  
  22.         getMenuInflater().inflate(R.menu.main, menu);  
  23.         return true;  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean onOptionsItemSelected(MenuItem item) {  
  28.         if (item.getItemId() == R.id.save) {  
  29.             savePdf();  
  30.             return true;  
  31.         }  
  32.         return super.onOptionsItemSelected(item);  
  33.     }  
  34.   
  35.     private void savePdf() {  
  36.         if(!allowSave)  
  37.             return;  
  38.         allowSave = false;  
  39.         textView.setVisibility(View.VISIBLE);  
  40.         if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)  
  41.                 == PERMISSION_GRANTED) {  
  42.             String fileName = String.format("%s.pdf"new SimpleDateFormat("dd_MM_yyyyHH_mm_ss", Locale.US).format(new Date()));  
  43.             final PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(fileName);  
  44.             PrintAttributes printAttributes = new PrintAttributes.Builder()  
  45.                     .setMediaSize(PrintAttributes.MediaSize.ISO_A4)  
  46.                     .setResolution(new PrintAttributes.Resolution("pdf""pdf"600600))  
  47.                     .setMinMargins(PrintAttributes.Margins.NO_MARGINS)  
  48.                     .build();  
  49.             final File file = Environment.getExternalStorageDirectory();  
  50.             new PdfPrint(printAttributes).print(  
  51.                     printAdapter,  
  52.                     file,  
  53.                     fileName,  
  54.                     new PdfPrint.CallbackPrint() {  
  55.                         @Override  
  56.                         public void onSuccess(String path) {  
  57.                             textView.setVisibility(View.GONE);  
  58.                             allowSave = true;  
  59.                             Toast.makeText(getApplicationContext(),  
  60.                                     String.format("Your file is saved in %s", path),  
  61.                                     Toast.LENGTH_LONG).show();  
  62.                         }  
  63.   
  64.                         @Override  
  65.                         public void onFailure(Exception ex) {  
  66.                             textView.setVisibility(View.GONE);  
  67.                             allowSave = true;  
  68.                             Toast.makeText(getApplicationContext(),  
  69.                                     String.format("Exception while saving the file and the exception is %s", ex.getMessage()),  
  70.                                     Toast.LENGTH_LONG).show();  
  71.                         }  
  72.                     });  
  73.         } else {  
  74.             ActivityCompat.requestPermissions(thisnew String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST);  
  75.         }  
  76.     }  
  77.   
  78.     @Override  
  79.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {  
  80.         if (requestCode == PERMISSION_REQUEST) {  
  81.             if (grantResults[Arrays.asList(permissions).indexOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)] == PERMISSION_GRANTED) {  
  82.                 savePdf();  
  83.             }  
  84.         }  
  85.         super.onRequestPermissionsResult(requestCode, permissions, grantResults);  
  86.     }  
  87. }  
Reference
  • https://developer.android.com/training/printing/.

Download

You can download the same code from GitHub. If you like this article, please like and share the article and star the repo in GitHub.