pdfobject.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /**
  2. * PDFObject v2.2.8
  3. * https://github.com/pipwerks/PDFObject
  4. * @license
  5. * Copyright (c) 2008-2022 Philip Hutchison
  6. * MIT-style license: http://pipwerks.mit-license.org/
  7. * UMD module pattern from https://github.com/umdjs/umd/blob/master/templates/returnExports.js
  8. */
  9. (function (root, factory) {
  10. if (typeof define === "function" && define.amd) {
  11. // AMD. Register as an anonymous module.
  12. define([], factory);
  13. } else if (typeof module === "object" && module.exports) {
  14. // Node. Does not work with strict CommonJS, but
  15. // only CommonJS-like environments that support module.exports,
  16. // like Node.
  17. module.exports = factory();
  18. } else {
  19. // Browser globals (root is window)
  20. root.PDFObject = factory();
  21. }
  22. }(this, function () {
  23. "use strict";
  24. //PDFObject is designed for client-side (browsers), not server-side (node)
  25. //Will choke on undefined navigator and window vars when run on server
  26. //Return boolean false and exit function when running server-side
  27. if( typeof window === "undefined" ||
  28. window.navigator === undefined ||
  29. window.navigator.userAgent === undefined ||
  30. window.navigator.mimeTypes === undefined){
  31. return false;
  32. }
  33. let pdfobjectversion = "2.2.8";
  34. let nav = window.navigator;
  35. let ua = window.navigator.userAgent;
  36. //Time to jump through hoops -- browser vendors do not make it easy to detect PDF support.
  37. /*
  38. IE11 still uses ActiveX for Adobe Reader, but IE 11 doesn't expose window.ActiveXObject the same way
  39. previous versions of IE did. window.ActiveXObject will evaluate to false in IE 11, but "ActiveXObject"
  40. in window evaluates to true.
  41. MS Edge does not support ActiveX so this test will evaluate false
  42. */
  43. let isIE = ("ActiveXObject" in window);
  44. /*
  45. There is a coincidental correlation between implementation of window.promises and native PDF support in desktop browsers
  46. We use this to assume if the browser supports promises it supports embedded PDFs
  47. Is this fragile? Sort of. But browser vendors removed mimetype detection, so we're left to improvise
  48. */
  49. let isModernBrowser = (window.Promise !== undefined);
  50. //Older browsers still expose the mimeType
  51. let supportsPdfMimeType = (nav.mimeTypes["application/pdf"] !== undefined);
  52. //Safari on iPadOS doesn't report as 'mobile' when requesting desktop site, yet still fails to embed PDFs
  53. let isSafariIOSDesktopMode = ( nav.platform !== undefined &&
  54. nav.platform === "MacIntel" &&
  55. nav.maxTouchPoints !== undefined &&
  56. nav.maxTouchPoints > 1 );
  57. //Quick test for mobile devices.
  58. let isMobileDevice = (isSafariIOSDesktopMode || /Mobi|Tablet|Android|iPad|iPhone/.test(ua));
  59. //Safari desktop requires special handling
  60. let isSafariDesktop = ( !isMobileDevice &&
  61. nav.vendor !== undefined &&
  62. /Apple/.test(nav.vendor) &&
  63. /Safari/.test(ua) );
  64. //Firefox started shipping PDF.js in Firefox 19. If this is Firefox 19 or greater, assume PDF.js is available
  65. let isFirefoxWithPDFJS = (!isMobileDevice && /irefox/.test(ua) && ua.split("rv:").length > 1) ? (parseInt(ua.split("rv:")[1].split(".")[0], 10) > 18) : false;
  66. /* ----------------------------------------------------
  67. Supporting functions
  68. ---------------------------------------------------- */
  69. let createAXO = function (type){
  70. var ax;
  71. try {
  72. ax = new ActiveXObject(type);
  73. } catch (e) {
  74. ax = null; //ensure ax remains null
  75. }
  76. return ax;
  77. };
  78. //If either ActiveX support for "AcroPDF.PDF" or "PDF.PdfCtrl" are found, return true
  79. //Constructed as a method (not a prop) to avoid unneccesarry overhead -- will only be evaluated if needed
  80. let supportsPdfActiveX = function (){ return !!(createAXO("AcroPDF.PDF") || createAXO("PDF.PdfCtrl")); };
  81. //Determines whether PDF support is available
  82. let supportsPDFs = (
  83. //As of Sept 2020 no mobile browsers properly support PDF embeds
  84. !isMobileDevice && (
  85. //We're moving into the age of MIME-less browsers. They mostly all support PDF rendering without plugins.
  86. isModernBrowser ||
  87. //Modern versions of Firefox come bundled with PDFJS
  88. isFirefoxWithPDFJS ||
  89. //Browsers that still support the original MIME type check
  90. supportsPdfMimeType ||
  91. //Pity the poor souls still using IE
  92. (isIE && supportsPdfActiveX())
  93. )
  94. );
  95. //Create a fragment identifier for using PDF Open parameters when embedding PDF
  96. let buildURLFragmentString = function(pdfParams){
  97. let string = "";
  98. let prop;
  99. if(pdfParams){
  100. for (prop in pdfParams) {
  101. if (pdfParams.hasOwnProperty(prop)) {
  102. string += encodeURIComponent(prop) + "=" + encodeURIComponent(pdfParams[prop]) + "&";
  103. }
  104. }
  105. //The string will be empty if no PDF Params found
  106. if(string){
  107. string = "#" + string;
  108. //Remove last ampersand
  109. string = string.slice(0, string.length - 1);
  110. }
  111. }
  112. return string;
  113. };
  114. let embedError = function (msg, suppressConsole){
  115. if(!suppressConsole){
  116. console.log("[PDFObject] " + msg);
  117. }
  118. return false;
  119. };
  120. let emptyNodeContents = function (node){
  121. while(node.firstChild){
  122. node.removeChild(node.firstChild);
  123. }
  124. };
  125. let getTargetElement = function (targetSelector){
  126. //Default to body for full-browser PDF
  127. let targetNode = document.body;
  128. //If a targetSelector is specified, check to see whether
  129. //it's passing a selector, jQuery object, or an HTML element
  130. if(typeof targetSelector === "string"){
  131. //Is CSS selector
  132. targetNode = document.querySelector(targetSelector);
  133. } else if (window.jQuery !== undefined && targetSelector instanceof jQuery && targetSelector.length) {
  134. //Is jQuery element. Extract HTML node
  135. targetNode = targetSelector.get(0);
  136. } else if (targetSelector.nodeType !== undefined && targetSelector.nodeType === 1){
  137. //Is HTML element
  138. targetNode = targetSelector;
  139. }
  140. return targetNode;
  141. };
  142. let generatePDFObjectMarkup = function (embedType, targetNode, url, pdfOpenFragment, width, height, id, title, omitInlineStyles, PDFJS_URL){
  143. //Ensure target element is empty first
  144. emptyNodeContents(targetNode);
  145. let source = url;
  146. if(embedType === "pdfjs"){
  147. //If PDFJS_URL already contains a ?, assume querystring is in place, and use an ampersand to append PDFJS's file parameter
  148. let connector = (PDFJS_URL.indexOf("?") !== -1) ? "&" : "?";
  149. source = PDFJS_URL + connector + "file=" + encodeURIComponent(url) + pdfOpenFragment;
  150. }
  151. let el_type = (embedType === "pdfjs" || embedType === "iframe") ? "iframe" : "embed";
  152. let el = document.createElement(el_type);
  153. el.className = "pdfobject";
  154. el.type = "application/pdf";
  155. el.title = title;
  156. el.src = source;
  157. if(id){
  158. el.id = id;
  159. }
  160. if(el_type === "iframe"){
  161. el.allow = "fullscreen";
  162. el.frameborder = "0";
  163. }
  164. if(!omitInlineStyles){
  165. let style = (el_type === "embed") ? "overflow: auto;" : "border: none;";
  166. if(targetNode !== document.body){
  167. //assign width and height to target node
  168. style += "width: " + width + "; height: " + height + ";";
  169. } else {
  170. //this is a full-page embed, use CSS to fill the viewport
  171. style += "position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%;";
  172. }
  173. el.style.cssText = style;
  174. }
  175. targetNode.classList.add("pdfobject-container");
  176. targetNode.appendChild(el);
  177. return targetNode.getElementsByTagName(el_type)[0];
  178. };
  179. let embed = function(url, targetSelector, options){
  180. //If targetSelector is not defined, convert to boolean
  181. let selector = targetSelector || false;
  182. //Ensure options object is not undefined -- enables easier error checking below
  183. let opt = options || {};
  184. //Get passed options, or set reasonable defaults
  185. let id = (typeof opt.id === "string") ? opt.id : "";
  186. let page = opt.page || false;
  187. let pdfOpenParams = opt.pdfOpenParams || {};
  188. let fallbackLink = (typeof opt.fallbackLink === "string" || typeof opt.fallbackLink === "boolean") ? opt.fallbackLink : true;
  189. let width = opt.width || "100%";
  190. let height = opt.height || "100%";
  191. let title = opt.title || "Embedded PDF";
  192. let assumptionMode = (typeof opt.assumptionMode === "boolean") ? opt.assumptionMode : true;
  193. let forcePDFJS = (typeof opt.forcePDFJS === "boolean") ? opt.forcePDFJS : false;
  194. let supportRedirect = (typeof opt.supportRedirect === "boolean") ? opt.supportRedirect : false;
  195. let omitInlineStyles = (typeof opt.omitInlineStyles === "boolean") ? opt.omitInlineStyles : false;
  196. let suppressConsole = (typeof opt.suppressConsole === "boolean") ? opt.suppressConsole : false;
  197. let forceIframe = (typeof opt.forceIframe === "boolean") ? opt.forceIframe : false;
  198. let PDFJS_URL = opt.PDFJS_URL || false;
  199. let targetNode = getTargetElement(selector);
  200. let fallbackHTML = "";
  201. let pdfOpenFragment = "";
  202. let fallbackHTML_default = "<p>This browser does not support inline PDFs. Please download the PDF to view it: <a href='[url]'>Download PDF</a></p>";
  203. //Ensure URL is available. If not, exit now.
  204. if(typeof url !== "string"){ return embedError("URL is not valid", suppressConsole); }
  205. //If target element is specified but is not valid, exit without doing anything
  206. if(!targetNode){ return embedError("Target element cannot be determined", suppressConsole); }
  207. //page option overrides pdfOpenParams, if found
  208. if(page){ pdfOpenParams.page = page; }
  209. //Stringify optional Adobe params for opening document (as fragment identifier)
  210. pdfOpenFragment = buildURLFragmentString(pdfOpenParams);
  211. // --== Do the dance: Embed attempt #1 ==--
  212. //If the forcePDFJS option is invoked, skip everything else and embed as directed
  213. if(forcePDFJS && PDFJS_URL){
  214. return generatePDFObjectMarkup("pdfjs", targetNode, url, pdfOpenFragment, width, height, id, title, omitInlineStyles, PDFJS_URL);
  215. }
  216. // --== Embed attempt #2 ==--
  217. //Embed PDF if traditional support is provided, or if this developer is willing to roll with assumption
  218. //that modern desktop (not mobile) browsers natively support PDFs
  219. if(supportsPDFs || (assumptionMode && !isMobileDevice)){
  220. //Should we use <embed> or <iframe>? In most cases <embed>.
  221. //Allow developer to force <iframe>, if desired
  222. //There is an edge case where Safari does not respect 302 redirect requests for PDF files when using <embed> element.
  223. //Redirect appears to work fine when using <iframe> instead of <embed> (Addresses issue #210)
  224. //Forcing Safari desktop to use iframe due to freezing bug in macOS 11 (Big Sur)
  225. let embedtype = (forceIframe || supportRedirect || isSafariDesktop) ? "iframe" : "embed";
  226. return generatePDFObjectMarkup(embedtype, targetNode, url, pdfOpenFragment, width, height, id, title, omitInlineStyles);
  227. }
  228. // --== Embed attempt #3 ==--
  229. //If everything else has failed and a PDFJS fallback is provided, try to use it
  230. if(PDFJS_URL){
  231. return generatePDFObjectMarkup("pdfjs", targetNode, url, pdfOpenFragment, width, height, id, title, omitInlineStyles, PDFJS_URL);
  232. }
  233. // --== PDF embed not supported! Use fallback ==--
  234. //Display the fallback link if available
  235. if(fallbackLink){
  236. fallbackHTML = (typeof fallbackLink === "string") ? fallbackLink : fallbackHTML_default;
  237. targetNode.innerHTML = fallbackHTML.replace(/\[url\]/g, url);
  238. }
  239. return embedError("This browser does not support embedded PDFs", suppressConsole);
  240. };
  241. return {
  242. embed: function (a,b,c){ return embed(a,b,c); },
  243. pdfobjectversion: (function () { return pdfobjectversion; })(),
  244. supportsPDFs: (function (){ return supportsPDFs; })()
  245. };
  246. }));