【问题标题】:Unable to create PDF from HTML in Xamarin Android无法在 Xamarin Android 中从 HTML 创建 PDF
【发布时间】:2017-03-25 16:17:37
【问题描述】:

我正在 Xamarin for Android 中开发一个应用程序。我已经使用 StringBuilder 生成了 HTML 文件。现在我的外部存储中有一个 HTML 文件,并且 PDF 需要相同的模板。因此,当我尝试使用 iTextSharp using XML WorkerPDFSharp 库将 HTML 转换为 PDF 时,由于缺少 System.Drawing.dll,我遇到了构建错误。然后我从 Xamarin 论坛和 Stackoverflow 链接中发现 Xamarin.Android 不支持它。

谁能告诉我有关如何为 PDF 或任何其他适用于 Xamarin.Android 的可将 html 文件转换为 pdf 的工作 nuget 包的模板的替代方法。

注意:我可以生成 PDF,但不能将 HTML 转换为 PDF。

这会很有帮助!非常感谢!

【问题讨论】:

  • @InitLipton 我检查了但收到以下错误“无法安装包'HtmlRenderer.Core 1.5.0.5'。您正在尝试将此包安装到针对'MonoAndroid,Version = v6的项目中。 0',但包不包含任何与该框架兼容的程序集引用或内容文件。有关详细信息,请联系包作者。"在我的项目属性中,使用 Android 版本编译仅提供“使用最新平台”选项。所以,我也无法更改版本。

标签: c# android xamarin xamarin.android pdf-generation


【解决方案1】:

使用 Nuget 包 Xam.iTextSharpLGPL

下面是示例代码

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using Android.Graphics;


  string path = Android.OS.Environment.ExternalStorageDirectory.Path;
  string pdfPath = System.IO.Path.Combine(path, "samplee.pdf");
  System.IO.FileStream fs = new FileStream(pdfPath, FileMode.Create);    
  Document document = new Document(PageSize.A4);
  PdfWriter writer = PdfWriter.GetInstance(document, fs);
  HTMLWorker worker = new HTMLWorker(document);
  document.Open();
  StringBuilder html = new StringBuilder();
  html.Append("<? xml version='1.0' encoding='utf-8' ?><html><head><title></title></head>");
  html.Append("<CENTER>Simple Sample html</H1>");
  html.Append("<H4>By User1</H4>");
  html.Append("<H2>Demonstrating a few HTML features</H2>");
  html.Append("</CENTER>");
  html.Append("<p>HTML doesn't normally use line breaks for ordinary text. A white space of any size is treated as a single space. This is because the author of the page has no way of knowing the size of the reader's screen, or what size type they will have their browser set for.");
  html.Append("</p></body</html>");
  TextReader reader = new StringReader(html.ToString());
  worker.StartDocument();
  worker.Parse(reader);
  worker.EndDocument();
  worker.Close();
  document.Close();
  writer.Close();
  fs.Close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 2015-05-07
    • 2017-12-25
    • 2021-05-21
    • 2013-02-02
    • 2015-01-29
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多