I am saving PDF files for Employee with HttpPostedFilebase where the path of the pdf will be saved in the database. Now I want to display the PDF in a div, not the download link. For showing image, I have done <img src=@Url.Content(Model.employee_image) />. How can I do the same for Displaying PDF?
First Method
As you have mentioned you have link/URL of the image and want to show something like that, so get the url of .pdf file in view and append it using
<object>
or <iframe>
tag of HTML
Suppose you have Model.PdfURL saved in the database, then you can show it in view using code below
<iframe src="https://docs.google.com/gview?url=@Model.PdfURL" width="200" height="200" type='application/pdf'>
</iframe>
For example, I have the pdf link as https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf
Then looking at the above HTML, my code would be
<iframe src="https://docs.google.com/gview?url=https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf&embedded=true" width="200" height="200" type='application/pdf'>
</iframe>
Note: if your website has HTTP(not secured URL) use HTTP for docs.google.com also
Working fiddle here
Second approach
You can use external library http://mozilla.github.io/pdf.js/examples/
Third approach
Display PDF File as PartialView. You can not specify the return type File as
PartialViewResult
.
Let's use the HTML 5 tag embed in partialview to display pdf within browser and render the partial view inside div using AJax.ActionLink helper.
<div>@Ajax.ActionLink("View Temp PDF", "PDFPartialView", new AjaxOptions { UpdateTargetId = "pdfContainer" })</div>
Let's create action method PDFPartialView
inside Home controller that returns
PartialViewResult
as below.
public PartialViewResult PDFPartialView()
{
//if you don't have url get the url from database here by passing id in the ActionMethod
// and pass it in Partial View using ViewBag
return PartialView();
}
Add view by selecting it as partial view. We have created partial view PDFPartialView. Create embed html 5 tag inside the partial view & specify src to the relative path of the PDF file as below.
<h3>Partial for display PDF</h3><br />
<embed src="/PDFURL.pdf" type="application/pdf"></embed>
<!--Or you can use iframe also-->
If the above answer doesn’t work for you, here are the few links with same approach of <embed> tag, but explained in detail
https://www.aspsnippets.com/Articles/Display-Show-PDF-file-embedded-in-View-in-ASPNet-MVC-Razor.aspx
Second link which has 4 alternatives for your issue
https://www.codeproject.com/Tips/697733/Display-PDF-within-web-browser-using-MVC
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly