如何将PDF返回到MVC中的浏览器?

我有iTextSharp的这个演示代码

Document document = new Document(); try { PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create)); document.Open(); document.Add(new Paragraph("Hello World")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); 

如何让控制器将pdf文档返回给浏览器?

编辑:

运行此代码确实打开Acrobat,但出现错误消息“文件已损坏,无法修复”

  public FileStreamResult pdf() { MemoryStream m = new MemoryStream(); Document document = new Document(); PdfWriter.GetInstance(document, m); document.Open(); document.Add(new Paragraph("Hello World")); document.Add(new Paragraph(DateTime.Now.ToString())); m.Position = 0; return File(m, "application/pdf"); } 

任何想法,为什么这是行不通的?

返回一个FileContentResult 。 你的控制器动作的最后一行是这样的:

 return File("Chap0101.pdf", "application/pdf"); 

如果您正在dynamic生成此PDF,最好使用MemoryStream ,并在内存中创build文档,而不是保存到文件。 代码会是这样的:

 Document document = new Document(); MemoryStream stream = new MemoryStream(); try { PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream); pdfWriter.CloseStream = false; document.Open(); document.Add(new Paragraph("Hello World")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); stream.Flush(); //Always catches me out stream.Position = 0; //Not sure if this is required return File(stream, "application/pdf", "DownloadName.pdf"); 

我得到它与这个代码工作。

 using iTextSharp.text; using iTextSharp.text.pdf; public FileStreamResult pdf() { MemoryStream workStream = new MemoryStream(); Document document = new Document(); PdfWriter.GetInstance(document, workStream).CloseStream = false; document.Open(); document.Add(new Paragraph("Hello World")); document.Add(new Paragraph(DateTime.Now.ToString())); document.Close(); byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return new FileStreamResult(workStream, "application/pdf"); } 

如果您从操作方法返回FileResult ,并在控制器上使用File()扩展方法,那么执行您想要的操作就非常简单。 File()方法会覆盖File()的二进制内容,文件path或Stream

 public FileResult DownloadFile() { return File("path\\to\\pdf.pdf", "application/pdf"); } 

您必须指定:

 Response.AppendHeader("content-disposition", "inline; filename=file.pdf"); return new FileStreamResult(stream, "application/pdf") 

直接在浏览器中打开文件,而不是下载

我遇到了类似的问题,我偶然发现了一个解决scheme。 我使用了两个post,一个来自堆栈 ,显示返回下载的方法,另一个显示ItextSharp和MVC的工作解决scheme。

 public FileStreamResult About() { // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); Document document = new Document(PageSize.A4.Rotate()); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); // Set up fonts used in the document Font font_heading_1 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 19, Font.BOLD); Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9); // Create the heading paragraph with the headig font Paragraph paragraph; paragraph = new Paragraph("Hello world!", font_heading_1); // Add a horizontal line below the headig text and add it to the paragraph iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; paragraph.Add(seperator); // Add paragraph to document document.Add(paragraph); // Close the PDF document document.Close(); // Hat tip to David for his code on stackoverflow for this bit // https://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf"); // Return the output stream return File(output, "application/pdf"); //new FileStreamResult(output, "application/pdf"); } 

您可以创build一个自定义类来修改内容types,并将该文件添加到响应中。

http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

我知道这个问题是古老的,但我想我会分享这个,因为我找不到任何类似的东西。

我想使用Razor来创build我的视图/模型,并将它们渲染为Pdf

通过这种方式,我可以使用标准的html输出来控制pdf演示文稿,而不是如何使用iTextSharp来编排文档。

项目和源代码在这里可以使用nuget安装说明:

https://github.com/andyhutch77/MvcRazorToPdf

 Install-Package MvcRazorToPdf 

你通常会做一个Response.Flush,然后是一个Response.Close,但由于某种原因iTextSharp库似乎不喜欢这个。 数据并没有通过,Adobe认为PDF是腐败的。 退出Response.Close函数,看看你的结果是否更好:

 Response.Clear(); Response.ContentType = "application/pdf"; Response.AppendHeader("Content-disposition", "attachment; filename=file.pdf"); // open in a new window Response.OutputStream.Write(outStream.GetBuffer(), 0, outStream.GetBuffer().Length); Response.Flush(); // For some reason, if we close the Response stream, the PDF doesn't make it through //Response.Close(); 

如果你从DB返回var-binary数据在popup窗口或浏览器上显示PDF,请按照以下代码进行操作: –

查看页面:

 @using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post)) { <a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a> } 

扫描控制器:

 public ActionResult DisplayPDF() { byte[] byteArray = GetPdfFromDB(4); MemoryStream pdfStream = new MemoryStream(); pdfStream.Write(byteArray, 0, byteArray.Length); pdfStream.Position = 0; return new FileStreamResult(pdfStream, "application/pdf"); } private byte[] GetPdfFromDB(int id) { #region byte[] bytes = { }; string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=@Id and Enabled = 1"; cmd.Parameters.AddWithValue("@Id", id); cmd.Connection = con; con.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { if (sdr.HasRows == true) { sdr.Read(); bytes = (byte[])sdr["Scan_Pdf_File"]; } } con.Close(); } } return bytes; #endregion }