0

With the reference of following StackOverflow suggestion,

Convert HTML to PDF in .NET

I tried to convert the HTML file to PDF using HtmlRenderer.PdfSharp but unfortunately it shows compatible error like below,

HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)

 HtmlRenderer.Core 1.5.0.5 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRenderer.Core 1.5.0.5 supports:
  - net20 (.NETFramework,Version=v2.0)
  - net30 (.NETFramework,Version=v3.0)
  - net35-client (.NETFramework,Version=v3.5,Profile=Client)
  - net40-client (.NETFramework,Version=v4.0,Profile=Client)
  - net45 (.NETFramework,Version=v4.5)      

HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)     

And I tried with wkhtmltopdf too but it throws similar error in android and other platform projects.

My requirement is to convert the HTML file to PDF file only (no need to view the PDF file, just to save it in local path).

Can anyone please provide suggestions?

Note : Need open source suggestion :)

Awaiting for your suggestions !!!

Support to convert the HTML to PDF in Xamarin Forms

Dinesh B
  • 33
  • 1
  • 2
  • Quoting Dinesh B: *" Finally, Thanks for your suggestions. After one month of effort now, I am able to render the HTML file to PDF as required without using any third party library. I am sharing my Git repo for future reference. https://github.com/dinesh4official/XFPDF"* – M-- Jan 20 '20 at 15:54
  • @M--, I suggested a solution with example. not a theoretical one. – Dinesh B Jan 21 '20 at 05:59
  • That qualifies for a comment not an answer. That's why the answer got deleted by a moderator. Cheers. – M-- Jan 21 '20 at 06:00

2 Answers2

0

you can use the HtmlToPdfConverter

private void ConvertUrlToPdf()
{
    try {
        String serverIPAddress = serverIP.Text;
        uint serverPortNumber = uint.Parse (serverPort.Text);

        // create the HTML to PDF converter object
        HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter (serverIPAddress, serverPortNumber);

        // set service password if necessary
        if (serverPassword.Text.Length > 0)
            htmlToPdfConverter.ServicePassword = serverPassword.Text;

        // set PDF page size
        htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;

        // set PDF page orientation
        htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;

        // convert the HTML page from given URL to PDF in a buffer
        byte[] pdfBytes = htmlToPdfConverter.ConvertUrl (urlToConvert.Text);

        string documentsFolder = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); 
        string outPdfFile = System.IO.Path.Combine (documentsFolder, "EvoHtmlToPdf.pdf");

        // write the PDF buffer in output file
        System.IO.File.WriteAllBytes (outPdfFile, pdfBytes);

        // open the PDF document in the default PDF viewer
        UIDocumentInteractionController pdfViewer = UIDocumentInteractionController.FromUrl (Foundation.NSUrl.FromFilename (outPdfFile));
        pdfViewer.PresentOpenInMenu (this.View.Frame, this.View, true);

    } catch (Exception ex) {
        UIAlertView alert = new UIAlertView ();
        alert.Title = "Error";
        alert.AddButton ("OK");
        alert.Message = ex.Message;
        alert.Show ();
    }
}

another

you can see thisurl

Angella Yu
  • 52
  • 8
  • I can't see HtmlToPdfConverter under Android or iOS project. Can you please let me know is this 3rd party library. I am looking for open source. – Dinesh B Dec 10 '19 at 15:30
0

You can read the HTML as a stream and store it into local like below,

public static class FileManager
{
    public static async Task<MemoryStream> DownloadFileAsStreamAsync(string url)
    {
        try
        {
            var stream = new MemoryStream();
            using (var httpClient = new HttpClient())
            {
                var downloadStream = await httpClient.GetStreamAsync(new Uri(url));
                if (downloadStream != null)
                {
                    await downloadStream.CopyToAsync(stream);
                }
            }

            return stream;
        }
        catch (Exception exception)
        {
            return null;
        }
    }

    public static async Task<bool> DownloadAndWriteIntoNewFile(string url, string fileName)
    {
        var stream = await DownloadFileAsStreamAsync(url);
        if (stream == null || stream.Length == 0)
            return false;

        var filePath = GetFilePath(fileName);

        if (!File.Exists(filePath))
            return false;

        File.Delete(filePath);

        // Create file.
        using (var createdFile = File.Create(filePath))
        {
        }

        // Open and write into file.
        using (var openFile = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite))
        {
            stream.WriteTo(openFile);
        }

        return true;
    }

    public static string GetFilePath(string fileName)
    {
        var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), fileName);
        return filePath;
    }

    public static void WriteAsText(string filePath, string contents)
    {
        File.WriteAllText(filePath, contents);
    }

    public static string ReadAsText(string filePath)
    {
        return File.ReadAllText(filePath);
    }
}

You can read a stored pdf file and displayed using webview like below,

private async void HtmlToPDF()
{
    await FileManager.DownloadAndWriteIntoNewFile("https://www.google.co.in/?gws_rd=ssl", "SavePDF.pdf");
    var filePath = FileManager.GetFilePath("SavePDF.pdf");
    var pdfString = FileManager.ReadAsText(filePath);

    var webView = new WebView
    {
        Source = new HtmlWebViewSource
        {
            Html = pdfString
        }
    };

    this.Content = webView;
}

And the output below,

enter image description here

Likewise, you can save HTML as PDF and do what you want..

Ganesan VG
  • 176
  • 9