View PDF as part of the page

Peter picture Peter · Jun 22, 2011 · Viewed 65.3k times · Source

I am trying to view a PDF document in my MVC web page, but I cant make it to work.

I would like the PDF to be displayed as a part of the other stuff on the page (header, footer etc.). Currently I have a solution where the PDF is shown, but on the entire page.

Has anybody done this, if yes then how?

Answer

Beygi picture Beygi · Jun 22, 2011

Why don't you try using iframe like this :

<iframe src="even file stream action url"></iframe>

I suggest to use object tag if it's possible, use iframe just for testing.

If you want to render PDF as part of the page as you just did

src='<% Html.RenderAction("GetPDF"); %>'

Then this is your option

If you need complete control over PDF content using CSS or whatsoever, like Google books and so on, then you need tools that help you to convert each requested page of PDF to Plain Text, HTML or even image. tools like PDFsharp. Search Google For Tools

If you want display PDF as part of the page then this is what you have to do

ASPX: src="<%= Url.Action("GetPDF") %>"
Razor: src="@Url.Action("GetPDF")"

And final answer could be

<object data="<%= Url.Action("GetPDF") %>" type="application/pdf" width="300" height="200">
    alt : <a href="data/test.pdf">test.pdf</a>
</object>

And in the case that you want to return PDF as Stream then you need

public FileStreamResult GetPDF()
{
    FileStream fs = new FileStream("c:\\PeterPDF2.pdf", FileMode.Open, FileAccess.Read);
    return File(fs, "application/pdf");
}