无法从程序集 'itextsharp, Version=5.5.5.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca' 加载类型 'iTextSharp.text.html.HtmlParser'

Could not load type 'iTextSharp.text.html.HtmlParser' from assembly 'itextsharp, Version=5.5.5.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca'

see this link 将 html 转换为 pdf 我在 webconfig 中遇到这个版本错误让一些天才找到并解决问题。

我的模型

 public class Customer
  {
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
  }

我的控制器这是正常代码

 public ActionResult Index()
    {
        List<Customer> customers = new List<Customer>();

        for (int i = 1; i <= 10; i++)
        {
            Customer customer = new Customer
            {
                CustomerID = i,
                FirstName = string.Format("FirstName{0}", i.ToString()),
                LastName = string.Format("LastName{0}", i.ToString())
            };
            customers.Add(customer);
        }
        return View(customers);
    }

这是用于 pdf 转换控制器的

public ActionResult PDF()
    {
        List<Customer> customers = new List<Customer>();

        for (int i = 1; i <= 10; i++)
        {
            Customer customer = new Customer
            {
                CustomerID = i,
                FirstName = string.Format("FirstName{0}", i.ToString()),
                LastName = string.Format("LastName{0}", i.ToString())
            };
            customers.Add(customer);
        }

        return new RazorPDF.PdfResult(customers, "PDF");
    }

我的网络配置

 <dependentAssembly>
    <assemblyIdentity name="itextsharp" publicKeyToken="8354ae6d2174ddca" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.5.5.0" newVersion="5.5.5.0" />
  </dependentAssembly>

你有几个问题。

首先,您有一个版本绑定重定向:

<bindingRedirect oldVersion="0.0.0.0-5.5.5.0" newVersion="5.5.5.0" />

这是一个巨大的笼统声明,假设版本 0.0.0.05.5.5.0 之间没有发生 API 变化。但是,some/many/most/all 库会在发生 API 更改时增加其主要和次要版本号。

其次,但与第一个相关,在 iTextSharp 4.1.6(4.x 系列中最后发布的 iTextSharp,从 Java 2.x 系列移植)和 5 之间实际上是一些 API 的变化。在您的特定情况下,class iTextSharp.text.html.HtmlParser 已被删除,这就是为什么会出现该异常的原因。

有几种方法可以解决这个问题。

选项 #1 - 好方法

  1. 摆脱 RazorPDF。它已经两年半没有更新了,它需要一个过时版本的 iTextSharp 并使用过时的 HTML 解析器。

  2. 切换到使用 iTextSharp 的更新 HTML 解析 XmlWorkerSee this (long winded) answer for how to use it.

选项 #2 - 糟糕的方式

  1. 阅读官方第4箱iText website's sales FAQ page标题"Why shouldn't I use iText 2.x (or iTextSharp 4.x)?"

  2. 下载 iTextSharp 4.1.6 源代码。您需要自己寻找。不要费心询问从哪里获得它,因为这个版本不受社区甚至软件制造商的支持。

  3. 让您的法律顾问逐行检查源代码,以确保它符合您所在辖区的法律以及任何有关版权的国际条约。说真的。

  4. 如果您的法律顾问批准源代码,请编译它,删除绑定重定向并将 DLL 放入您的项目中。

  5. 接受 4.1.6 版的解析器非常非常有限并且有几个已知问题会抛出您认为完全有效的异常的事实 HTML。还要接受,如果您就这些问题寻求任何支持,您将被告知两件事,升级到最新版本并从 HTMLWorker 切换到 XmlWorker.

选项 #3 - 丑陋的方式(布鲁诺)

  1. 下载official iTextSharp source.

  2. Re-implement iTextSharp.text.html.HtmlParser 和所有其他缺失的 class 使用 4.1.6 逻辑或您自己的逻辑的方法和属性。

  3. 编译并link