How to generate PDF with iTextSharp and show/download it from web browser within a WebApi2 C#/.NET project?

9.1k Views Asked by At

This one is driving me mad. I'm trying to implement this example, which is working if you download the project, but I have a WebApi2 app, not the classic aspx, so I have problems with Response (The name 'Response' does not exist in the current context).

var document = new Document(PageSize.A4, 50, 50, 25, 25);

var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);

document.Open();

document.Add(new Paragraph("Hello World"));

document.Close();

Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=testDoc.pdf", "some string"));
Response.BinaryWrite(output.ToArray());

I tried several things like adding HttpContext.Current to the Response like this:

HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=testDoc.pdf", "some string"));
HttpContext.Current.Response.BinaryWrite(output.ToArray());

But there's no way I can make the .pdf document to show on/download from the browser.

What am I to do here?

1

There are 1 best solutions below

8
On BEST ANSWER

With HttpResponseMessage:

public HttpResponseMessage ExampleOne()
{
    var stream = CreatePdf();

    return new HttpResponseMessage
    {
        Content = new StreamContent(stream)
        {
            Headers =
            {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    };
}

With IHttpActionResult:

public IHttpActionResult ExampleTwo()
{
    var stream = CreatePdf();

    return ResponseMessage(new HttpResponseMessage
    {
        Content = new StreamContent(stream)
        {
            Headers =
            {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    });
}

Here is the CreatePdf method:

private Stream CreatePdf()
{
    using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
    {
        var output = new MemoryStream();

        var writer = PdfWriter.GetInstance(document, output);
        writer.CloseStream = false;

        document.Open();
        document.Add(new Paragraph("Hello World"));
        document.Close();

        output.Seek(0, SeekOrigin.Begin);

        return output;
    }
}