How to open a PDF file in an <iframe>?

2019-01-01 03:41发布

问题:

I want to open the pdf file in an iframe. I am using following code:

<a class=\"iframeLink\" href=\"https://something.com/HTC_One_XL_User_Guide.pdf\"
   jQuery1640737952376988841=\"85\"> User guide </a>

It is opening fine in Firefox, but it is not opening in IE8.

Does anyone know how to make it work also for IE ?

回答1:

Using an iframe to \"render\" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id=\"pdfRenderer\"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: \"https://something.com/HTC_One_XL_User_Guide.pdf\",
  id: \"pdfRendered\",
  pdfOpenParams: {
    view: \"FitH\"
  }
}).embed(\"pdfRenderer\");


回答2:

This is the code to link an HTTP(S) accessible PDF from an <iframe>:

<iframe src=\"https://research.google.com/pubs/archive/44678.pdf\"
   width=\"800px\" height=\"600px\" >

Fiddle: http://jsfiddle.net/cEuZ3/1545/

EDIT: and you can use Javascript, from the <a> tag (onclick event) to set iFrame\' SRC attribute at runtime...

EDIT 2: Appearently, it is a bug (but there are workarounds):

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?



回答3:

It also important to make sure that the web server sends the file with Content-Disposition = inline. this might not be the case if you are reading the file yourself and send it\'s content to the browser:

in php it will look like this...

...headers...
header(\"Content-Disposition: inline; filename=doc.pdf\");
...headers...

readfile(\'localfilepath.pdf\')


回答4:

Do it like this:

<iframe src=\"http://samplepdf.com/sample.pdf\" width=\"800px\" height=\"600px\"></iframe>

Remember to close iframe tag.