我正在使用FileResult作为MVC中返回PDF文件的函数的返回值。

我应该在Web窗体中使用哪种返回类型?

谢谢

public FileResult PrintPDFVoucher(object sender, EventArgs e)
    {
        PdfDocument outputDoc = new PdfDocument();
        PdfDocument pdfDoc = PdfReader.Open(
            Server.MapPath(ConfigurationManager.AppSettings["Template"]),
            PdfDocumentOpenMode.Import
        );

        MemoryStream memory = new MemoryStream();

        try
        {
            //Add pages to the import document
            int pageCount = pdfDoc.PageCount;
            for (int i = 0; i < pageCount; i++)
            {
                PdfPage page = pdfDoc.Pages[i];
                outputDoc.AddPage(page);
            }
            //Target specifix page
            PdfPage pdfPage = outputDoc.Pages[0];

            XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
            XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);


            //Save
            outputDoc.Save(memory, true);
            gfxs.Dispose();
            pdfPage.Close();
        }
        finally
        {
            outputDoc.Close();
            outputDoc.Dispose();
        }

        var result = new FileContentResult(memory.GetBuffer(), "text/pdf");
        result.FileDownloadName = "file.pdf";
        return result;
    }

最佳答案

在ASP.NET Webforms中,您需要手动将文件写入Response流。 Web表单中没有结果抽象。

  Response.ContentType = "Application/pdf";
  //Write the generated file directly to the response stream
  Response.BinaryWrite(memory);//Response.WriteFile(FilePath); if you have a physical file you want them to download
  Response.End();


此代码未经测试,但这应该可以帮助您大致了解。

07-26 00:04