Search code examples
c#xamarinxamarin.androiditext

Xamarin Android save webview in pdf


I'm developing an app in xamarin for android.

The objective is for the user to fill a document and save it as a PDF.

I have tried this process:

HTML TO PDF

I have designed a cshtml file, that contains the same structure as the document, with the input that the user inserted. So far so good, it looks good in the webview. I now wish to convert this to PDF but I can't seem to find a way to convert it.

Is there a way to convert CSHTML to PDF, or somehow convert the content of the webview to PDF?

I have tried an extension called "iTextSharp" to create and manipulate PDF's (my attempt to convert html to a PDF file but the styles and images used in html aren't being applied).

The final objective is to create a PDF file that has the same structure as an HTML Page that I own.

Any way I can accomplish this? Ideas are most welcome


Solution

  • I could convert the whole WebView page content to pdf with below code. Hope it may help you. However, I have just tried this in Simulator.

    [Activity(Label = "DroidWebview", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        WebView myWebView;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
    
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
    
            myWebView = FindViewById<WebView>(Resource.Id.webview);
            myWebView.Settings.JavaScriptEnabled = true;
            myWebView.SetWebViewClient(new MyWebViewClient());
    
            myWebView.LoadUrl("https://stackoverflow.com/questions/46978983/xamarin-android-save-webview-in-pdf");
    
            Button myPrintButton = FindViewById<Button>(Resource.Id.myPrintButton);
            myPrintButton.Click += (sender, e) =>
            {
                var printManager = (PrintManager)GetSystemService(PrintService);
                string fileName = "MyPrint_" + Guid.NewGuid().ToString() + ".pdf";
                var printAdapter = myWebView.CreatePrintDocumentAdapter(fileName);
                PrintJob printJob = printManager.Print("MyPrintJob", printAdapter, new PrintAttributes.Builder().Build());
            };
        }
    }
    
    public class MyWebViewClient : WebViewClient
    {
        public override bool ShouldOverrideUrlLoading(WebView view, string url)
        {
            view.LoadUrl(url);
            return false;
        }
    }