Simon Price
Simon Price

Reputation: 3261

ASP.Net MVC 5 Render PDF in Browser from Byte[] C#

I am working with Kendo MVC and I want to render an uploaded PDF into a Tabstrip.

When getting the PDF file to show in the tab, I am calling my controller and subsequent service, getting the file data as a byte array and returning data into its respective div using the following code.

public FileStreamResult GetRxPdf(int prescriptionId)
{
    var retVal = _service.GetRxPdf(prescriptionId);
    byte[] byteArray = retVal.FileData;
    MemoryStream pdfStream = new MemoryStream();
    pdfStream.Write(byteArray, 0, byteArray.Length);
    pdfStream.Position = 0;
    return new FileStreamResult(pdfStream, retVal.ContentType);
}

The rendered output is not the PDF, but is as follows

%PDF-1.7 %���� 1 0 obj <>/OutputIntents[<>] /Metadata 148 0 R/ViewerPreferences 149 0 R>> endobj 2 0 obj <> endobj 3 0 obj <>/XObject<>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/Annots[ 7 0 R 10 0 R 11 0 R 21 0 R] /MediaBox[ 0 0 595.32 841.92] /Contents 4 0 R/StructParents 0>> endobj 4 0 obj <> stream x��]Ys�F~W��ɔ5�\�I�֒��[9[�yH�@S�̲�����7���=Ip��P�TE��3������1�>[,��&�e��7�ϖ��������������?�N/&���r~w����%~��lr5[|�mq�������$%�W׊e!I8+jAIÊ����ׯ��㣳��ӗ������|w|��eA�H�D����uqy3�����F������G/`�/�G��m�����4r�g����m�*��/s^%�HQ�R�]䛋����]��h1S>�W������R^�0>���՘�Q1(�'l�zL���z>棇��pm0����=�±7�;�� ?��]��ů�>�� ��U�~�O?��a�^���>�A+�xD %�Ԍ�H� /�������$MD�~�A2V6�Ѣ��Q....more file data here... 0000166807 00000 n trailer <] >> startxref 166853 %%EOF

When the data comes back via an ajax call it this is how it is passed to the div

 $("#divRxPdf").html(data);

I would be grateful if anyone could help me with this and show the PDF in the Div accordingly.

Upvotes: 1

Views: 1913

Answers (2)

karthickj25
karthickj25

Reputation: 1197

Update:

PDF needs to be embeded in the HTML with <embed> or <iframe> . You could also use library such as pdf.js to render pdf files with some controls.

The pdf.js readme has samples and how to: https://github.com/mozilla/pdf.js


You can return the pdf as file by passing the binary using retun File() method

public ActionResult GetRxPdf(int prescriptionId)
 {
    var retVal = _service.GetRxPdf(prescriptionId);
    byte[] byteArray = retVal.FileData;      
   return File(byteArray , "application/pdf" , "Filename.pdf");
}

Upvotes: 2

Baskar John
Baskar John

Reputation: 726

You can use object tag to achieve it.

$obj = $('<object>'); 
$obj.attr("data","Url to PDF");
$obj.attr("type","application/pdf");

$("#pdfdiv_content").append($obj);

For more details refer this link

Upvotes: 0

Related Questions