1

Is it possible to merged pdf file without saving it to disk?

I have a generated pdf (via itextsharp) and a physical pdf file. These two should show to the browser as merged.

What I currently have is, (a pseudo code)

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");
}

This works, but I was just wondering if, would it be possible to just merged the pdf and show it to the browser without saving anything on the disc?

Any help would be much appreciated. Thanks

Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67
  • We shove non-disk pdfs out the http response all the time at my shop. Just get a ref to the raw binary as a byte array, clear the response, set the headers (especially the mime type), and write. – Paul Kienitz Oct 14 '15 at 06:45
  • 1
    @PaulKienitz cool, Think you can show me it in code? for references – Boy Pasmo Oct 14 '15 at 06:47

2 Answers2

4

You can try to use PdfWriter class and MemoryStream like this:

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();
}

You can also refer: Creating a PDF from a RDLC Report in the Background

Additionally: if data is the PDF in memory, than you need to do data.CopyTo(base.Response.OutputStream);

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

try this

    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);
    }