C# 使用itextsharp将pdf流式传输到用户浏览器

C# 使用itextsharp将pdf流式传输到用户浏览器,c#,jquery,asp.net,ajax,itextsharp,C#,Jquery,Asp.net,Ajax,Itextsharp,在这里,我试图跟随这篇文章: 我在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 outpu

在这里,我试图跟随这篇文章:

我在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并将其流式传输到用户的浏览器

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

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

%PDF-1.4 %���� 20 obj 流动 x�+�R �25便士�04WI�2P�5.��1.�� �BҸ4>>>>/Contents 2 0 R/父3 0 R>> endobj 10 obj endobj 30 obj endobj 50 obj endobj 60 obj endobj 外部参照 0 7 0000000000 65535 f 0000000 304 00000n 00000000150万元 000000039200000N 0000000 147 00000 n 0000000443000000N 000000048800000N 拖车 > %iText-5.3.5 起始外部参照 646 %%EOF {d:null}


我做错什么了吗?

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


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

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


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

使用xmlhttprequest时,您似乎无法接收二进制数据。jquery就是这样做的。 当你做一个表单发布一个标准的a href链接

它应该会起作用。因为响应类型由浏览器处理

确保您在服务器上设置了匹配的头,就像您所做的那样

contentDisposition = "attachment=\"" name "";
contentType = "application/pdf";

希望这对您有所帮助。使用xmlhttprequest时,您似乎无法接收二进制数据。jquery就是这样做的。 当你做一个表单发布一个标准的a href链接

它应该会起作用。因为响应类型由浏览器处理

确保您在服务器上设置了匹配的头,就像您所做的那样

contentDisposition = "attachment=\"" name "";
contentType = "application/pdf";

希望这对我有所帮助我这样做:

方法在页面aspx.cs中

    [WebMethod()]
    public static string CreatePdf()
    {

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30f, 30f, 30f, 30f);
        iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);

        doc.Open();
        doc.Add(new iTextSharp.text.Chunk("hello world"));
        doc.Close(); 
        // convert ms to byte and Base64
        return System.Convert.ToBase64String(ms.ToArray());


    }
函数jQuery

$("#createPdf").click(function () {
        //call ajax
        $.ajax({ 
            url: "main.aspx/CreatePdf",
            data: '{}',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                //pdf
                var downloadpdf = $('<a id="downloadpdf" download="file.pdf" href="data:application/pdf;base64,' + result.d + '" >');
                $('body').append(downloadpdf);
                document.getElementById("downloadpdf").click();
                $("#downloadpdf").remove();
            },
            error: function (req, status, error) {
                alert(error);
            }
        }); 
    });                                

我希望它能帮助别人

我就是这样做的:

方法在页面aspx.cs中

    [WebMethod()]
    public static string CreatePdf()
    {

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30f, 30f, 30f, 30f);
        iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);

        doc.Open();
        doc.Add(new iTextSharp.text.Chunk("hello world"));
        doc.Close(); 
        // convert ms to byte and Base64
        return System.Convert.ToBase64String(ms.ToArray());


    }
函数jQuery

$("#createPdf").click(function () {
        //call ajax
        $.ajax({ 
            url: "main.aspx/CreatePdf",
            data: '{}',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                //pdf
                var downloadpdf = $('<a id="downloadpdf" download="file.pdf" href="data:application/pdf;base64,' + result.d + '" >');
                $('body').append(downloadpdf);
                document.getElementById("downloadpdf").click();
                $("#downloadpdf").remove();
            },
            error: function (req, status, error) {
                alert(error);
            }
        }); 
    });                                

我希望它能帮助别人

您不能通过ajax下载文件。不要使用ajax,而是使用普通表单并从中发布。您不能通过ajax下载文件。这是一个很好的答案-使用普通表单post,没有ajax-文档将返回而不刷新页面这是一个很好的答案-使用普通表单post,没有ajax-文档将返回而不刷新页面