使用 iText 合并 PDF 并在客户端另存为流

Merge PDF using iText and save as stream on client side

我尝试使用我在这里找到的代码 http://web.archive.org/web/20111012184438/http://alex.buayacorp.com/merge-pdf-files-with-itext-and-net.html 将 2 个或多个 PDF 文件合并为一个。

我想实现输出作为流返回并保存在客户端。我试图修改代码但没有成功。该代码尝试将输出保存在服务器上,然后导致未授权访问异常。 谁有正确的线索?


private void MergePDFs()
{
    DataSourceSelectArguments args = new DataSourceSelectArguments();
    DataView view = (DataView)SqlDataSource1.Select(args);

    DataTable table = view.ToTable();
    List<PdfReader> readerList = new List<PdfReader>();

    foreach (DataRow myRow in table.Rows)
    {
        PdfReader pdfReader = new PdfReader(Convert.ToString(myRow[0]));
        readerList.Add(pdfReader);
    }

    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, Response.OutputStream);
    document.Open();

    foreach (PdfReader reader in readerList)
    {
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            copy.AddPage(copy.GetImportedPage(reader, i));
        }
    }

    document.Close();
    Response.AppendHeader("content-disposition", "inline; filename=OutPut.pdf");
    Response.ContentType = "application/pdf";
}

您似乎正在使用 OutputStream 将 PDF 字节作为文件写入服务器磁盘上。这通常是您在 Web 应用程序中不想要的东西。在 Web 应用程序中,您希望将字节写入 Response object,如 iTextSharp generated PDF: How to send the pdf to the client and add a prompt?

的答案中所述

常识会告诉您最好将字节直接写入 OutputStreamResponse,但经验告诉我们并非所有浏览器都能正确处理这些字节。最好先将 PDF 写入 MemoryStream(如 Create PDF in memory instead of physical file 中所述)。一旦内存中有字节,就可以将字节刷新到 Response object after 设置正确的 HTTP headers (尤其是 ContentLength 对于某些浏览器很重要)。

很明显,您不能在未经用户同意的情况下将字节写入客户端,例如因为

  1. 这将是一个安全隐患。浏览器不应允许服务器将任何内容写入最终用户的磁盘。
  2. 您对最终用户文件系统的组织一无所知(并非每台计算机都有 C: 驱动器)。

如果您希望最终用户保存 PDF,您应该使用以下 HTTP header:

Response.AddHeader("Content-Disposition", "attachment; filename=yourfile.pdf");

想了解更多信息?阅读 How To Write Binary Files to the Browser Using ASP.NET and Visual C# .NET

额外的建议:请帮我一个忙,不要使用糟糕的 iTextSharp 示例。合并 PDF 使用 PdfCopyNOT 使用 PdfWriter 完成。下载免费电子书 The Best iText Questions on Whosebug,您将节省大量时间 (1.) 搜索答案和 (2.) 避免错误答案。