Search code examples
c#pdfcode-behindmemorystreamhtml-object

How to memory stream a pdf to a HTML Object


My objective is to display a PDF in a html-<object> from a memory stream.

From C# code behind I can get a PDF from a Memory Stream to display in a browser like this, This will effectively covert the whole browser to a PDF reader (not ideal) since I lose my application controls etc. I'd like to keep the feel of the application like everything is inside one form:

    MyWeb.Service.Retrieve.GetPdfById r = new MyWeb.Service.Retrieve.GetPdfById();

            MemoryStream byteStream = new MemoryStream(r.Execute("705"));
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "inline; filename=dummy.pdf");
            Response.AddHeader("content-length", byteStream.Length.ToString());
            Response.BinaryWrite(byteStream.ToArray());
            Response.End();

In HTML I can get a PDF to display within an <object> like this, this means I can display it ideally in a <div> but it's not from a dynamically generated memory stream:

    <object data="PDF_File/myFile.pdf" type="application/pdf" width="800px"height="600px">
      alt : <a href="PDF_File/myFile.pdf">TAG.pdf</a>
    </object>

So how do I get the memory stream into the HTML-<object> please?


Solution

  • The data attribute of the object tag should contain a URL which points to an endpoint which will provide the PDF byte stream.

    To make this page work, you will need to add an additional handler that provides the byte stream, e.g. GetPdf.ashx. The ProcessRequest method of the handler would prepare the PDF bytestream and return it inline in the response, preceded by the appropriate headers indicating it is a PDF object.

    protected void ProcessRequest(HttpContext context)
    {
        byte[] pdfBytes = GetPdfBytes(); //This is where you should be calling the appropriate APIs to get the PDF as a stream of bytes
        var response = context.Response;
        response.ClearContent();
        response.ContentType = "application/pdf";
        response.AddHeader("Content-Disposition", "inline");
        response.AddHeader("Content-Length", pdfBytes.Length.ToString());
        response.BinaryWrite(pdfBytes); 
        response.End();
    }
    

    Populate the data attibute with a URL pointing at the the handler, e.g. "GetPdf.ashx".