Kategoriarkiv: object

Embedding a PDF file dynamically on a web page

So embedding a PDF to a web page is pretty easy. All you need to do is to add an object or embed element to your HTML.

Actually, you could use only object or embed, depending on browser support. But using both is a safeguard. If object fails to load it’s data, it will render it’s child elements instead, in this case the embed element.

There are spaces between the < and object/embed elements since WordPress doesn’t allow these elements. Remove it if copying this code.

But what if you don’t know what PDF file you want to display, and you want to load it dynamically? This is what I was trying to do, and of course I ran into problems displaying the PDF in Internet Explorer. This is how you should be able to set which file will be loaded using javascript. First, we add the elements to our HTML. To make it easier to get the elements in our javascript, give them a unique id.

Then, in javascript, we SHOULD be able to change witch PDF should be shown like this.

It works perfectly in Chrome, but in IE (tried versions 10 and 11 as well as emulated 8 and 9), you will only see a grey frame with nothing in it. When debugging the javascript the attribute is actually updated, and everything seems to be fine, except you can’t see the PDF. Very frustrating. After a bit of googling i found a solution here (it’s not the marked answer). Instead of using <element>.setAttribute(), which should work, you need to modify the outerHTML attribute of the element.

However, this will only work if you already have the attribute present. So either you need to have a default url in your HTML, or you need to set the attribute first, which both is kind of annoying. Putting it all together it might look something like this.

And there you go. Dynamically loading an embedded PDF to a web page, working in IE 8-11 and Chrome, and hopefully other browsers as well.

My main sources/further reading:
http://stackoverflow.com/questions/676705/changing-data-content-on-an-object-tag-in-html
http://stackoverflow.com/questions/1244788/embed-vs-object