display_utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 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.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
  27. exports.deprecated = deprecated;
  28. exports.getColorValues = getColorValues;
  29. exports.getCurrentTransform = getCurrentTransform;
  30. exports.getCurrentTransformInverse = getCurrentTransformInverse;
  31. exports.getFilenameFromUrl = getFilenameFromUrl;
  32. exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
  33. exports.getRGB = getRGB;
  34. exports.getXfaPageViewport = getXfaPageViewport;
  35. exports.isDataScheme = isDataScheme;
  36. exports.isPdfFile = isPdfFile;
  37. exports.isValidFetchUrl = isValidFetchUrl;
  38. exports.loadScript = loadScript;
  39. exports.setLayerDimensions = setLayerDimensions;
  40. var _base_factory = require("./base_factory.js");
  41. var _util = require("../shared/util.js");
  42. const SVG_NS = "http://www.w3.org/2000/svg";
  43. const AnnotationPrefix = "pdfjs_internal_id_";
  44. exports.AnnotationPrefix = AnnotationPrefix;
  45. class PixelsPerInch {
  46. static CSS = 96.0;
  47. static PDF = 72.0;
  48. static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
  49. }
  50. exports.PixelsPerInch = PixelsPerInch;
  51. class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  52. constructor({
  53. ownerDocument = globalThis.document
  54. } = {}) {
  55. super();
  56. this._document = ownerDocument;
  57. }
  58. _createCanvas(width, height) {
  59. const canvas = this._document.createElement("canvas");
  60. canvas.width = width;
  61. canvas.height = height;
  62. return canvas;
  63. }
  64. }
  65. exports.DOMCanvasFactory = DOMCanvasFactory;
  66. async function fetchData(url, asTypedArray = false) {
  67. if (isValidFetchUrl(url, document.baseURI)) {
  68. const response = await fetch(url);
  69. if (!response.ok) {
  70. throw new Error(response.statusText);
  71. }
  72. return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  73. }
  74. return new Promise((resolve, reject) => {
  75. const request = new XMLHttpRequest();
  76. request.open("GET", url, true);
  77. if (asTypedArray) {
  78. request.responseType = "arraybuffer";
  79. }
  80. request.onreadystatechange = () => {
  81. if (request.readyState !== XMLHttpRequest.DONE) {
  82. return;
  83. }
  84. if (request.status === 200 || request.status === 0) {
  85. let data;
  86. if (asTypedArray && request.response) {
  87. data = new Uint8Array(request.response);
  88. } else if (!asTypedArray && request.responseText) {
  89. data = (0, _util.stringToBytes)(request.responseText);
  90. }
  91. if (data) {
  92. resolve(data);
  93. return;
  94. }
  95. }
  96. reject(new Error(request.statusText));
  97. };
  98. request.send(null);
  99. });
  100. }
  101. class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  102. _fetchData(url, compressionType) {
  103. return fetchData(url, this.isCompressed).then(data => {
  104. return {
  105. cMapData: data,
  106. compressionType
  107. };
  108. });
  109. }
  110. }
  111. exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
  112. class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  113. _fetchData(url) {
  114. return fetchData(url, true);
  115. }
  116. }
  117. exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
  118. class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  119. _createSVG(type) {
  120. return document.createElementNS(SVG_NS, type);
  121. }
  122. }
  123. exports.DOMSVGFactory = DOMSVGFactory;
  124. class PageViewport {
  125. constructor({
  126. viewBox,
  127. scale,
  128. rotation,
  129. offsetX = 0,
  130. offsetY = 0,
  131. dontFlip = false
  132. }) {
  133. this.viewBox = viewBox;
  134. this.scale = scale;
  135. this.rotation = rotation;
  136. this.offsetX = offsetX;
  137. this.offsetY = offsetY;
  138. const centerX = (viewBox[2] + viewBox[0]) / 2;
  139. const centerY = (viewBox[3] + viewBox[1]) / 2;
  140. let rotateA, rotateB, rotateC, rotateD;
  141. rotation %= 360;
  142. if (rotation < 0) {
  143. rotation += 360;
  144. }
  145. switch (rotation) {
  146. case 180:
  147. rotateA = -1;
  148. rotateB = 0;
  149. rotateC = 0;
  150. rotateD = 1;
  151. break;
  152. case 90:
  153. rotateA = 0;
  154. rotateB = 1;
  155. rotateC = 1;
  156. rotateD = 0;
  157. break;
  158. case 270:
  159. rotateA = 0;
  160. rotateB = -1;
  161. rotateC = -1;
  162. rotateD = 0;
  163. break;
  164. case 0:
  165. rotateA = 1;
  166. rotateB = 0;
  167. rotateC = 0;
  168. rotateD = -1;
  169. break;
  170. default:
  171. throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
  172. }
  173. if (dontFlip) {
  174. rotateC = -rotateC;
  175. rotateD = -rotateD;
  176. }
  177. let offsetCanvasX, offsetCanvasY;
  178. let width, height;
  179. if (rotateA === 0) {
  180. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  181. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  182. width = (viewBox[3] - viewBox[1]) * scale;
  183. height = (viewBox[2] - viewBox[0]) * scale;
  184. } else {
  185. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  186. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  187. width = (viewBox[2] - viewBox[0]) * scale;
  188. height = (viewBox[3] - viewBox[1]) * scale;
  189. }
  190. this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
  191. this.width = width;
  192. this.height = height;
  193. }
  194. get rawDims() {
  195. const {
  196. viewBox
  197. } = this;
  198. return (0, _util.shadow)(this, "rawDims", {
  199. pageWidth: viewBox[2] - viewBox[0],
  200. pageHeight: viewBox[3] - viewBox[1],
  201. pageX: viewBox[0],
  202. pageY: viewBox[1]
  203. });
  204. }
  205. clone({
  206. scale = this.scale,
  207. rotation = this.rotation,
  208. offsetX = this.offsetX,
  209. offsetY = this.offsetY,
  210. dontFlip = false
  211. } = {}) {
  212. return new PageViewport({
  213. viewBox: this.viewBox.slice(),
  214. scale,
  215. rotation,
  216. offsetX,
  217. offsetY,
  218. dontFlip
  219. });
  220. }
  221. convertToViewportPoint(x, y) {
  222. return _util.Util.applyTransform([x, y], this.transform);
  223. }
  224. convertToViewportRectangle(rect) {
  225. const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
  226. const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
  227. return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  228. }
  229. convertToPdfPoint(x, y) {
  230. return _util.Util.applyInverseTransform([x, y], this.transform);
  231. }
  232. }
  233. exports.PageViewport = PageViewport;
  234. class RenderingCancelledException extends _util.BaseException {
  235. constructor(msg, type, extraDelay = 0) {
  236. super(msg, "RenderingCancelledException");
  237. this.type = type;
  238. this.extraDelay = extraDelay;
  239. }
  240. }
  241. exports.RenderingCancelledException = RenderingCancelledException;
  242. function isDataScheme(url) {
  243. const ii = url.length;
  244. let i = 0;
  245. while (i < ii && url[i].trim() === "") {
  246. i++;
  247. }
  248. return url.substring(i, i + 5).toLowerCase() === "data:";
  249. }
  250. function isPdfFile(filename) {
  251. return typeof filename === "string" && /\.pdf$/i.test(filename);
  252. }
  253. function getFilenameFromUrl(url, onlyStripPath = false) {
  254. if (!onlyStripPath) {
  255. [url] = url.split(/[#?]/, 1);
  256. }
  257. return url.substring(url.lastIndexOf("/") + 1);
  258. }
  259. function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  260. if (typeof url !== "string") {
  261. return defaultFilename;
  262. }
  263. if (isDataScheme(url)) {
  264. (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
  265. return defaultFilename;
  266. }
  267. const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  268. const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  269. const splitURI = reURI.exec(url);
  270. let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  271. if (suggestedFilename) {
  272. suggestedFilename = suggestedFilename[0];
  273. if (suggestedFilename.includes("%")) {
  274. try {
  275. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  276. } catch (ex) {}
  277. }
  278. }
  279. return suggestedFilename || defaultFilename;
  280. }
  281. class StatTimer {
  282. started = Object.create(null);
  283. times = [];
  284. time(name) {
  285. if (name in this.started) {
  286. (0, _util.warn)(`Timer is already running for ${name}`);
  287. }
  288. this.started[name] = Date.now();
  289. }
  290. timeEnd(name) {
  291. if (!(name in this.started)) {
  292. (0, _util.warn)(`Timer has not been started for ${name}`);
  293. }
  294. this.times.push({
  295. name,
  296. start: this.started[name],
  297. end: Date.now()
  298. });
  299. delete this.started[name];
  300. }
  301. toString() {
  302. const outBuf = [];
  303. let longest = 0;
  304. for (const {
  305. name
  306. } of this.times) {
  307. longest = Math.max(name.length, longest);
  308. }
  309. for (const {
  310. name,
  311. start,
  312. end
  313. } of this.times) {
  314. outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
  315. }
  316. return outBuf.join("");
  317. }
  318. }
  319. exports.StatTimer = StatTimer;
  320. function isValidFetchUrl(url, baseUrl) {
  321. try {
  322. const {
  323. protocol
  324. } = baseUrl ? new URL(url, baseUrl) : new URL(url);
  325. return protocol === "http:" || protocol === "https:";
  326. } catch (ex) {
  327. return false;
  328. }
  329. }
  330. function loadScript(src, removeScriptElement = false) {
  331. return new Promise((resolve, reject) => {
  332. const script = document.createElement("script");
  333. script.src = src;
  334. script.onload = function (evt) {
  335. if (removeScriptElement) {
  336. script.remove();
  337. }
  338. resolve(evt);
  339. };
  340. script.onerror = function () {
  341. reject(new Error(`Cannot load script at: ${script.src}`));
  342. };
  343. (document.head || document.documentElement).append(script);
  344. });
  345. }
  346. function deprecated(details) {
  347. console.log("Deprecated API usage: " + details);
  348. }
  349. let pdfDateStringRegex;
  350. class PDFDateString {
  351. static toDateObject(input) {
  352. if (!input || typeof input !== "string") {
  353. return null;
  354. }
  355. if (!pdfDateStringRegex) {
  356. pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
  357. }
  358. const matches = pdfDateStringRegex.exec(input);
  359. if (!matches) {
  360. return null;
  361. }
  362. const year = parseInt(matches[1], 10);
  363. let month = parseInt(matches[2], 10);
  364. month = month >= 1 && month <= 12 ? month - 1 : 0;
  365. let day = parseInt(matches[3], 10);
  366. day = day >= 1 && day <= 31 ? day : 1;
  367. let hour = parseInt(matches[4], 10);
  368. hour = hour >= 0 && hour <= 23 ? hour : 0;
  369. let minute = parseInt(matches[5], 10);
  370. minute = minute >= 0 && minute <= 59 ? minute : 0;
  371. let second = parseInt(matches[6], 10);
  372. second = second >= 0 && second <= 59 ? second : 0;
  373. const universalTimeRelation = matches[7] || "Z";
  374. let offsetHour = parseInt(matches[8], 10);
  375. offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
  376. let offsetMinute = parseInt(matches[9], 10) || 0;
  377. offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
  378. if (universalTimeRelation === "-") {
  379. hour += offsetHour;
  380. minute += offsetMinute;
  381. } else if (universalTimeRelation === "+") {
  382. hour -= offsetHour;
  383. minute -= offsetMinute;
  384. }
  385. return new Date(Date.UTC(year, month, day, hour, minute, second));
  386. }
  387. }
  388. exports.PDFDateString = PDFDateString;
  389. function getXfaPageViewport(xfaPage, {
  390. scale = 1,
  391. rotation = 0
  392. }) {
  393. const {
  394. width,
  395. height
  396. } = xfaPage.attributes.style;
  397. const viewBox = [0, 0, parseInt(width), parseInt(height)];
  398. return new PageViewport({
  399. viewBox,
  400. scale,
  401. rotation
  402. });
  403. }
  404. function getRGB(color) {
  405. if (color.startsWith("#")) {
  406. const colorRGB = parseInt(color.slice(1), 16);
  407. return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  408. }
  409. if (color.startsWith("rgb(")) {
  410. return color.slice(4, -1).split(",").map(x => parseInt(x));
  411. }
  412. if (color.startsWith("rgba(")) {
  413. return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  414. }
  415. (0, _util.warn)(`Not a valid color format: "${color}"`);
  416. return [0, 0, 0];
  417. }
  418. function getColorValues(colors) {
  419. const span = document.createElement("span");
  420. span.style.visibility = "hidden";
  421. document.body.append(span);
  422. for (const name of colors.keys()) {
  423. span.style.color = name;
  424. const computedColor = window.getComputedStyle(span).color;
  425. colors.set(name, getRGB(computedColor));
  426. }
  427. span.remove();
  428. }
  429. function getCurrentTransform(ctx) {
  430. const {
  431. a,
  432. b,
  433. c,
  434. d,
  435. e,
  436. f
  437. } = ctx.getTransform();
  438. return [a, b, c, d, e, f];
  439. }
  440. function getCurrentTransformInverse(ctx) {
  441. const {
  442. a,
  443. b,
  444. c,
  445. d,
  446. e,
  447. f
  448. } = ctx.getTransform().invertSelf();
  449. return [a, b, c, d, e, f];
  450. }
  451. function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  452. if (viewport instanceof PageViewport) {
  453. const {
  454. pageWidth,
  455. pageHeight
  456. } = viewport.rawDims;
  457. const {
  458. style
  459. } = div;
  460. const widthStr = `calc(var(--scale-factor) * ${pageWidth}px)`;
  461. const heightStr = `calc(var(--scale-factor) * ${pageHeight}px)`;
  462. if (!mustFlip || viewport.rotation % 180 === 0) {
  463. style.width = widthStr;
  464. style.height = heightStr;
  465. } else {
  466. style.width = heightStr;
  467. style.height = widthStr;
  468. }
  469. }
  470. if (mustRotate) {
  471. div.setAttribute("data-main-rotation", viewport.rotation);
  472. }
  473. }