4

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!

Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
user2328912
  • 235
  • 2
  • 3
  • 17
  • Do you want the user to download the PDF as a file or to have the document embedded in the page? – D Stanley Jun 24 '13 at 13:14
  • the document embedded in the page. (i've created a nice popup with td, css etc. etc. so i don't want the pdf in another page). For example.. if object data="URL TO A LINK" , it's all ok. But if object data =@Model.pdfInBytes , page is blank – user2328912 Jun 24 '13 at 13:16

2 Answers2

12

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.

Community
  • 1
  • 1
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1
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.

serene
  • 685
  • 6
  • 16