如何使用iTextSharp生成PDF,并在WebApi2 C#/.NET项目中从web浏览器中显示/下载它?

如何使用iTextSharp生成PDF,并在WebApi2 C#/.NET项目中从web浏览器中显示/下载它?,c#,itext,asp.net-web-api2,httpcontext,response.contenttype,C#,Itext,Asp.net Web Api2,Httpcontext,Response.contenttype,这件事快把我逼疯了。 我正在尝试实现,如果您下载该项目,它将起作用,但我有一个WebApi2应用程序,而不是经典的aspx,因此我在响应方面有问题(当前上下文中不存在名称“Response”) 我尝试了几种方法,例如向响应中添加HttpContext.Current,如下所示: HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("Content-

这件事快把我逼疯了。 我正在尝试实现,如果您下载该项目,它将起作用,但我有一个WebApi2应用程序,而不是经典的aspx,因此我在
响应
方面有问题(当前上下文中不存在名称“Response”)

我尝试了几种方法,例如向响应中添加HttpContext.Current,如下所示:

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文档显示在浏览器上或从浏览器下载


我在这里要做什么?

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

你是在什么背景下这么做的?您不需要响应对象从Web API控制器返回文件。例如,请参阅。如果您的方法签名类似于“我的方法签名”中的“公共HttpResponseMessage YourMethodName(HttpRequestMessage request)”,则您可以完全控制要从方法发送的响应。No
HttpRequestMessage request
。@Codemaster:您指的是什么上下文?他的意思是,如果您正在执行控制器操作,则应返回
HttpResponseMessage
ihttpackationresult
。不要直接写入
HttpContext.Current.Response
。如何将创建的pdf放入变量
stream
?更新了答案,希望有帮助!我在我的项目中粘贴了你的代码,但它不起作用。我得到了这些错误:
ReadTimeout='output.ReadTimeout'引发了一个类型为'System.invalidoOperationException'
的异常,而
WriteTimeout='output.WriteTimeout'引发了一个类型为'System.invalidoOperationException'
的异常,您什么时候会收到该异常<代码>内存流不支持访问内存流输出中的那些属性。它在创建时获取
ReadTimeout
WriteTimeout
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;
    }
}