Steven
Steven

Reputation: 18869

Streaming a pdf to the user's browser using itextsharp

I'm trying to follow this article here: https://web.archive.org/web/20211020001758/https://www.4guysfromrolla.com/articles/030911-1.aspx

I have this method in 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());        
}

And this jQuery code on my page:

$('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);
        }
    });
});

This is supposed to create a pdf and stream it to the user's browser.

When I click on a link with the class download, my web method gets hit and the code runs. It just doesn't stream the pdf to the browser.

If I look in Firebug, it posts to my method with status 200, and I get this Response:

%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}

Am I doing something wrong here?

Upvotes: 1

Views: 8570

Answers (3)

Diogo Cid
Diogo Cid

Reputation: 3794

Well i do this, that way:

Method in page 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());


    }

Function 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);
            }
        }); 
    });                                

I hope it help someone!

Upvotes: 1

silverfighter
silverfighter

Reputation: 6882

It looks like you cannot receive binary data when you use xmlhttprequest. (this is what jquery does). When you do a a form post a standard a href link

it should work. Because then the response type is handled by the browser...

make sure you set the matching headers on the server as you do...

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

hope this helps

Upvotes: 1

localhost
localhost

Reputation: 66

Marc B is correct. You need to have your server-side code respond with the pdf output stream.

So, point your download link to a new file, say PDFDownload.aspx, and place the code from your CreatePdf function in the PageLoad of PDFDownload.aspx.cs.

Upvotes: 4

Related Questions