iTextSharp |无法在IE中输出PDF

时间:2012-01-09 16:50:10

标签: c# asp.net-mvc-3 pdf pdf-generation itextsharp

我最近遇到了一个问题,即将在iTextSharp中生成的PDF输出到新窗口,并且无法找到解决问题的方法。

此问题似乎只出现在IE中,并且在新窗口打开时,它仍然是空白的,似乎根本不加载PDF。 (Chrome和Firefox似乎工作得很好)

我将详细介绍这个过程,希望能为大家提供一些帮助:

第1步:

用户单击View中的“打印”按钮,这将调用以下Javascript来执行:

window.open($("#PrintURL").val(), 'Print_Preview', 'resizable=1');

第2步:

调用的URL将适当的数据拉入模型,然后将其传递到部分视图中,该视图将传递到PDFResult中,如下所示:

//Grabs the Data
var data = reportAgent.GetData();

//Builds a string that contains the Report layout and builds the Report
string html = ControllerContext.RenderPartialAsString("~/Views/Reports/Report.cshtml", data);

return new PDFResult(html, ...);

第3步:

在PDFResult ExecuteResult()方法中,我构建了报告将输出的文档,并调整其他参数,例如PageSize,Headers和Footers。

public override void ExecuteResult(ControllerContext context)
{
    //Sets Response to output a PDF
    var response = context.HttpContext.Response;
    response.ContentType = "application/pdf";

    //Generate Document
    Document document = new Document();

    //Sets Page Size and Styles

    //Build Headers and Footers and Add to Document

    //Builds the document writer and prepares a Print Dialog upon opening
    PdfWriter writer = PdfWriter.GetInstance(document, context.HttpContext.Response.OutputStream);      
    PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
    writer.SetOpenAction(action);     
    writer.PageEvent = page;
    document.Open();

    //Iterates through the html string that was passed in and formats the document

    document.Close();
}

我似乎无法弄清楚为什么新窗口在Internet Explorer中保持空白,而大多数其他浏览器似乎工作正常。 (我知道我过去曾在IE中使用过相同的过程,我现在很难过。)

非常感谢任何改进此过程的想法/建议。

更新


我正在测试一些建议的更改,当我删除构建文档的区域并添加以下内容时:

document.Add(new Phrase("TEST"));

只会向PDF添加一行,然后生成它。我收到“Internet Explorer无法显示网页”错误,并提供诊断连接问题选项。单击“诊断连接问题”选项并完成后,将按预期加载PDF。

当新窗口尝试加载PDF时,这是不是“准备好”的问题?

(这是在IE8中)

1 个答案:

答案 0 :(得分:0)

我设法最终解决了这个问题。在准备好显示PDF之前,窗口似乎已打开。 (这是通过简单地刷新窗口来确定的,然后PDF会正确显示。)

因此,我没有打开特定网址的窗口,而是生成了一个窗口并在窗口中打开了URL,这似乎解决了这个问题。)