You are currently viewing How to save the content of Webview as PDF file using Xamarin Android C#?
Xamarin

How to save the content of Webview as PDF file using Xamarin Android C#?

4.1
(8)

How to save the content of Webview as PDF file using Xamarin Android C#?

Are you looking for Xamarin C# code to save your HTML content of Webview into a PDF file? Then you are on the right page. Here is the example to save Webview content as a PDF file without using any third-party library.

In Android 4.4 (API level 19), the WebView class has been updated to enable printing HTML content. The class allows you to load a local HTML resource or download a page from the web, create a print job and hand it off to Android’s print services.

Read more at Printing HTML Docs

Follow the below steps to create a sample project to print or save the HTML content as a PDF file.

Step 1: Create a new blank Android app project (From Visual Studio) with MainActivity only.

Step 2: Update your main layout file with the following code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
         android:layout_width="match_parent"
    android:layout_height="match_parent">
        <Button
        android:text="Button 1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="25px"
        android:minHeight="25px"
        android:id="@+id/button1" />

    </LinearLayout>
    
</RelativeLayout>

Step 3: Create a new custom print layout with the name print_view.axml within layout directory and update with the following code (layout/print_view.axml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
     <WebView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/printWebView" />
</LinearLayout>

Step 4: Update your MainActivity.cs file with the following code

[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        Button btn1;
        private WebView myWebView;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            btn1 = FindViewById<Button>(Resource.Id.button1);
            btn1.Click += Button_Clicked;
        }
        private void CreatePrintWebView(View printView)
        {
            WebView webView = printView.FindViewById<WebView>(Resource.Id.printWebView);

            string htmlDocument =
      "<html><body><h1>Xamarin Android Print Test</h1><p>"
        + "This is some sample page content.</p></body></html>";

            webView.LoadDataWithBaseURL(null, htmlDocument,
                    "text/HTML", "UTF-8", null);
        }
        private void LoadPrintWebVIew()
        {
            // PrescriptionView is the design view
            var printView = LayoutInflater.Inflate(Resource.Layout.print_view, null);
            CreatePrintWebView(printView);
            Android.App.AlertDialog dialog = null;
            AlertDialog.Builder alert = new AlertDialog.Builder(this);

            alert.SetView(printView);

            alert.SetPositiveButton("Print", (senderAlert, args) =>
            {
                var webView = printView.FindViewById<WebView>(Resource.Id.printWebView);
                string fileName = "MyPrintFile_" + Guid.NewGuid().ToString() + ".pdf";
                var printMgr = (PrintManager)GetSystemService(MainActivity.PrintService);
                printMgr.Print("MyPrintJob", webView.CreatePrintDocumentAdapter(fileName), new PrintAttributes.Builder().Build());
            });

            alert.SetNegativeButton("Close", (senderAlert, args) =>
            {
                dialog.Dismiss();
            });

            dialog = alert.Create();
            dialog.Show();
         
        }

        /// <summary>
        /// Save or print the PDF file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Clicked(object sender, EventArgs e)
                {
            LoadPrintWebVIew();
        }

    }

Output:

Hope this will helps.

For Complete project refer this GitHub Link: view project

Read more Xamarin related posts: https://jigneshdarji.com/category/xamarin/

How useful was this post?

Click on a star to rate it!

Average rating 4.1 / 5. Vote count: 8

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?