ASP.NET Core 2中的MemoryStream PDF文件

时间:2018-03-06 17:42:21

标签: c# asp.net asp.net-core-2.0

继续收到错误消息“无法访问已关闭的流。”

在流式传输之前,是否需要先将文件物理保存在服务器上?我正在使用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);
    }

2 个答案:

答案 0 :(得分:0)

您使用的是Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim intResponse As Integer If MsgBox("Are you sure you would like to exit the calculator?", vbYesNo + vbQuestion) = vbNo Then Cancel = True End If ThisWorkbook.Saved = True End Sub 吗?如果是,请在您的问题上添加该标记。

iText7

答案 1 :(得分:0)

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

这是适合我的代码,一个完整的方法:

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