繁体   English   中英

ASP.NET Core 2中的MemoryStream PDF文件

[英]MemoryStream PDF file in ASP.NET Core 2

不断收到错误消息“无法访问关闭的流”。

在流式传输之前,是否需要先将文件物理保存在服务器上? 我对Excel文件也做同样的事情,并且效果很好。 在此处尝试对PDF文件使用相同的原理。

    [HttpGet("ExportPdf/{StockId}")]
    public IActionResult ExportPdf(int StockId)
    {
        string fileName = "test.pdf";

        MemoryStream memoryStream = new MemoryStream();

       // Create PDF document  
        Document document = new Document(PageSize.A4, 25, 25, 25, 25);

        PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStream);

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

        memoryStream.Position = 0;

        return File(memoryStream, "application/pdf", fileName);
    }

您正在使用iText7吗? 如果是,请将该标签添加到您的问题上。

using (var output = new MemoryStream())
{
    using (var pdfWriter = new PdfWriter(output))
    {
        // You need to set this to false to prevent the stream
        // from being closed.
        pdfWriter.SetCloseStream(false);

        using (var pdfDocument = new PdfDocument(pdfWriter))
        {
            ...
        }

        var renderedBuffer = new byte[output.Position];
        output.Position = 0;
        output.Read(renderedBuffer, 0, renderedBuffer.Length);

        ...
    }
}

根据David Liang的评论切换到iText&(7.1.1)版本

这是对我有用的代码,一个完整的方法:

    [HttpGet]
    public IActionResult Pdf()
    {
        MemoryStream memoryStream = new MemoryStream();

        PdfWriter pdfWriter = new PdfWriter(memoryStream);

        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

        Document document = new Document(pdfDocument);
        document.Add(new Paragraph("Welcome"));
        document.Close();

        byte[] file = memoryStream.ToArray();
        MemoryStream ms = new MemoryStream();
        ms.Write(file, 0, file.Length);
        ms.Position = 0;

        return File(fileStream: ms, contentType: "application/pdf", fileDownloadName: "test_file_name" + ".pdf");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM