4

I was wondering if anyone knows how to display PDF's in jQuery using Fancybox/Lightbox, etc? I have tried with no success!

green_arrow
  • 1,257
  • 7
  • 21
  • 37
  • 5
    Pretty annoying if you ask me. Some people have configured their browser to download PDFs and open them in an external viewer. For them the lightbox would just show an empty iframe. Besides that, the plural is `PDFs`, not `PDF's`. – ThiefMaster Jan 10 '12 at 13:23
  • 1
    "I have tried with no success!" - You have tried _what_? Can you show some code and describe expected behavior vs. observed behavior? – David Jan 10 '12 at 13:36

1 Answers1

7

For fancybox v1.3.x, having this HTML:

<a class="pdf" href="sample.pdf">open pdf file</a>

use this script:

$(document).ready(function() {
 $(".pdf").click(function() {
  $.fancybox({
   'width': '70%', // or whatever
   'height': '90%',
   'autoDimensions': false,
   'content': '<embed src="'+this.href+'#nameddest=self&page=1&view=FitH,0&zoom=80,0,0" type="application/pdf" height="99%" width="100%" />',
   'onClosed': function() {
     $("#fancybox-inner").empty();
   }
  });
  return false;
 }); // pdf 
}); // ready

Of course, be sure you load jQuery and fancybox js and css files first

Please notice that I set height="99%" within the <embed> tag. If you use HTML5 DCTYPE, it will avoid a double vertical scroll bar. This is because the way HTML5 initializes margins.

For fancybox v2.x: if you are using fancybox v2.x you may use the same script but you don't need the onClosed option, so remove

'onClosed': function() {
 $("#fancybox-inner").empty();
}

from the script and the last trialing comma after the content option.

Also change the autoDimensions word for autoSize .

JFK
  • 40,963
  • 31
  • 133
  • 306