4

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.

2 Answers 2

3

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"?

Sign up to request clarification or add additional context in comments.

Comments

1

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");
        }

1 Comment

This helped me figure out what's actually going on in this situation. See my answer for details!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.