【问题标题】:How to get html content and convert it to PDF with itextsharp?如何获取 html 内容并使用 itextsharp 将其转换为 PDF?
【发布时间】:2010-10-22 02:13:09
【问题描述】:

有谁知道如何获取 html 内容,将其转换为 pdf 并将其保存到数据库?

我尝试了很多方法,但似乎没有任何效果。在某些文章中,它是使用 HTMLParse 编写的,在其他文章中是 HTMLWorker……有时会抛出错误“文档没有页面”……有时,它只是抛出一个异常,但它没有指定错误……

有谁知道这样做的好方法吗?

我正在使用 C# 3.0、ASP.NET MVC 和 LinQToSQL。

提前感谢,非常感谢!

【问题讨论】:

    标签: c# asp.net-mvc pdf linq-to-sql itextsharp


    【解决方案1】:

    对于 HTML 到 PDF,我倾向于查看 HTMLDoc。它是一个 exe 而不是一个库,所以它可能不是您正在寻找的东西,但它可能会让您克服困难。

    看着 iText 的书,Lowagie 说:

    “iText 邮件列表中的一个常见问题是,'iText 是否提供 HTML2PDF 功能?'官方回答是否定的;建议您使用 HtmlDoc 或 ICEBrowser。”第 456 页。

    他接着展示了一个 HTMLParser 的例子,但强调它不是解析和呈现 HTML 的巨大工作。

    【讨论】:

      【解决方案2】:
       public class Pdf : IPdf
          {
              public FileStreamResult Make(string s)
              {
                  using (var ms = new MemoryStream())
                  {
                      using (var document = new Document())
                      {
                          PdfWriter.GetInstance(document, ms);
                          document.Open();
                          using (var str = new StringReader(s))
                          {
      
                              var htmlWorker = new HTMLWorker(document);
      
                              htmlWorker.Parse(str);
                          }
                          document.Close();
                      }
      
                      HttpContext.Current.Response.ContentType = "application/pdf";
                      HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
                      HttpContext.Current.Response.Buffer = true;
                      HttpContext.Current.Response.Clear();
                      HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                      HttpContext.Current.Response.OutputStream.Flush();
                      HttpContext.Current.Response.End();
      
                      return new FileStreamResult(HttpContext.Current.Response.OutputStream, "application/pdf");
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2014-09-29
        • 2022-03-07
        • 1970-01-01
        • 2012-08-19
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多