如何在 WebApi2 C#/.NET 项目中使用 iTextSharp 和 show/download 从 Web 浏览器生成 PDF?

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

这个快把我逼疯了。 我正在尝试实现 this example,如果您下载该项目,它就可以工作,但是我有一个 WebApi2 应用程序,而不是经典的 aspx,所以我遇到了 Response 的问题(The名称 'Response' 在当前上下文中不存在 ).

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());

我尝试了几种方法,例如将 HttpContext.Current 添加到 Response 中,如下所示:

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());

但是我无法使 .pdf 文档在浏览器中显示 on/download。

我在这里做什么?

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

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

这里是 CreatePdf 方法:

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