iTextSharp generated PDF: How to send the pdf to the client and add a prompt?

前端 未结 5 482
半阙折子戏
半阙折子戏 2020-12-01 17:25

I have generated a pdf using iTextSharp, when its created it saves automatically in the location provided in my code on the server not on the client side and of course witho

5条回答
  •  無奈伤痛
    2020-12-01 18:10

    You do not need to use MemoryStream. Use Response.OutputStream instead. That's what it's there for. No need to use Response.BinaryWrite() or any other call to explicitly write the document either; iTextSharp takes care of writing to the stream when you use Response.OutputStream.

    Here's a simple working example:

    Response.ContentType = "application/pdf";
    Response.AppendHeader(
      "Content-Disposition",
      "attachment; filename=test.pdf"
    );
    using (Document document = new Document()) {
      PdfWriter.GetInstance(document, Response.OutputStream);
      document.Open();
      document.Add(new Paragraph("This is a paragraph"));
    }
    

    Here's how to add the proper HTTP headers. (getting the prompt to save the file) And if your code is in a web form, (button click handler), add Response.End() to the code example above after the using statement so that the web form's HTML output is not appended the PDF document.

提交回复
热议问题