支持在 Xamarin Forms 中将 HTML 转换为 PDF

Support to convert the HTML to PDF in Xamarin Forms

参考以下Whosebug建议,

Convert HTML to PDF in .NET

我尝试使用 HtmlRenderer.PdfSharpHTML 文件转换为 PDF,但不幸的是它显示如下兼容错误,

HtmlRendererCore.PdfSharpCore 1.0.1 与 netstandard2.0 (.NETStandard,Version=v2.0) 不兼容。包 HtmlRendererCore.PdfSharpCore 1.0.1 支持: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)     

我也尝试过 wkhtmltopdf,但它在 android 和其他平台项目中引发了类似的错误。

我的要求是只把HTML文件转成PDF文件(不需要查看PDF文件,只需要保存在本地路径)。

谁能给点建议吗?

注:需要开源建议:)

等待您的建议!!!

支持在 Xamarin Forms 中将 HTML 转换为 PDF

您可以使用 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 ();
    }
}

另一个

你可以看到这个

您可以将 HTML 作为流读取并将其存储到本地,如下所示,

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);
    }
}

您可以读取存储的 pdf 文件并使用如下所示的 webview 显示,

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;
}

下面的输出,

同样,您可以将 HTML 另存为 PDF 并按照您的意愿进行操作..