user2328912
user2328912

Reputation: 245

Show byte[] as pdf with html5

Hi i have a big problem. I have a byte[] receveid from a Wcf service. The byte array represents a pdf file. In the Controller, i would like to do this:

PDFDto pdfDTO = new PDFDTO();
pdfDTO.pdfInBytes = pdfInBytes; //the byte array representing pdf
return PartialView("PopupPDF,pdfDTO);

in the View i would like to do this:

      <object data="@Model.pdfInBytes" width="900" height="600" type="application/pdf"> </object>

but it seems uncorrect. I've searched in all the internet, there are a lot of posts about this problem but no one matches perfectly my situation. Have you got any ideas?Thanks a lot!

Upvotes: 5

Views: 11237

Answers (2)

serene
serene

Reputation: 685

protected ActionResult InlineFile(byte[] content, string contentType, string fileDownloadName)
    {
        Response.AppendHeader("Content-Disposition", string.Concat("inline; filename=\"", fileDownloadName, "\""));
        return File(content, contentType);
    }

Add this code to your base controller or the controller itself and call this function to show file in the browser itself.

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101594

I would recommend creating another action on the controller designed specifically for rendering the PDF data. Then it's just a matter of referencing it within your data attribute:

data="@Url.Action("GetPdf", "PDF")"

I'm not sure you can dump raw PDF data within the DOM without hitting some kind of encoding issue. You may be able to do like images, though I've never tried. But, for demo's sake and image would look like:

src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"

So, assuming the same could be done it would probably look like the following:

@{
  String base64EncodedPdf = System.Convert.ToBase64String(Model.pdfInBytes);
}

@* ... *@
<object data="data:application/pdf;base64,@base64EncodedPdf"
        width="900" height="600" type="application/pdf"></object>

I still stand by my original response to create a new action however.

Upvotes: 12

Related Questions