c# - 使用 itextsharp 将 pdf 流式传输到用户的浏览器

标签 c# jquery asp.net ajax itext

我正在尝试关注这篇文章:https://web.archive.org/web/20211020001758/https://www.4guysfromrolla.com/articles/030911-1.aspx

我在 Services.asmx 中有这个方法:

[WebMethod]
public void CreatePdf()
{
    // Create a Document object
    var document = new Document(PageSize.A4, 50, 50, 25, 25);

    // Create a new PdfWriter object, specifying the output stream
    var output = new MemoryStream();
    var writer = PdfWriter.GetInstance(document, output);

    // Open the Document for writing
    document.Open();

    // Create a new Paragraph object with the text, "Hello, World!"
    var welcomeParagraph = new Paragraph("Hello, World!");

    // Add the Paragraph object to the document
    document.Add(welcomeParagraph);

    // Close the Document - this saves the document contents to the output stream
    document.Close();

    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpContext.Current.Response.AddHeader("Content-Disposition",
        "attachment;filename=file.pdf");
    HttpContext.Current.Response.BinaryWrite(output.ToArray());        
}

还有我页面上的这段 jQuery 代码:

$('a.download').click(function () {

    $.ajax({
        type: "POST",
        url: "/Services.asmx/CreatePdf",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            alert(result.d);
        }
    });
});

这应该创建一个 pdf 并将其流式传输到用户的浏览器。

当我单击类 download 的链接时,我的 web 方法被点击并且代码运行。它只是不将 pdf 流式传输到浏览器。

如果我查看 Firebug,它会以状态 200 发布到我的方法,并且我得到以下响应:

%PDF-1.4 %���� 2 0 obj <>stream x�+�r �25P�04WI�2P�5��1�� �BҸ4>>>/Contents 2 0 R/Parent 3 0 R>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000304 00000 n 0000000015 00000 n 0000000392 00000 n 0000000147 00000 n 0000000443 00000 n 0000000488 00000 n trailer <<21ba8d519bb56a2d0ec514bcb9c47169>]>> %iText-5.3.5 startxref 646 %%EOF {"d":null}

我是不是做错了什么?

最佳答案

马克 B 是正确的。您需要让您的服务器端代码响应 pdf 输出流。

因此,将您的下载链接指向一个新文件,比如 PDFDownload.aspx,并将来自 CreatePdf 函数的代码放在 PDFDownload.aspx.cs 的 PageLoad 中。

关于c# - 使用 itextsharp 将 pdf 流式传输到用户的浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716425/

相关文章:

Jquery:在父div内的索引处选择子div

c# - 从 Input 控件获取数据到代码隐藏

javascript - 下拉选项无法使用 jquery 选择器访问?

jquery - 如何将 Bootstrap 图标颜色更改为黄色?

javascript - 缩小表 td 中的文本,使其适合大小。逐渐显示调整大小列上的文本

c# - 使用 DropDownList 设置整个网站背景的问题

javascript - 使用 Knockout 在 Asp.Net 中绑定(bind)日期

c# - Exception.ToString()上的OutOfMemory异常

c# - 当可以在 lambda 中使用 await 时,为什么不能在 lambda 中使用 yield?

C# 编译器 - 未分配字段和局部变量初始值