Boy Pasmo
Boy Pasmo

Reputation: 8471

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

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

Upvotes: 1

Views: 4755

Answers (2)

user3875617
user3875617

Reputation:

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

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

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

Upvotes: 4

Related Questions