Ray
Ray

Reputation: 510

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?

Upvotes: 2

Views: 8022

Answers (2)

Eugene
Eugene

Reputation: 2878

You could try the following:

  1. Stream PDF as inline PDF inside iframe but this imposes size limitations and not working in IE and older browsers because of security issues.
  2. Use PDFObject.js to embed PDF as into HTML page (and optionally point it to the link to get dynamically generated PDF from the server)

Upvotes: 0

israel altar
israel altar

Reputation: 1794

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".

Upvotes: 2

Related Questions