Adem Aygun
Adem Aygun

Reputation: 582

Failed to load PDF document (ASP.NET MVC ajax)

I need display dynamically pdf. But I get error : Failed to load PDF document.(I use Chrome)

Index.cshtml:

<div >
    <h3> AJAX: (data='@@Url.Action("GetPDF")')</h3>
    <object data='@Url.Action("GetPDF")' type="application/pdf" width="300" height="200"></object>
</div>
<div>
    <h3> PATH: (data="/Pdf/32_1.pdf")</h3>
    <object data="/Pdf/32_1.pdf" type="application/pdf" width="300" height="200"></object>
</div>

HomeController.cs:

public FileStreamResult GetPDF()
{
    string fileName = "32_1.pdf";
    FileStream fs = new FileStream(@"C:\Documents\MUH0000020\" + fileName, FileMode.Open, FileAccess.Read);
    return File(fs, "application/pdf", fileName);
}

result :

enter image description here

please help.

Upvotes: 4

Views: 4453

Answers (2)

Brian MacKay
Brian MacKay

Reputation: 32029

When you use FileStreamResult() or File() to return a file, and you specify a filename, MVC renders a Content-Disposition header that looks like this:

attachment; filename=someFile.pdf

The 'attachment' part is specifically telling the browser not display this document in-browser, but rather to send it as a file. And it appears that Chrome's PDF viewer chokes in that situation, probably by design!

This seems to be a better way to specify filename, when trying to get a PDF to display in-browser, in Chrome:

Response.AddHeader("Content-Disposition", "inline; filename=someFile.pdf");

return new FileStreamResult(stream, "application/pdf");

As a side note, your solution above actually works because you aren't specifying the file name at all, which gets around the header problem! It works, but not because of the StreamReader, which is actually for working with text files. You could have passed in a MemoryStream or FileStream directly and been fine.

More: Content-Disposition:What are the differences between "inline" and "attachment"?

Upvotes: 3

Adem Aygun
Adem Aygun

Reputation: 582

I changed my method :

public FileStreamResult GetPDF()
        {
            string fileName = "32_1.pdf";
            StreamReader reader = new StreamReader(@"C:\Documents\MUH0000020\" + fileName);

            return new FileStreamResult(reader.BaseStream, "application/pdf");
        }

Upvotes: 1

Related Questions