【问题标题】:HTML to PDF conversion - Almost works, butHTML 到 PDF 的转换 - 几乎可以工作,但是
【发布时间】:2015-02-11 11:05:52
【问题描述】:

过去几天我花了很大一部分时间寻找易于使用的库,该库将 html 字符串作为输入,并将 PDF 输出作为文件输出到客户端浏览器。

在我试用的几十种工具中,一个名为NReco PDF Generator 的产品似乎很适合我的需求,它是基于wkhtmltopdf 的众多衍生工具之一。

这是我的测试代码:

var strHtml = String.Format("<h1>Hello World!</h1");

Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");

(new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(strHtml, null, Response.OutputStream);
Response.End();

使用上面的代码,我希望看到一个 PDF 文件被传递到我的浏览器。相反,我只看到在我的开发者控制台中生成的输出流。 (顺便说一句,我正在使用 Chrome)

我的问题不是关于上述产品的工作原理,我认为它按预期工作,而是关于我的代码是否缺少对 .NET 的 Response 对象的任何操作或做错了什么。正如我已经指出的,我可以在控制台中看到转换后的 Pdf 流。我认为这只是在文件中捕获该流并将其传递给客户端的问题。

【问题讨论】:

    标签: c# pdf response file-conversion


    【解决方案1】:

    缺少的行是Response.BinaryWrite(pdfBytes)。如果没有该行,PDF 将不会呈现给用户。

    据我所知,你不需要这些行:

    Response.Clear();
    Response.ClearHeaders();
    

    以下对我有用(显然,您需要添加using NReco.PdfGenerator;

    string strHtml = String.Format("<h1>Hello World!</h1");
    HtmlToPdfConverter pdfConverter = new HtmlToPdfConverter();
    var pdfBytes = pdfConverter.GeneratePdf(strHtml);
    
    Response.ContentType = "application/pdf";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.AddHeader("Content-Disposition", "Inline; filename=TEST.pdf");
    Response.BinaryWrite(pdfBytes);
    Response.Flush();
    Response.End();
    

    【讨论】:

      【解决方案2】:

      将 PDF 存储为字节数组,然后将其写入响应。

      var pdfBytes = new NReco.PdfGenerator.HtmlToPdfConverter().GeneratePdf(strHtml);
      Response.BinaryWrite(pdfBytes);
      

      而不是

      (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(strHtml, null, Response.OutputStream);
      

      灵感来自NReco's site

      【讨论】:

      • Mason - 这是我之前尝试过的几种方法之一,虽然它似乎有效,但我没有看到将 PDF 传递给浏览器。
      • 使用浏览器的调试工具检查来自服务器的响应。查看文件是否遇到或以某种方式嵌入到 HTML 文档中。
      猜你喜欢
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多