jquery在线预览PDF文件,打开PDF文件

发布于2017-03-26  2,810次阅读


最主要的是使用到了一个jquery的插件jquery.media.js,使用这个插件就很容易实现了。

核心代码

 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  4. <title>Online View PDF</title>
  5. <script type="text/javascript" src="http://sources.ikeepstudying.com/js/jquery-1.8.3.min.js"></script>
  6. <script type="text/javascript" src="jquery.media.js"></script>
  7. <script type="text/javascript">
  8.     $(function() {
  9.         $('a.media').media({width:800, height:600});
  10.     });
  11. </script>
  12. </head>
  13. <body>
  14. <a class="media" href="guice.pdf">PDF File</a>
  15. </body>
  16. </html>

查看预览:http://sources.ikeepstudying.com/jquery.media/pdf.php

使用jquery.media.js就可以直接把一个连接到pdf文件的链接打开,满足了需求。

jquery.media.js

Js代码
  1. /*
  2.  * jQuery Media Plugin for converting elements into rich media content.
  3.  *
  4.  * Examples and documentation at: http://malsup.com/jquery/media/
  5.  * Copyright (c) 2007-2010 M. Alsup
  6.  * Dual licensed under the MIT and GPL licenses:
  7.  * http://www.opensource.org/licenses/mit-license.php
  8.  * http://www.gnu.org/licenses/gpl.html
  9.  *
  10.  * @author: M. Alsup
  11.  * @version: 0.99 (05-JUN-2013)
  12.  * @requires jQuery v1.1.2 or later
  13.  * $Id: jquery.media.js 2460 2007-07-23 02:53:15Z malsup $
  14.  *
  15.  * Supported Media Players:
  16.  *  - Flash
  17.  *  - Quicktime
  18.  *  - Real Player
  19.  *  - Silverlight
  20.  *  - Windows Media Player
  21.  *  - iframe
  22.  *
  23.  * Supported Media Formats:
  24.  *   Any types supported by the above players, such as:
  25.  *   Video: asf, avi, flv, mov, mpg, mpeg, mp4, qt, smil, swf, wmv, 3g2, 3gp
  26.  *   Audio: aif, aac, au, gsm, mid, midi, mov, mp3, m4a, snd, rm, wav, wma
  27.  *   Other: bmp, html, pdf, psd, qif, qtif, qti, tif, tiff, xaml
  28.  *
  29.  * Thanks to Mark Hicken and Brent Pedersen for helping me debug this on the Mac!
  30.  * Thanks to Dan Rossi for numerous bug reports and code bits!
  31.  * Thanks to Skye Giordano for several great suggestions!
  32.  * Thanks to Richard Connamacher for excellent improvements to the non-IE behavior!
  33.  */
  34. /*global SWFObject alert Sys */
  35. /*jshint forin:false */
  36. ;(function($) {
  37. "use strict";
  38. var mode = document.documentMode || 0;
  39. var msie = /MSIE/.test(navigator.userAgent);
  40. var lameIE = msie && (/MSIE (6|7|8)\.0/.test(navigator.userAgent) || mode < 9);
  41. /**
  42.  * Chainable method for converting elements into rich media.
  43.  *
  44.  * @param options
  45.  * @param callback fn invoked for each matched element before conversion
  46.  * @param callback fn invoked for each matched element after conversion
  47.  */
  48. $.fn.media = function(options, f1, f2) {
  49.     if (options == 'undo') {
  50.         return this.each(function() {
  51.             var $this = $(this);
  52.             var html = $this.data('media.origHTML');
  53.             if (html)
  54.                 $this.replaceWith(html);
  55.         });
  56.     }
  57.     return this.each(function() {
  58.         if (typeof options == 'function') {
  59.             f2 = f1;
  60.             f1 = options;
  61.             options = {};
  62.         }
  63.         var o = getSettings(this, options);
  64.         // pre-conversion callback, passes original element and fully populated options
  65.         if (typeof f1 == 'function') f1(this, o);
  66.         var r = getTypesRegExp();
  67.         var m = r.exec(o.src.toLowerCase()) || [''];
  68.         var fn;
  69.         if (o.type)
  70.             m[0] = o.type;
  71.         else
  72.             m.shift();
  73.         for (var i=0; i < m.length; i++) {
  74.             fn = m[i].toLowerCase();
  75.             if (isDigit(fn[0])) fn = 'fn' + fn; // fns can't begin with numbers
  76.             if (!$.fn.media[fn])
  77.                 continue;  // unrecognized media type
  78.             // normalize autoplay settings
  79.             var player = $.fn.media[fn+'_player'];
  80.             if (!o.params) o.params = {};
  81.             if (player) {
  82.                 var num = player.autoplayAttr == 'autostart';
  83.                 o.params[player.autoplayAttr || 'autoplay'] = num ? (o.autoplay ? 1 : 0) : o.autoplay ? true : false;
  84.             }
  85.             var $div = $.fn.media[fn](this, o);
  86.             $div.css('backgroundColor', o.bgColor).width(o.width);
  87.             if (o.canUndo) {
  88.                 var $temp = $('<div></div>').append(this);
  89.                 $div.data('media.origHTML', $temp.html()); // store original markup
  90.             }
  91.             // post-conversion callback, passes original element, new div element and fully populated options
  92.             if (typeof f2 == 'function') f2(this, $div[0], o, player.name);
  93.             break;
  94.         }
  95.     });
  96. };
  97. /**
  98.  * Non-chainable method for adding or changing file format / player mapping
  99.  * @name mapFormat
  100.  * @param String format File format extension (ie: mov, wav, mp3)
  101.  * @param String player Player name to use for the format (one of: flash, quicktime, realplayer, winmedia, silverlight or iframe
  102.  */
  103. $.fn.media.mapFormat = function(format, player) {
  104.     if (!format || !player || !$.fn.media.defaults.players[player]) return// invalid
  105.     format = format.toLowerCase();
  106.     if (isDigit(format[0])) format = 'fn' + format;
  107.     $.fn.media[format] = $.fn.media[player];
  108.     $.fn.media[format+'_player'] = $.fn.media.defaults.players[player];
  109. };
  110. // global defautls; override as needed
  111. $.fn.media.defaults = {
  112.     standards:  true,       // use object tags only (no embeds for non-IE browsers)
  113.     canUndo:    true,       // tells plugin to store the original markup so it can be reverted via: $(sel).mediaUndo()
  114.     width:      400,
  115.     height:     400,
  116.     autoplay:   0,          // normalized cross-player setting
  117.     bgColor:    '#ffffff',  // background color
  118.     params:     { wmode: 'transparent'},    // added to object element as param elements; added to embed element as attrs
  119.     attrs:      {},         // added to object and embed elements as attrs
  120.     flvKeyName: 'file',     // key used for object src param (thanks to Andrea Ercolino)
  121.     flashvars:  {},         // added to flash content as flashvars param/attr
  122.     flashVersion:   '7',    // required flash version
  123.     expressInstaller: null// src for express installer
  124.     // default flash video and mp3 player (@see: http://jeroenwijering.com/?item=Flash_Media_Player)
  125.     flvPlayer:   'mediaplayer.swf',
  126.     mp3Player:   'mediaplayer.swf',
  127.     // @see http://msdn2.microsoft.com/en-us/library/bb412401.aspx
  128.     silverlight: {
  129.         inplaceInstallPrompt: 'true'// display in-place install prompt?
  130.         isWindowless:         'true'// windowless mode (false for wrapping markup)
  131.         framerate:            '24',   // maximum framerate
  132.         version:              '0.9',  // Silverlight version
  133.         onError:              null,   // onError callback
  134.         onLoad:               null,   // onLoad callback
  135.         initParams:           null,   // object init params
  136.         userContext:          null    // callback arg passed to the load callback
  137.     }
  138. };
  139. // Media Players; think twice before overriding
  140. $.fn.media.defaults.players = {
  141.     flash: {
  142.         name:        'flash',
  143.         title:       'Flash',
  144.         types:       'flv,mp3,swf',
  145.         mimetype:    'application/x-shockwave-flash',
  146.         pluginspage: 'http://www.adobe.com/go/getflashplayer',
  147.         ieAttrs: {
  148.             classid:  'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
  149.             type:     'application/x-oleobject',
  150.             codebase: 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + $.fn.media.defaults.flashVersion
  151.         }
  152.     },
  153.     quicktime: {
  154.         name:        'quicktime',
  155.         title:       'QuickTime',
  156.         mimetype:    'video/quicktime',
  157.         pluginspage: 'http://www.apple.com/quicktime/download/',
  158.         types:       'aif,aiff,aac,au,bmp,gsm,mov,mid,midi,mpg,mpeg,mp4,m4a,psd,qt,qtif,qif,qti,snd,tif,tiff,wav,3g2,3gp',
  159.         ieAttrs: {
  160.             classid:  'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
  161.             codebase: 'http://www.apple.com/qtactivex/qtplugin.cab'
  162.         }
  163.     },
  164.     realplayer: {
  165.         name:         'real',
  166.         title:        'RealPlayer',
  167.         types:        'ra,ram,rm,rpm,rv,smi,smil',
  168.         mimetype:     'audio/x-pn-realaudio-plugin',
  169.         pluginspage:  'http://www.real.com/player/',
  170.         autoplayAttr: 'autostart',
  171.         ieAttrs: {
  172.             classid: 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'
  173.         }
  174.     },
  175.     winmedia: {
  176.         name:         'winmedia',
  177.         title:        'Windows Media',
  178.         types:        'asx,asf,avi,wma,wmv',
  179.         mimetype:     isFirefoxWMPPluginInstalled() ? 'application/x-ms-wmp' : 'application/x-mplayer2',
  180.         pluginspage:  'http://www.microsoft.com/Windows/MediaPlayer/',
  181.         autoplayAttr: 'autostart',
  182.         oUrl:         'url',
  183.         ieAttrs: {
  184.             classid:  'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6',
  185.             type:     'application/x-oleobject'
  186.         }
  187.     },
  188.     // special cases
  189.     img: {
  190.         name:  'img',
  191.         title: 'Image',
  192.         types: 'gif,png,jpg'
  193.     },
  194.     iframe: {
  195.         name:  'iframe',
  196.         types: 'html,pdf'
  197.     },
  198.     silverlight: {
  199.         name:  'silverlight',
  200.         types: 'xaml'
  201.     }
  202. };
  203. //
  204. //  everything below here is private
  205. //
  206. // detection script for FF WMP plugin (http://www.therossman.org/experiments/wmp_play.html)
  207. // (hat tip to Mark Ross for this script)
  208. function isFirefoxWMPPluginInstalled() {
  209.     var plugs = navigator.plugins || [];
  210.     for (var i = 0; i < plugs.length; i++) {
  211.         var plugin = plugs[i];
  212.         if (plugin['filename'] == 'np-mswmp.dll')
  213.             return true;
  214.     }
  215.     return false;
  216. }
  217. var counter = 1;
  218. for (var player in $.fn.media.defaults.players) {
  219.     var types = $.fn.media.defaults.players[player].types;
  220.     $.each(types.split(','), function(i,o) {
  221.         if (isDigit(o[0])) o = 'fn' + o;
  222.         $.fn.media[o] = $.fn.media[player] = getGenerator(player);
  223.         $.fn.media[o+'_player'] = $.fn.media.defaults.players[player];
  224.     });
  225. }
  226. function getTypesRegExp() {
  227.     var types = '';
  228.     for (var player in $.fn.media.defaults.players) {
  229.         if (types.length) types += ',';
  230.         types += $.fn.media.defaults.players[player].types;
  231.     }
  232.     return new RegExp('\\.(' + types.replace(/,/ig,'|') + ')\\b');
  233. }
  234. function getGenerator(player) {
  235.     return function(el, options) {
  236.         return generate(el, options, player);
  237.     };
  238. }
  239. function isDigit(c) {
  240.     return '0123456789'.indexOf(c) > -1;
  241. }
  242. // flatten all possible options: global defaults, meta, option obj
  243. function getSettings(el, options) {
  244.     options = options || {};
  245.     var a, n;
  246.     var $el = $(el);
  247.     var cls = el.className || '';
  248.     // support metadata plugin (v1.0 and v2.0)
  249.     var meta = $.metadata ? $el.metadata() : $.meta ? $el.data() : {};
  250.     meta = meta || {};
  251.     var w = meta.width  || parseInt(((cls.match(/\bw:(\d+)/)||[])[1]||0),10) || parseInt(((cls.match(/\bwidth:(\d+)/)||[])[1]||0),10);
  252.     var h = meta.height || parseInt(((cls.match(/\bh:(\d+)/)||[])[1]||0),10) || parseInt(((cls.match(/\bheight:(\d+)/)||[])[1]||0),10);
  253.     if (w) meta.width = w;
  254.     if (h) meta.height = h;
  255.     if (cls) meta.cls = cls;
  256.     // crank html5 style data attributes
  257.     var dataName = 'data-';
  258.     for (var i=0; i < el.attributes.length; i++) {
  259.         a = el.attributes[i], n = $.trim(a.name);
  260.         var index = n.indexOf(dataName);
  261.         if (index === 0) {
  262.             n = n.substring(dataName.length);
  263.             meta[n] = a.value;
  264.         }
  265.     }
  266.     a = $.fn.media.defaults;
  267.     var b = options;
  268.     var c = meta;
  269.     var p = { params: { bgColor: options.bgColor || $.fn.media.defaults.bgColor } };
  270.     var opts = $.extend({}, a, b, c);
  271.     $.each(['attrs','params','flashvars','silverlight'], function(i,o) {
  272.         opts[o] = $.extend({}, p[o] || {}, a[o] || {}, b[o] || {}, c[o] || {});
  273.     });
  274.     if (typeof opts.caption == 'undefined') opts.caption = $el.text();
  275.     // make sure we have a source!
  276.     opts.src = opts.src || $el.attr('href') || $el.attr('src') || 'unknown';
  277.     return opts;
  278. }
  279. //
  280. //  Flash Player
  281. //
  282. // generate flash using SWFObject library if possible
  283. $.fn.media.swf = function(el, opts) {
  284.     var f, p;
  285.     if (!window.SWFObject && !window.swfobject) {
  286.         // roll our own
  287.         if (opts.flashvars) {
  288.             var a = [];
  289.             for (f in opts.flashvars)
  290.                 a.push(f + '=' + opts.flashvars[f]);
  291.             if (!opts.params) opts.params = {};
  292.             opts.params.flashvars = a.join('&');
  293.         }
  294.         return generate(el, opts, 'flash');
  295.     }
  296.     var id = el.id ? (' id="'+el.id+'"') : '';
  297.     var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
  298.     var $div = $('<div' + id + cls + '>');
  299.     // swfobject v2+
  300.     if (window.swfobject) {
  301.         $(el).after($div).appendTo($div);
  302.         if (!el.id) el.id = 'movie_player_' + counter++;
  303.         // replace el with swfobject content
  304.         window.swfobject.embedSWF(opts.src, el.id, opts.width, opts.height, opts.flashVersion,
  305.             opts.expressInstaller, opts.flashvars, opts.params, opts.attrs);
  306.     }
  307.     // swfobject < v2
  308.     else {
  309.         $(el).after($div).remove();
  310.         var so = new SWFObject(opts.src, 'movie_player_' + counter++, opts.width, opts.height, opts.flashVersion, opts.bgColor);
  311.         if (opts.expressInstaller) so.useExpressInstall(opts.expressInstaller);
  312.         for (p in opts.params)
  313.             if (p != 'bgColor') so.addParam(p, opts.params[p]);
  314.         for (f in opts.flashvars)
  315.             so.addVariable(f, opts.flashvars[f]);
  316.         so.write($div[0]);
  317.     }
  318.     if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
  319.     return $div;
  320. };
  321. // map flv and mp3 files to the swf player by default
  322. $.fn.media.flv = $.fn.media.mp3 = function(el, opts) {
  323.     var src = opts.src;
  324.     var player = /\.mp3\b/i.test(src) ? opts.mp3Player : opts.flvPlayer;
  325.     var key = opts.flvKeyName;
  326.     src = encodeURIComponent(src);
  327.     opts.src = player;
  328.     opts.src = opts.src + '?'+key+'=' + (src);
  329.     var srcObj = {};
  330.     srcObj[key] = src;
  331.     opts.flashvars = $.extend({}, srcObj, opts.flashvars );
  332.     return $.fn.media.swf(el, opts);
  333. };
  334. //
  335. //  Silverlight
  336. //
  337. $.fn.media.xaml = function(el, opts) {
  338.     if (!window.Sys || !window.Sys.Silverlight) {
  339.         if ($.fn.media.xaml.warning) return;
  340.         $.fn.media.xaml.warning = 1;
  341.         alert('You must include the Silverlight.js script.');
  342.         return;
  343.     }
  344.     var props = {
  345.         width: opts.width,
  346.         height: opts.height,
  347.         background: opts.bgColor,
  348.         inplaceInstallPrompt: opts.silverlight.inplaceInstallPrompt,
  349.         isWindowless: opts.silverlight.isWindowless,
  350.         framerate: opts.silverlight.framerate,
  351.         version: opts.silverlight.version
  352.     };
  353.     var events = {
  354.         onError: opts.silverlight.onError,
  355.         onLoad: opts.silverlight.onLoad
  356.     };
  357.     var id1 = el.id ? (' id="'+el.id+'"') : '';
  358.     var id2 = opts.id || 'AG' + counter++;
  359.     // convert element to div
  360.     var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
  361.     var $div = $('<div' + id1 + cls + '>');
  362.     $(el).after($div).remove();
  363.     Sys.Silverlight.createObjectEx({
  364.         source: opts.src,
  365.         initParams: opts.silverlight.initParams,
  366.         userContext: opts.silverlight.userContext,
  367.         id: id2,
  368.         parentElement: $div[0],
  369.         properties: props,
  370.         events: events
  371.     });
  372.     if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
  373.     return $div;
  374. };
  375. //
  376. // generate object/embed markup
  377. //
  378. function generate(el, opts, player) {
  379.     var $el = $(el);
  380.     var o = $.fn.media.defaults.players[player];
  381.     var a, key, v;
  382.     if (player == 'iframe') {
  383.         o = $('<iframe' + ' width="' + opts.width + '" height="' + opts.height + '" >');
  384.         o.attr('src', opts.src);
  385.         o.css('backgroundColor', o.bgColor);
  386.     }
  387.     else if (player == 'img') {
  388.         o = $('<img>');
  389.         o.attr('src', opts.src);
  390.         if (opts.width)
  391.             o.attr('width', opts.width);
  392.         if (opts.height)
  393.             o.attr('height', opts.height);
  394.         o.css('backgroundColor', o.bgColor);
  395.     }
  396.     else if (lameIE) {
  397.         a = ['<object width="' + opts.width + '" height="' + opts.height + '" '];
  398.         for (key in opts.attrs)
  399.             a.push(key + '="'+opts.attrs[key]+'" ');
  400.         for (key in o.ieAttrs || {}) {
  401. v = o.ieAttrs[key];
  402.             if (key == 'codebase' && window.location.protocol == 'https:')
  403.                 v = v.replace('http','https');
  404.             a.push(key + '="'+v+'" ');
  405.         }
  406.         a.push('></ob'+'ject'+'>');
  407.         var p = ['<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">'];
  408.         for (key in opts.params)
  409.             p.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
  410.         o = document.createElement(a.join(''));
  411.         for (var i=0; i < p.length; i++)
  412.             o.appendChild(document.createElement(p[i]));
  413.     }
  414.     else if (opts.standards) {
  415.         // Rewritten to be standards compliant by Richard Connamacher
  416.         a = ['<object type="' + o.mimetype +'" width="' + opts.width + '" height="' + opts.height +'"'];
  417.         if (opts.src) a.push(' data="' + opts.src + '" ');
  418.         if (msie) {
  419.             for (key in o.ieAttrs || {}) {
  420.                 v = o.ieAttrs[key];
  421.                 if (key == 'codebase' && window.location.protocol == 'https:')
  422.                     v = v.replace('http','https');
  423.                 a.push(key + '="'+v+'" ');
  424.             }
  425.         }
  426.         a.push('>');
  427.         a.push('<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">');
  428.         for (key in opts.params) {
  429.             if (key == 'wmode' && player != 'flash'// FF3/Quicktime borks on wmode
  430.                 continue;
  431.             a.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
  432.         }
  433.         // Alternate HTML
  434.         a.push('<div><p><strong>'+o.title+' Required</strong></p><p>'+o.title+' is required to view this media. <a href="'+o.pluginspage+'">Download Here</a>.</p></div>');
  435.         a.push('</ob'+'ject'+'>');
  436.     }
  437.      else {
  438.             a = ['<embed width="' + opts.width + '" height="' + opts.height + '" style="display:block"'];
  439.             if (opts.src) a.push(' src="' + opts.src + '" ');
  440.             for (key in opts.attrs)
  441.                 a.push(key + '="'+opts.attrs[key]+'" ');
  442.             for (key in o.eAttrs || {})
  443.                 a.push(key + '="'+o.eAttrs[key]+'" ');
  444.             for (key in opts.params) {
  445.                 if (key == 'wmode' && player != 'flash'// FF3/Quicktime borks on wmode
  446.                     continue;
  447.                 a.push(key + '="'+opts.params[key]+'" ');
  448.             }
  449.             a.push('></em'+'bed'+'>');
  450.         }
  451.     // convert element to div
  452.     var id = el.id ? (' id="'+el.id+'"') : '';
  453.     var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
  454.     var $div = $('<div' + id + cls + '>');
  455.     $el.after($div).remove();
  456.     if (lameIE || player == 'iframe' || player == 'img')
  457.         $div.append(o);
  458.     else
  459.         $div.html(a.join(''));
  460.     if (opts.caption)
  461.         $('<div>').appendTo($div).html(opts.caption);
  462.     return $div;
  463. }
  464. })(jQuery);

 

转发至 http://justcoding.iteye.com/blog/2163072  如有问题 可以联系站长删除文章


  • 微信或支付宝

道,可道,非常道;名,可名,非常名。