生成pdf而不将其保存到磁盘然后将其显示给浏览器

Generate a pdf without saving it to disk then show it to browser

是否可以在不保存到磁盘的情况下合并 pdf 文件?

我有一个生成的 pdf(通过 itextsharp)和一个物理 pdf 文件。这两个应该显示给浏览器合并。

我目前拥有的是,(伪代码)

public ActionResult Index()
{
  // Generate dyanamic pdf first
  var pdf = GeneratePdf();
  // Then save it to disk for retrieval later
  SaveToDisc(pdf);
  // Retrieve the static pdf
  var staticPdf = GetStaticPdf();
  // Retrieve the generated pdf that was made earlier
  var generatedPdf = GetGeneratedPdf("someGeneratedFile.pdf");
  // This creates the merged pdf
  MergePdf(new List<string> { generatedPdf, staticPdf }, "mergedPdf.pdf");

  // Now retrieve the merged pdf and show it to the browser
  var mergedPdf = GetMergedPdf("mergedPdf.pdf");

  return new FileStreamResult(mergedFile, "application/pdf");
}

这可行,但我只是想知道是否可以合并 pdf 并将其显示给浏览器而不在光盘上保存任何内容?

如有任何帮助,我们将不胜感激。谢谢

您可以尝试这样使用 PdfWriter class 和 MemoryStream

using (MemoryStream ms = new MemoryStream())
{
    Document doc = new Document(PageSize.A4, 60, 60, 10, 10);
    PdfWriter pw = PdfWriter.GetInstance(doc, ms);
    //your code to write something to the pdf
    return ms.ToArray();
}

您还可以参考:Creating a PDF from a RDLC Report in the Background

此外:如果 data 是内存中的 PDF,那么您需要做 data.CopyTo(base.Response.OutputStream);

试试这个

    string path = Server.MapPath("Yourpdf.pdf");
    WebClient client = new WebClient();
    Byte[] buffer = client.DownloadData(path);

    if (buffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }