Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin free HTML or DOC to PDF Conversion

I'm currently searching for a library or a way to convert HTML OR DOCX files into PDF on the phone/tab, primarily I'am searching for a way on Android or iOS idk if its a PCL or platform specific approach. I could do this for every Platform independently, because our app requires iOS 8 or android kitkat, both supporting native PDF conversion but i want to do it seamless for the user, so the question is, if anyone has done this before, without loading it into a visible Webview at first or has knowledge of an open not GPL licensed API(can't publish the code), to do this with Xamarin.

I am aware of the possibility to do this online, but I don't want to to be dependent to a online service for this.

Help and ideas are appreciated.

like image 266
Qui-Gon Jinn Avatar asked Dec 18 '22 16:12

Qui-Gon Jinn


2 Answers

Android Solution:

Call the SafeHTMLToPDF(string html, string filename) via a dependency service like

DependencyService.Get<YOURINTERFACE>().SafeHTMLToPDF(htmlString, "Invoice");


   public string SafeHTMLToPDF(string html, string filename)
    {

        var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/pay&go/");
        var file = new Java.IO.File(dir + "/" + filename + ".pdf");

        if (!dir.Exists())
            dir.Mkdirs();


        int x = 0;
        while (file.Exists())
        {
            x++;
            file= new Java.IO.File(dir + "/" + filename + "( " + x + " )" + ".pdf");
        }

        if (webpage == null)
            webpage = new Android.Webkit.WebView(GetApplicationContext());

        int width = 2102;
        int height = 2973;

        webpage.Layout(0, 0, width, height);
        webpage.LoadDataWithBaseURL("",html, "text/html", "UTF-8" , null);
        webpage.SetWebViewClient(new WebViewCallBack(file.ToString()));

        return file.ToString();
    }


    class WebViewCallBack : WebViewClient
    {

        string fileNameWithPath = null;

        public WebViewCallBack(string path)
        {
            this.fileNameWithPath = path;
        }


        public override void OnPageFinished(Android.Webkit.WebView myWebview, string url)
        {
            PdfDocument document = new PdfDocument();
            PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(2120 ,3000, 1).Create());

            myWebview.Draw(page.Canvas);
            document.FinishPage(page);
            Stream filestream = new MemoryStream();
            FileOutputStream fos = new Java.IO.FileOutputStream(fileNameWithPath, false); ;
            try
            {
                document.WriteTo(filestream);
                fos.Write(((MemoryStream)filestream).ToArray(), 0, (int)filestream.Length);
                fos.Close();
            }
            catch
            {
            }
        }
    }

And the Way to do it under iOS

public string SafeHTMLToPDF(string html, string filename)
    {
        UIWebView webView = new UIWebView(new CGRect(0, 0, 6.5 * 72, 9 * 72));


        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var file = Path.Combine(documents, "Invoice" + "_" + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToShortTimeString() + ".pdf");

        webView.Delegate = new WebViewCallBack(file);
        webView.ScalesPageToFit = true;
        webView.UserInteractionEnabled = false;
        webView.BackgroundColor = UIColor.White;
        webView.LoadHtmlString(html, null);



        return file;
    }

    class WebViewCallBack : UIWebViewDelegate
    {

        string filename = null;
        public WebViewCallBack(string path)
        {
            this.filename = path;

        }
        public override void LoadingFinished(UIWebView webView)
        {
            double height, width;
            int header, sidespace;

            width = 595.2;
            height = 841.8;
            header = 10;
            sidespace = 10;


            UIEdgeInsets pageMargins = new UIEdgeInsets(header, sidespace, header, sidespace);
            webView.ViewPrintFormatter.ContentInsets = pageMargins;

            UIPrintPageRenderer renderer = new UIPrintPageRenderer();
            renderer.AddPrintFormatter(webView.ViewPrintFormatter, 0);

            CGSize pageSize = new CGSize(width, height);
            CGRect printableRect = new CGRect(sidespace,
                              header,
                              pageSize.Width - (sidespace * 2),
                              pageSize.Height - (header * 2));
            CGRect paperRect = new CGRect(0, 0, width, height);
            renderer.SetValueForKey(NSValue.FromObject(paperRect), (NSString)"paperRect");
            renderer.SetValueForKey(NSValue.FromObject(printableRect), (NSString)"printableRect");
            NSData file = PrintToPDFWithRenderer(renderer, paperRect);
            File.WriteAllBytes(filename, file.ToArray());
        }

        private NSData PrintToPDFWithRenderer(UIPrintPageRenderer renderer, CGRect paperRect)
        {
            NSMutableData pdfData = new NSMutableData();
            UIGraphics.BeginPDFContext(pdfData, paperRect, null);

            renderer.PrepareForDrawingPages(new NSRange(0, renderer.NumberOfPages));

            CGRect bounds = UIGraphics.PDFContextBounds;

            for (int i = 0; i < renderer.NumberOfPages; i++)
            {
                UIGraphics.BeginPDFPage();
                renderer.DrawPage(i, paperRect);
            }
            UIGraphics.EndPDFContent();

            return pdfData;
        }

    }
like image 74
Qui-Gon Jinn Avatar answered Dec 28 '22 08:12

Qui-Gon Jinn


Frustrated with the existing solutions, I've built some extension methods (OpenSource, MIT Licensed) that convert HTML or the content of a Xamarin.Forms.WebView to a PDF file. Sample usage for WebView to PDF:

        async void ShareButton_Clicked(object sender, EventArgs e)
        {
            if (Forms9Patch.ToPdfService.IsAvailable)
            {
                if (await webView.ToPdfAsync("output.pdf") is ToFileResult pdfResult)
                {
                    if (pdfResult.IsError)
                        using (Toast.Create("PDF Failure", pdfResult.Result)) { }
                    else
                    {
                        var collection = new Forms9Patch.MimeItemCollection();
                        collection.AddBytesFromFile("application/pdf", pdfResult.Result);
                        Forms9Patch.Sharing.Share(collection, shareButton);
                    }
                }
            }
            else
                using (Toast.Create(null, "PDF Export is not available on this device")) { }
        }
    }

For a more complete explanation of how to use it, here's a short article: https://medium.com/@ben_12456/share-xamarin-forms-webview-as-a-pdf-a877542e824a?

like image 35
baskren Avatar answered Dec 28 '22 07:12

baskren