0
public IHttpActionResult DownloadPDF()
{
    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;
    }
}

我可以下载 PDF,但上下文为空。在这里,我使用的是内存流,我也尝试在相应的文件夹中下载文件流,但是如果我尝试打开下载的文件,那么内容也是空的。谁能帮我这里缺少什么?

4

1 回答 1

0

这是一种在使用 Web API 时通常对我有用的方法

private byte[] CreatePdf() {
    var buffer = new byte[0];
    //stream to hold output data
    var output = new MemoryStream();
    //creation of a document-object
    using (var document = new Document(PageSize.A4, 50, 50, 25, 25)) {
        //create a writer that listens to the document
        // and directs a PDF-stream to output stream
        var writer = PdfWriter.GetInstance(document, output);

        //open the document
        document.Open();

        // Create a page in the document
        document.NewPage();

        // Get the top layer to write some text
        var pdfContentBytes = writer.DirectContent;
        pdfContentBytes.BeginText();

        //add content to page
        document.Add(new Paragraph("Hello World"));

        //done writing text
        pdfContentBytes.EndText();

        // make sure any data in the buffer is written to the output stream
        writer.Flush();

        document.Close();
    }    
    buffer = output.GetBuffer();
    return buffer;
}

然后在行动中

public IHttpActionResult DownloadPDF() {
    var buffer = CreatePdf();

    return ResponseMessage(new HttpResponseMessage {
        Content = new StreamContent(new MemoryStream(buffer)) {
            Headers = {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    });
}
于 2017-12-08T11:37:12.407 回答