display_utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.addLinkAttributes = addLinkAttributes;
  27. exports.getFilenameFromUrl = getFilenameFromUrl;
  28. exports.isFetchSupported = isFetchSupported;
  29. exports.isValidFetchUrl = isValidFetchUrl;
  30. exports.loadScript = loadScript;
  31. exports.deprecated = deprecated;
  32. exports.PDFDateString = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
  33. var _util = require("../shared/util.js");
  34. const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
  35. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  36. const SVG_NS = "http://www.w3.org/2000/svg";
  37. class DOMCanvasFactory {
  38. create(width, height) {
  39. if (width <= 0 || height <= 0) {
  40. throw new Error("Invalid canvas size");
  41. }
  42. const canvas = document.createElement("canvas");
  43. const context = canvas.getContext("2d");
  44. canvas.width = width;
  45. canvas.height = height;
  46. return {
  47. canvas,
  48. context
  49. };
  50. }
  51. reset(canvasAndContext, width, height) {
  52. if (!canvasAndContext.canvas) {
  53. throw new Error("Canvas is not specified");
  54. }
  55. if (width <= 0 || height <= 0) {
  56. throw new Error("Invalid canvas size");
  57. }
  58. canvasAndContext.canvas.width = width;
  59. canvasAndContext.canvas.height = height;
  60. }
  61. destroy(canvasAndContext) {
  62. if (!canvasAndContext.canvas) {
  63. throw new Error("Canvas is not specified");
  64. }
  65. canvasAndContext.canvas.width = 0;
  66. canvasAndContext.canvas.height = 0;
  67. canvasAndContext.canvas = null;
  68. canvasAndContext.context = null;
  69. }
  70. }
  71. exports.DOMCanvasFactory = DOMCanvasFactory;
  72. class DOMCMapReaderFactory {
  73. constructor({
  74. baseUrl = null,
  75. isCompressed = false
  76. }) {
  77. this.baseUrl = baseUrl;
  78. this.isCompressed = isCompressed;
  79. }
  80. async fetch({
  81. name
  82. }) {
  83. if (!this.baseUrl) {
  84. throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
  85. }
  86. if (!name) {
  87. throw new Error("CMap name must be specified.");
  88. }
  89. const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
  90. const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
  91. if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {
  92. return fetch(url).then(async response => {
  93. if (!response.ok) {
  94. throw new Error(response.statusText);
  95. }
  96. let cMapData;
  97. if (this.isCompressed) {
  98. cMapData = new Uint8Array(await response.arrayBuffer());
  99. } else {
  100. cMapData = (0, _util.stringToBytes)(await response.text());
  101. }
  102. return {
  103. cMapData,
  104. compressionType
  105. };
  106. }).catch(reason => {
  107. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
  108. });
  109. }
  110. return new Promise((resolve, reject) => {
  111. const request = new XMLHttpRequest();
  112. request.open("GET", url, true);
  113. if (this.isCompressed) {
  114. request.responseType = "arraybuffer";
  115. }
  116. request.onreadystatechange = () => {
  117. if (request.readyState !== XMLHttpRequest.DONE) {
  118. return;
  119. }
  120. if (request.status === 200 || request.status === 0) {
  121. let cMapData;
  122. if (this.isCompressed && request.response) {
  123. cMapData = new Uint8Array(request.response);
  124. } else if (!this.isCompressed && request.responseText) {
  125. cMapData = (0, _util.stringToBytes)(request.responseText);
  126. }
  127. if (cMapData) {
  128. resolve({
  129. cMapData,
  130. compressionType
  131. });
  132. return;
  133. }
  134. }
  135. reject(new Error(request.statusText));
  136. };
  137. request.send(null);
  138. }).catch(reason => {
  139. throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
  140. });
  141. }
  142. }
  143. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  144. class DOMSVGFactory {
  145. create(width, height) {
  146. (0, _util.assert)(width > 0 && height > 0, "Invalid SVG dimensions");
  147. const svg = document.createElementNS(SVG_NS, "svg:svg");
  148. svg.setAttribute("version", "1.1");
  149. svg.setAttribute("width", width + "px");
  150. svg.setAttribute("height", height + "px");
  151. svg.setAttribute("preserveAspectRatio", "none");
  152. svg.setAttribute("viewBox", "0 0 " + width + " " + height);
  153. return svg;
  154. }
  155. createElement(type) {
  156. (0, _util.assert)(typeof type === "string", "Invalid SVG element type");
  157. return document.createElementNS(SVG_NS, type);
  158. }
  159. }
  160. exports.DOMSVGFactory = DOMSVGFactory;
  161. class PageViewport {
  162. constructor({
  163. viewBox,
  164. scale,
  165. rotation,
  166. offsetX = 0,
  167. offsetY = 0,
  168. dontFlip = false
  169. }) {
  170. this.viewBox = viewBox;
  171. this.scale = scale;
  172. this.rotation = rotation;
  173. this.offsetX = offsetX;
  174. this.offsetY = offsetY;
  175. const centerX = (viewBox[2] + viewBox[0]) / 2;
  176. const centerY = (viewBox[3] + viewBox[1]) / 2;
  177. let rotateA, rotateB, rotateC, rotateD;
  178. rotation = rotation % 360;
  179. rotation = rotation < 0 ? rotation + 360 : rotation;
  180. switch (rotation) {
  181. case 180:
  182. rotateA = -1;
  183. rotateB = 0;
  184. rotateC = 0;
  185. rotateD = 1;
  186. break;
  187. case 90:
  188. rotateA = 0;
  189. rotateB = 1;
  190. rotateC = 1;
  191. rotateD = 0;
  192. break;
  193. case 270:
  194. rotateA = 0;
  195. rotateB = -1;
  196. rotateC = -1;
  197. rotateD = 0;
  198. break;
  199. case 0:
  200. rotateA = 1;
  201. rotateB = 0;
  202. rotateC = 0;
  203. rotateD = -1;
  204. break;
  205. default:
  206. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  207. }
  208. if (dontFlip) {
  209. rotateC = -rotateC;
  210. rotateD = -rotateD;
  211. }
  212. let offsetCanvasX, offsetCanvasY;
  213. let width, height;
  214. if (rotateA === 0) {
  215. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  216. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  217. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  218. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  219. } else {
  220. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  221. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  222. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  223. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  224. }
  225. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  226. this.width = width;
  227. this.height = height;
  228. }
  229. clone({
  230. scale = this.scale,
  231. rotation = this.rotation,
  232. offsetX = this.offsetX,
  233. offsetY = this.offsetY,
  234. dontFlip = false
  235. } = {}) {
  236. return new PageViewport({
  237. viewBox: this.viewBox.slice(),
  238. scale,
  239. rotation,
  240. offsetX,
  241. offsetY,
  242. dontFlip
  243. });
  244. }
  245. convertToViewportPoint(x, y) {
  246. return _util.Util.applyTransform([x, y], this.transform);
  247. }
  248. convertToViewportRectangle(rect) {
  249. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  250. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  251. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  252. }
  253. convertToPdfPoint(x, y) {
  254. return _util.Util.applyInverseTransform([x, y], this.transform);
  255. }
  256. }
  257. exports.PageViewport = PageViewport;
  258. class RenderingCancelledException extends _util.BaseException {
  259. constructor(msg, type) {
  260. super(msg);
  261. this.type = type;
  262. }
  263. }
  264. exports.RenderingCancelledException = RenderingCancelledException;
  265. const LinkTarget = {
  266. NONE: 0,
  267. SELF: 1,
  268. BLANK: 2,
  269. PARENT: 3,
  270. TOP: 4
  271. };
  272. exports.LinkTarget = LinkTarget;
  273. function addLinkAttributes(link, {
  274. url,
  275. target,
  276. rel,
  277. enabled = true
  278. } = {}) {
  279. (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
  280. const urlNullRemoved = (0, _util.removeNullCharacters)(url);
  281. if (enabled) {
  282. link.href = link.title = urlNullRemoved;
  283. } else {
  284. link.href = "";
  285. link.title = `Disabled: ${urlNullRemoved}`;
  286. link.onclick = () => {
  287. return false;
  288. };
  289. }
  290. let targetStr = "";
  291. switch (target) {
  292. case LinkTarget.NONE:
  293. break;
  294. case LinkTarget.SELF:
  295. targetStr = "_self";
  296. break;
  297. case LinkTarget.BLANK:
  298. targetStr = "_blank";
  299. break;
  300. case LinkTarget.PARENT:
  301. targetStr = "_parent";
  302. break;
  303. case LinkTarget.TOP:
  304. targetStr = "_top";
  305. break;
  306. }
  307. link.target = targetStr;
  308. link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
  309. }
  310. function getFilenameFromUrl(url) {
  311. const anchor = url.indexOf("#");
  312. const query = url.indexOf("?");
  313. const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  314. return url.substring(url.lastIndexOf("/", end) + 1, end);
  315. }
  316. class StatTimer {
  317. constructor() {
  318. this.started = Object.create(null);
  319. this.times = [];
  320. }
  321. time(name) {
  322. if (name in this.started) {
  323. (0, _util.warn)(`Timer is already running for ${name}`);
  324. }
  325. this.started[name] = Date.now();
  326. }
  327. timeEnd(name) {
  328. if (!(name in this.started)) {
  329. (0, _util.warn)(`Timer has not been started for ${name}`);
  330. }
  331. this.times.push({
  332. name,
  333. start: this.started[name],
  334. end: Date.now()
  335. });
  336. delete this.started[name];
  337. }
  338. toString() {
  339. const outBuf = [];
  340. let longest = 0;
  341. for (const time of this.times) {
  342. const name = time.name;
  343. if (name.length > longest) {
  344. longest = name.length;
  345. }
  346. }
  347. for (const time of this.times) {
  348. const duration = time.end - time.start;
  349. outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
  350. }
  351. return outBuf.join("");
  352. }
  353. }
  354. exports.StatTimer = StatTimer;
  355. function isFetchSupported() {
  356. return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype && typeof ReadableStream !== "undefined";
  357. }
  358. function isValidFetchUrl(url, baseUrl) {
  359. try {
  360. const {
  361. protocol
  362. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  363. return protocol === "http:" || protocol === "https:";
  364. } catch (ex) {
  365. return false;
  366. }
  367. }
  368. function loadScript(src) {
  369. return new Promise((resolve, reject) => {
  370. const script = document.createElement("script");
  371. script.src = src;
  372. script.onload = resolve;
  373. script.onerror = function () {
  374. reject(new Error(`Cannot load script at: ${script.src}`));
  375. };
  376. (document.head || document.documentElement).appendChild(script);
  377. });
  378. }
  379. function deprecated(details) {
  380. console.log("Deprecated API usage: " + details);
  381. }
  382. let pdfDateStringRegex;
  383. class PDFDateString {
  384. static toDateObject(input) {
  385. if (!input || !(0, _util.isString)(input)) {
  386. return null;
  387. }
  388. if (!pdfDateStringRegex) {
  389. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  390. }
  391. const matches = pdfDateStringRegex.exec(input);
  392. if (!matches) {
  393. return null;
  394. }
  395. const year = parseInt(matches[1], 10);
  396. let month = parseInt(matches[2], 10);
  397. month = month >= 1 && month <= 12 ? month - 1 : 0;
  398. let day = parseInt(matches[3], 10);
  399. day = day >= 1 && day <= 31 ? day : 1;
  400. let hour = parseInt(matches[4], 10);
  401. hour = hour >= 0 && hour <= 23 ? hour : 0;
  402. let minute = parseInt(matches[5], 10);
  403. minute = minute >= 0 && minute <= 59 ? minute : 0;
  404. let second = parseInt(matches[6], 10);
  405. second = second >= 0 && second <= 59 ? second : 0;
  406. const universalTimeRelation = matches[7] || "Z";
  407. let offsetHour = parseInt(matches[8], 10);
  408. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  409. let offsetMinute = parseInt(matches[9], 10) || 0;
  410. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  411. if (universalTimeRelation === "-") {
  412. hour += offsetHour;
  413. minute += offsetMinute;
  414. } else if (universalTimeRelation === "+") {
  415. hour -= offsetHour;
  416. minute -= offsetMinute;
  417. }
  418. return new Date(Date.UTC(year, month, day, hour, minute, second));
  419. }
  420. }
  421. exports.PDFDateString = PDFDateString;