128

我有这个 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");
    }

任何想法为什么这不起作用?

4

11 回答 11

133

返回一个FileContentResult。控制器操作的最后一行类似于:

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

如果您正在动态生成此 PDF,最好使用MemoryStream, 并在内存中创建文档而不是保存到文件中。代码将类似于:

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");
于 2009-10-02T16:13:20.863 回答
70

我让它与这段代码一起工作。

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");    
}
于 2009-10-02T19:53:18.433 回答
29

您必须指定:

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

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

于 2014-04-02T18:04:38.340 回答
18

如果您FileResult从您的操作方法返回 a ,并File()在控制器上使用扩展方法,那么做您想做的事情就很容易了。方法上有一些覆盖File(),它将采用文件的二进制内容、文件的路径或Stream.

public FileResult DownloadFile()
{
    return File("path\\to\\pdf.pdf", "application/pdf");
}
于 2009-10-02T16:20:08.850 回答
11

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

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");
}
于 2009-11-04T16:34:48.723 回答
6

FileStreamResult当然有效。但是,如果您查看Microsoft Docs,它继承自ActionResult -> FileResult,它有另一个派生类FileContentResult。它“将二进制文件的内容发送到响应”。因此,如果您已经拥有byte[],则应该FileContentResult改用。

public ActionResult DisplayPDF()
{
    byte[] byteArray = GetPdfFromWhatever();

    return new FileContentResult(byteArray, "application/pdf");
}
于 2019-08-16T13:14:35.837 回答
3

您可以创建自定义类来修改内容类型并将文件添加到响应中。

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

于 2009-10-02T16:05:10.407 回答
3

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

我想使用 Razor创建我的视图/模型,并将它们呈现为 Pdfs

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

项目和源代码可在此处获得 nuget 安装说明:

https://github.com/andyhutch77/MvcRazorToPdf

Install-Package MvcRazorToPdf
于 2013-11-25T16:57:37.993 回答
2

您通常会执行 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();
于 2009-11-04T16:41:47.517 回答
2
HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");

如果文件名是动态生成的,那么如何在此处定义文件名,它是通过此处的 guid 生成的。

于 2018-07-04T06:44:25.530 回答
1

如果您从 DB 返回 var-binary 数据以在弹出窗口或浏览器上显示 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
        }
于 2017-10-10T10:20:02.713 回答