annotation.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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.MarkupAnnotation = exports.AnnotationFactory = exports.AnnotationBorderStyle = exports.Annotation = void 0;
  27. exports.getQuadPoints = getQuadPoints;
  28. var _util = require("../shared/util.js");
  29. var _core_utils = require("./core_utils.js");
  30. var _default_appearance = require("./default_appearance.js");
  31. var _primitives = require("./primitives.js");
  32. var _bidi = require("./bidi.js");
  33. var _catalog = require("./catalog.js");
  34. var _colorspace = require("./colorspace.js");
  35. var _file_spec = require("./file_spec.js");
  36. var _object_loader = require("./object_loader.js");
  37. var _operator_list = require("./operator_list.js");
  38. var _stream = require("./stream.js");
  39. var _writer = require("./writer.js");
  40. var _factory = require("./xfa/factory.js");
  41. class AnnotationFactory {
  42. static create(xref, ref, pdfManager, idFactory, collectFields) {
  43. return Promise.all([pdfManager.ensureCatalog("acroForm"), collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1]).then(([acroForm, pageIndex]) => pdfManager.ensure(this, "_create", [xref, ref, pdfManager, idFactory, acroForm, collectFields, pageIndex]));
  44. }
  45. static _create(xref, ref, pdfManager, idFactory, acroForm, collectFields, pageIndex = -1) {
  46. const dict = xref.fetchIfRef(ref);
  47. if (!(0, _primitives.isDict)(dict)) {
  48. return undefined;
  49. }
  50. const id = (0, _primitives.isRef)(ref) ? ref.toString() : `annot_${idFactory.createObjId()}`;
  51. let subtype = dict.get("Subtype");
  52. subtype = (0, _primitives.isName)(subtype) ? subtype.name : null;
  53. const parameters = {
  54. xref,
  55. ref,
  56. dict,
  57. subtype,
  58. id,
  59. pdfManager,
  60. acroForm: acroForm instanceof _primitives.Dict ? acroForm : _primitives.Dict.empty,
  61. collectFields,
  62. pageIndex
  63. };
  64. switch (subtype) {
  65. case "Link":
  66. return new LinkAnnotation(parameters);
  67. case "Text":
  68. return new TextAnnotation(parameters);
  69. case "Widget":
  70. let fieldType = (0, _core_utils.getInheritableProperty)({
  71. dict,
  72. key: "FT"
  73. });
  74. fieldType = (0, _primitives.isName)(fieldType) ? fieldType.name : null;
  75. switch (fieldType) {
  76. case "Tx":
  77. return new TextWidgetAnnotation(parameters);
  78. case "Btn":
  79. return new ButtonWidgetAnnotation(parameters);
  80. case "Ch":
  81. return new ChoiceWidgetAnnotation(parameters);
  82. case "Sig":
  83. return new SignatureWidgetAnnotation(parameters);
  84. }
  85. (0, _util.warn)(`Unimplemented widget field type "${fieldType}", ` + "falling back to base field type.");
  86. return new WidgetAnnotation(parameters);
  87. case "Popup":
  88. return new PopupAnnotation(parameters);
  89. case "FreeText":
  90. return new FreeTextAnnotation(parameters);
  91. case "Line":
  92. return new LineAnnotation(parameters);
  93. case "Square":
  94. return new SquareAnnotation(parameters);
  95. case "Circle":
  96. return new CircleAnnotation(parameters);
  97. case "PolyLine":
  98. return new PolylineAnnotation(parameters);
  99. case "Polygon":
  100. return new PolygonAnnotation(parameters);
  101. case "Caret":
  102. return new CaretAnnotation(parameters);
  103. case "Ink":
  104. return new InkAnnotation(parameters);
  105. case "Highlight":
  106. return new HighlightAnnotation(parameters);
  107. case "Underline":
  108. return new UnderlineAnnotation(parameters);
  109. case "Squiggly":
  110. return new SquigglyAnnotation(parameters);
  111. case "StrikeOut":
  112. return new StrikeOutAnnotation(parameters);
  113. case "Stamp":
  114. return new StampAnnotation(parameters);
  115. case "FileAttachment":
  116. return new FileAttachmentAnnotation(parameters);
  117. default:
  118. if (!collectFields) {
  119. if (!subtype) {
  120. (0, _util.warn)("Annotation is missing the required /Subtype.");
  121. } else {
  122. (0, _util.warn)(`Unimplemented annotation type "${subtype}", ` + "falling back to base annotation.");
  123. }
  124. }
  125. return new Annotation(parameters);
  126. }
  127. }
  128. static async _getPageIndex(xref, ref, pdfManager) {
  129. try {
  130. const annotDict = await xref.fetchIfRefAsync(ref);
  131. if (!(0, _primitives.isDict)(annotDict)) {
  132. return -1;
  133. }
  134. const pageRef = annotDict.getRaw("P");
  135. if (!(0, _primitives.isRef)(pageRef)) {
  136. return -1;
  137. }
  138. const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [pageRef]);
  139. return pageIndex;
  140. } catch (ex) {
  141. (0, _util.warn)(`_getPageIndex: "${ex}".`);
  142. return -1;
  143. }
  144. }
  145. }
  146. exports.AnnotationFactory = AnnotationFactory;
  147. function getRgbColor(color, defaultColor = new Uint8ClampedArray(3)) {
  148. if (!Array.isArray(color)) {
  149. return defaultColor;
  150. }
  151. const rgbColor = defaultColor || new Uint8ClampedArray(3);
  152. switch (color.length) {
  153. case 0:
  154. return null;
  155. case 1:
  156. _colorspace.ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
  157. return rgbColor;
  158. case 3:
  159. _colorspace.ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
  160. return rgbColor;
  161. case 4:
  162. _colorspace.ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
  163. return rgbColor;
  164. default:
  165. return defaultColor;
  166. }
  167. }
  168. function getQuadPoints(dict, rect) {
  169. if (!dict.has("QuadPoints")) {
  170. return null;
  171. }
  172. const quadPoints = dict.getArray("QuadPoints");
  173. if (!Array.isArray(quadPoints) || quadPoints.length === 0 || quadPoints.length % 8 > 0) {
  174. return null;
  175. }
  176. const quadPointsLists = [];
  177. for (let i = 0, ii = quadPoints.length / 8; i < ii; i++) {
  178. quadPointsLists.push([]);
  179. for (let j = i * 8, jj = i * 8 + 8; j < jj; j += 2) {
  180. const x = quadPoints[j];
  181. const y = quadPoints[j + 1];
  182. if (rect !== null && (x < rect[0] || x > rect[2] || y < rect[1] || y > rect[3])) {
  183. return null;
  184. }
  185. quadPointsLists[i].push({
  186. x,
  187. y
  188. });
  189. }
  190. }
  191. return quadPointsLists.map(quadPointsList => {
  192. const [minX, maxX, minY, maxY] = quadPointsList.reduce(([mX, MX, mY, MY], quadPoint) => [Math.min(mX, quadPoint.x), Math.max(MX, quadPoint.x), Math.min(mY, quadPoint.y), Math.max(MY, quadPoint.y)], [Number.MAX_VALUE, Number.MIN_VALUE, Number.MAX_VALUE, Number.MIN_VALUE]);
  193. return [{
  194. x: minX,
  195. y: maxY
  196. }, {
  197. x: maxX,
  198. y: maxY
  199. }, {
  200. x: minX,
  201. y: minY
  202. }, {
  203. x: maxX,
  204. y: minY
  205. }];
  206. });
  207. }
  208. function getTransformMatrix(rect, bbox, matrix) {
  209. const [minX, minY, maxX, maxY] = _util.Util.getAxialAlignedBoundingBox(bbox, matrix);
  210. if (minX === maxX || minY === maxY) {
  211. return [1, 0, 0, 1, rect[0], rect[1]];
  212. }
  213. const xRatio = (rect[2] - rect[0]) / (maxX - minX);
  214. const yRatio = (rect[3] - rect[1]) / (maxY - minY);
  215. return [xRatio, 0, 0, yRatio, rect[0] - minX * xRatio, rect[1] - minY * yRatio];
  216. }
  217. class Annotation {
  218. constructor(params) {
  219. const dict = params.dict;
  220. this.setTitle(dict.get("T"));
  221. this.setContents(dict.get("Contents"));
  222. this.setModificationDate(dict.get("M"));
  223. this.setFlags(dict.get("F"));
  224. this.setRectangle(dict.getArray("Rect"));
  225. this.setColor(dict.getArray("C"));
  226. this.setBorderStyle(dict);
  227. this.setAppearance(dict);
  228. this.setBorderAndBackgroundColors(dict.get("MK"));
  229. this._streams = [];
  230. if (this.appearance) {
  231. this._streams.push(this.appearance);
  232. }
  233. this.data = {
  234. annotationFlags: this.flags,
  235. borderStyle: this.borderStyle,
  236. color: this.color,
  237. backgroundColor: this.backgroundColor,
  238. borderColor: this.borderColor,
  239. contentsObj: this._contents,
  240. hasAppearance: !!this.appearance,
  241. id: params.id,
  242. modificationDate: this.modificationDate,
  243. rect: this.rectangle,
  244. subtype: params.subtype,
  245. hasOwnCanvas: false
  246. };
  247. if (params.collectFields) {
  248. const kids = dict.get("Kids");
  249. if (Array.isArray(kids)) {
  250. const kidIds = [];
  251. for (const kid of kids) {
  252. if ((0, _primitives.isRef)(kid)) {
  253. kidIds.push(kid.toString());
  254. }
  255. }
  256. if (kidIds.length !== 0) {
  257. this.data.kidIds = kidIds;
  258. }
  259. }
  260. this.data.actions = (0, _core_utils.collectActions)(params.xref, dict, _util.AnnotationActionEventType);
  261. this.data.fieldName = this._constructFieldName(dict);
  262. this.data.pageIndex = params.pageIndex;
  263. }
  264. this._fallbackFontDict = null;
  265. }
  266. _hasFlag(flags, flag) {
  267. return !!(flags & flag);
  268. }
  269. _isViewable(flags) {
  270. return !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, _util.AnnotationFlag.NOVIEW);
  271. }
  272. _isPrintable(flags) {
  273. return this._hasFlag(flags, _util.AnnotationFlag.PRINT) && !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE);
  274. }
  275. mustBeViewed(annotationStorage) {
  276. const storageEntry = annotationStorage && annotationStorage.get(this.data.id);
  277. if (storageEntry && storageEntry.hidden !== undefined) {
  278. return !storageEntry.hidden;
  279. }
  280. return this.viewable && !this._hasFlag(this.flags, _util.AnnotationFlag.HIDDEN);
  281. }
  282. mustBePrinted(annotationStorage) {
  283. const storageEntry = annotationStorage && annotationStorage.get(this.data.id);
  284. if (storageEntry && storageEntry.print !== undefined) {
  285. return storageEntry.print;
  286. }
  287. return this.printable;
  288. }
  289. get viewable() {
  290. if (this.data.quadPoints === null) {
  291. return false;
  292. }
  293. if (this.flags === 0) {
  294. return true;
  295. }
  296. return this._isViewable(this.flags);
  297. }
  298. get printable() {
  299. if (this.data.quadPoints === null) {
  300. return false;
  301. }
  302. if (this.flags === 0) {
  303. return false;
  304. }
  305. return this._isPrintable(this.flags);
  306. }
  307. _parseStringHelper(data) {
  308. const str = typeof data === "string" ? (0, _util.stringToPDFString)(data) : "";
  309. const dir = str && (0, _bidi.bidi)(str).dir === "rtl" ? "rtl" : "ltr";
  310. return {
  311. str,
  312. dir
  313. };
  314. }
  315. setTitle(title) {
  316. this._title = this._parseStringHelper(title);
  317. }
  318. setContents(contents) {
  319. this._contents = this._parseStringHelper(contents);
  320. }
  321. setModificationDate(modificationDate) {
  322. this.modificationDate = (0, _util.isString)(modificationDate) ? modificationDate : null;
  323. }
  324. setFlags(flags) {
  325. this.flags = Number.isInteger(flags) && flags > 0 ? flags : 0;
  326. }
  327. hasFlag(flag) {
  328. return this._hasFlag(this.flags, flag);
  329. }
  330. setRectangle(rectangle) {
  331. if (Array.isArray(rectangle) && rectangle.length === 4) {
  332. this.rectangle = _util.Util.normalizeRect(rectangle);
  333. } else {
  334. this.rectangle = [0, 0, 0, 0];
  335. }
  336. }
  337. setColor(color) {
  338. this.color = getRgbColor(color);
  339. }
  340. setBorderAndBackgroundColors(mk) {
  341. if (mk instanceof _primitives.Dict) {
  342. this.borderColor = getRgbColor(mk.getArray("BC"), null);
  343. this.backgroundColor = getRgbColor(mk.getArray("BG"), null);
  344. } else {
  345. this.borderColor = this.backgroundColor = null;
  346. }
  347. }
  348. setBorderStyle(borderStyle) {
  349. this.borderStyle = new AnnotationBorderStyle();
  350. if (!(0, _primitives.isDict)(borderStyle)) {
  351. return;
  352. }
  353. if (borderStyle.has("BS")) {
  354. const dict = borderStyle.get("BS");
  355. const dictType = dict.get("Type");
  356. if (!dictType || (0, _primitives.isName)(dictType, "Border")) {
  357. this.borderStyle.setWidth(dict.get("W"), this.rectangle);
  358. this.borderStyle.setStyle(dict.get("S"));
  359. this.borderStyle.setDashArray(dict.getArray("D"));
  360. }
  361. } else if (borderStyle.has("Border")) {
  362. const array = borderStyle.getArray("Border");
  363. if (Array.isArray(array) && array.length >= 3) {
  364. this.borderStyle.setHorizontalCornerRadius(array[0]);
  365. this.borderStyle.setVerticalCornerRadius(array[1]);
  366. this.borderStyle.setWidth(array[2], this.rectangle);
  367. if (array.length === 4) {
  368. this.borderStyle.setDashArray(array[3], true);
  369. }
  370. }
  371. } else {
  372. this.borderStyle.setWidth(0);
  373. }
  374. }
  375. setAppearance(dict) {
  376. this.appearance = null;
  377. const appearanceStates = dict.get("AP");
  378. if (!(0, _primitives.isDict)(appearanceStates)) {
  379. return;
  380. }
  381. const normalAppearanceState = appearanceStates.get("N");
  382. if ((0, _primitives.isStream)(normalAppearanceState)) {
  383. this.appearance = normalAppearanceState;
  384. return;
  385. }
  386. if (!(0, _primitives.isDict)(normalAppearanceState)) {
  387. return;
  388. }
  389. const as = dict.get("AS");
  390. if (!(0, _primitives.isName)(as) || !normalAppearanceState.has(as.name)) {
  391. return;
  392. }
  393. this.appearance = normalAppearanceState.get(as.name);
  394. }
  395. loadResources(keys, appearance) {
  396. return appearance.dict.getAsync("Resources").then(resources => {
  397. if (!resources) {
  398. return undefined;
  399. }
  400. const objectLoader = new _object_loader.ObjectLoader(resources, keys, resources.xref);
  401. return objectLoader.load().then(function () {
  402. return resources;
  403. });
  404. });
  405. }
  406. getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  407. const data = this.data;
  408. let appearance = this.appearance;
  409. const isUsingOwnCanvas = data.hasOwnCanvas && intent & _util.RenderingIntentFlag.DISPLAY;
  410. if (!appearance) {
  411. if (!isUsingOwnCanvas) {
  412. return Promise.resolve(new _operator_list.OperatorList());
  413. }
  414. appearance = new _stream.StringStream("");
  415. appearance.dict = new _primitives.Dict();
  416. }
  417. const appearanceDict = appearance.dict;
  418. const resourcesPromise = this.loadResources(["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"], appearance);
  419. const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];
  420. const matrix = appearanceDict.getArray("Matrix") || [1, 0, 0, 1, 0, 0];
  421. const transform = getTransformMatrix(data.rect, bbox, matrix);
  422. return resourcesPromise.then(resources => {
  423. const opList = new _operator_list.OperatorList();
  424. opList.addOp(_util.OPS.beginAnnotation, [data.id, data.rect, transform, matrix, isUsingOwnCanvas]);
  425. return evaluator.getOperatorList({
  426. stream: appearance,
  427. task,
  428. resources,
  429. operatorList: opList,
  430. fallbackFontDict: this._fallbackFontDict
  431. }).then(() => {
  432. opList.addOp(_util.OPS.endAnnotation, []);
  433. this.reset();
  434. return opList;
  435. });
  436. });
  437. }
  438. async save(evaluator, task, annotationStorage) {
  439. return null;
  440. }
  441. getFieldObject() {
  442. if (this.data.kidIds) {
  443. return {
  444. id: this.data.id,
  445. actions: this.data.actions,
  446. name: this.data.fieldName,
  447. strokeColor: this.data.borderColor,
  448. fillColor: this.data.backgroundColor,
  449. type: "",
  450. kidIds: this.data.kidIds,
  451. page: this.data.pageIndex
  452. };
  453. }
  454. return null;
  455. }
  456. reset() {
  457. for (const stream of this._streams) {
  458. stream.reset();
  459. }
  460. }
  461. _constructFieldName(dict) {
  462. if (!dict.has("T") && !dict.has("Parent")) {
  463. (0, _util.warn)("Unknown field name, falling back to empty field name.");
  464. return "";
  465. }
  466. if (!dict.has("Parent")) {
  467. return (0, _util.stringToPDFString)(dict.get("T"));
  468. }
  469. const fieldName = [];
  470. if (dict.has("T")) {
  471. fieldName.unshift((0, _util.stringToPDFString)(dict.get("T")));
  472. }
  473. let loopDict = dict;
  474. const visited = new _primitives.RefSet();
  475. if (dict.objId) {
  476. visited.put(dict.objId);
  477. }
  478. while (loopDict.has("Parent")) {
  479. loopDict = loopDict.get("Parent");
  480. if (!(loopDict instanceof _primitives.Dict) || loopDict.objId && visited.has(loopDict.objId)) {
  481. break;
  482. }
  483. if (loopDict.objId) {
  484. visited.put(loopDict.objId);
  485. }
  486. if (loopDict.has("T")) {
  487. fieldName.unshift((0, _util.stringToPDFString)(loopDict.get("T")));
  488. }
  489. }
  490. return fieldName.join(".");
  491. }
  492. }
  493. exports.Annotation = Annotation;
  494. class AnnotationBorderStyle {
  495. constructor() {
  496. this.width = 1;
  497. this.style = _util.AnnotationBorderStyleType.SOLID;
  498. this.dashArray = [3];
  499. this.horizontalCornerRadius = 0;
  500. this.verticalCornerRadius = 0;
  501. }
  502. setWidth(width, rect = [0, 0, 0, 0]) {
  503. if ((0, _primitives.isName)(width)) {
  504. this.width = 0;
  505. return;
  506. }
  507. if (Number.isInteger(width)) {
  508. if (width > 0) {
  509. const maxWidth = (rect[2] - rect[0]) / 2;
  510. const maxHeight = (rect[3] - rect[1]) / 2;
  511. if (maxWidth > 0 && maxHeight > 0 && (width > maxWidth || width > maxHeight)) {
  512. (0, _util.warn)(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
  513. width = 1;
  514. }
  515. }
  516. this.width = width;
  517. }
  518. }
  519. setStyle(style) {
  520. if (!(0, _primitives.isName)(style)) {
  521. return;
  522. }
  523. switch (style.name) {
  524. case "S":
  525. this.style = _util.AnnotationBorderStyleType.SOLID;
  526. break;
  527. case "D":
  528. this.style = _util.AnnotationBorderStyleType.DASHED;
  529. break;
  530. case "B":
  531. this.style = _util.AnnotationBorderStyleType.BEVELED;
  532. break;
  533. case "I":
  534. this.style = _util.AnnotationBorderStyleType.INSET;
  535. break;
  536. case "U":
  537. this.style = _util.AnnotationBorderStyleType.UNDERLINE;
  538. break;
  539. default:
  540. break;
  541. }
  542. }
  543. setDashArray(dashArray, forceStyle = false) {
  544. if (Array.isArray(dashArray) && dashArray.length > 0) {
  545. let isValid = true;
  546. let allZeros = true;
  547. for (const element of dashArray) {
  548. const validNumber = +element >= 0;
  549. if (!validNumber) {
  550. isValid = false;
  551. break;
  552. } else if (element > 0) {
  553. allZeros = false;
  554. }
  555. }
  556. if (isValid && !allZeros) {
  557. this.dashArray = dashArray;
  558. if (forceStyle) {
  559. this.setStyle(_primitives.Name.get("D"));
  560. }
  561. } else {
  562. this.width = 0;
  563. }
  564. } else if (dashArray) {
  565. this.width = 0;
  566. }
  567. }
  568. setHorizontalCornerRadius(radius) {
  569. if (Number.isInteger(radius)) {
  570. this.horizontalCornerRadius = radius;
  571. }
  572. }
  573. setVerticalCornerRadius(radius) {
  574. if (Number.isInteger(radius)) {
  575. this.verticalCornerRadius = radius;
  576. }
  577. }
  578. }
  579. exports.AnnotationBorderStyle = AnnotationBorderStyle;
  580. class MarkupAnnotation extends Annotation {
  581. constructor(parameters) {
  582. super(parameters);
  583. const dict = parameters.dict;
  584. if (dict.has("IRT")) {
  585. const rawIRT = dict.getRaw("IRT");
  586. this.data.inReplyTo = (0, _primitives.isRef)(rawIRT) ? rawIRT.toString() : null;
  587. const rt = dict.get("RT");
  588. this.data.replyType = (0, _primitives.isName)(rt) ? rt.name : _util.AnnotationReplyType.REPLY;
  589. }
  590. if (this.data.replyType === _util.AnnotationReplyType.GROUP) {
  591. const parent = dict.get("IRT");
  592. this.setTitle(parent.get("T"));
  593. this.data.titleObj = this._title;
  594. this.setContents(parent.get("Contents"));
  595. this.data.contentsObj = this._contents;
  596. if (!parent.has("CreationDate")) {
  597. this.data.creationDate = null;
  598. } else {
  599. this.setCreationDate(parent.get("CreationDate"));
  600. this.data.creationDate = this.creationDate;
  601. }
  602. if (!parent.has("M")) {
  603. this.data.modificationDate = null;
  604. } else {
  605. this.setModificationDate(parent.get("M"));
  606. this.data.modificationDate = this.modificationDate;
  607. }
  608. this.data.hasPopup = parent.has("Popup");
  609. if (!parent.has("C")) {
  610. this.data.color = null;
  611. } else {
  612. this.setColor(parent.getArray("C"));
  613. this.data.color = this.color;
  614. }
  615. } else {
  616. this.data.titleObj = this._title;
  617. this.setCreationDate(dict.get("CreationDate"));
  618. this.data.creationDate = this.creationDate;
  619. this.data.hasPopup = dict.has("Popup");
  620. if (!dict.has("C")) {
  621. this.data.color = null;
  622. }
  623. }
  624. if (dict.has("RC")) {
  625. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(dict.get("RC"));
  626. }
  627. }
  628. setCreationDate(creationDate) {
  629. this.creationDate = (0, _util.isString)(creationDate) ? creationDate : null;
  630. }
  631. _setDefaultAppearance({
  632. xref,
  633. extra,
  634. strokeColor,
  635. fillColor,
  636. blendMode,
  637. strokeAlpha,
  638. fillAlpha,
  639. pointsCallback
  640. }) {
  641. let minX = Number.MAX_VALUE;
  642. let minY = Number.MAX_VALUE;
  643. let maxX = Number.MIN_VALUE;
  644. let maxY = Number.MIN_VALUE;
  645. const buffer = ["q"];
  646. if (extra) {
  647. buffer.push(extra);
  648. }
  649. if (strokeColor) {
  650. buffer.push(`${strokeColor[0]} ${strokeColor[1]} ${strokeColor[2]} RG`);
  651. }
  652. if (fillColor) {
  653. buffer.push(`${fillColor[0]} ${fillColor[1]} ${fillColor[2]} rg`);
  654. }
  655. let pointsArray = this.data.quadPoints;
  656. if (!pointsArray) {
  657. pointsArray = [[{
  658. x: this.rectangle[0],
  659. y: this.rectangle[3]
  660. }, {
  661. x: this.rectangle[2],
  662. y: this.rectangle[3]
  663. }, {
  664. x: this.rectangle[0],
  665. y: this.rectangle[1]
  666. }, {
  667. x: this.rectangle[2],
  668. y: this.rectangle[1]
  669. }]];
  670. }
  671. for (const points of pointsArray) {
  672. const [mX, MX, mY, MY] = pointsCallback(buffer, points);
  673. minX = Math.min(minX, mX);
  674. maxX = Math.max(maxX, MX);
  675. minY = Math.min(minY, mY);
  676. maxY = Math.max(maxY, MY);
  677. }
  678. buffer.push("Q");
  679. const formDict = new _primitives.Dict(xref);
  680. const appearanceStreamDict = new _primitives.Dict(xref);
  681. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  682. const appearanceStream = new _stream.StringStream(buffer.join(" "));
  683. appearanceStream.dict = appearanceStreamDict;
  684. formDict.set("Fm0", appearanceStream);
  685. const gsDict = new _primitives.Dict(xref);
  686. if (blendMode) {
  687. gsDict.set("BM", _primitives.Name.get(blendMode));
  688. }
  689. if (typeof strokeAlpha === "number") {
  690. gsDict.set("CA", strokeAlpha);
  691. }
  692. if (typeof fillAlpha === "number") {
  693. gsDict.set("ca", fillAlpha);
  694. }
  695. const stateDict = new _primitives.Dict(xref);
  696. stateDict.set("GS0", gsDict);
  697. const resources = new _primitives.Dict(xref);
  698. resources.set("ExtGState", stateDict);
  699. resources.set("XObject", formDict);
  700. const appearanceDict = new _primitives.Dict(xref);
  701. appearanceDict.set("Resources", resources);
  702. const bbox = this.data.rect = [minX, minY, maxX, maxY];
  703. appearanceDict.set("BBox", bbox);
  704. this.appearance = new _stream.StringStream("/GS0 gs /Fm0 Do");
  705. this.appearance.dict = appearanceDict;
  706. this._streams.push(this.appearance, appearanceStream);
  707. }
  708. }
  709. exports.MarkupAnnotation = MarkupAnnotation;
  710. class WidgetAnnotation extends Annotation {
  711. constructor(params) {
  712. super(params);
  713. const dict = params.dict;
  714. const data = this.data;
  715. this.ref = params.ref;
  716. data.annotationType = _util.AnnotationType.WIDGET;
  717. if (data.fieldName === undefined) {
  718. data.fieldName = this._constructFieldName(dict);
  719. }
  720. if (data.actions === undefined) {
  721. data.actions = (0, _core_utils.collectActions)(params.xref, dict, _util.AnnotationActionEventType);
  722. }
  723. const fieldValue = (0, _core_utils.getInheritableProperty)({
  724. dict,
  725. key: "V",
  726. getArray: true
  727. });
  728. data.fieldValue = this._decodeFormValue(fieldValue);
  729. const defaultFieldValue = (0, _core_utils.getInheritableProperty)({
  730. dict,
  731. key: "DV",
  732. getArray: true
  733. });
  734. data.defaultFieldValue = this._decodeFormValue(defaultFieldValue);
  735. if (fieldValue === undefined && data.defaultFieldValue !== null) {
  736. data.fieldValue = data.defaultFieldValue;
  737. }
  738. data.alternativeText = (0, _util.stringToPDFString)(dict.get("TU") || "");
  739. const defaultAppearance = (0, _core_utils.getInheritableProperty)({
  740. dict,
  741. key: "DA"
  742. }) || params.acroForm.get("DA");
  743. this._defaultAppearance = (0, _util.isString)(defaultAppearance) ? defaultAppearance : "";
  744. data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance);
  745. const fieldType = (0, _core_utils.getInheritableProperty)({
  746. dict,
  747. key: "FT"
  748. });
  749. data.fieldType = (0, _primitives.isName)(fieldType) ? fieldType.name : null;
  750. const localResources = (0, _core_utils.getInheritableProperty)({
  751. dict,
  752. key: "DR"
  753. });
  754. const acroFormResources = params.acroForm.get("DR");
  755. const appearanceResources = this.appearance && this.appearance.dict.get("Resources");
  756. this._fieldResources = {
  757. localResources,
  758. acroFormResources,
  759. appearanceResources,
  760. mergedResources: _primitives.Dict.merge({
  761. xref: params.xref,
  762. dictArray: [localResources, appearanceResources, acroFormResources],
  763. mergeSubDicts: true
  764. })
  765. };
  766. data.fieldFlags = (0, _core_utils.getInheritableProperty)({
  767. dict,
  768. key: "Ff"
  769. });
  770. if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
  771. data.fieldFlags = 0;
  772. }
  773. data.readOnly = this.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
  774. data.hidden = this._hasFlag(data.annotationFlags, _util.AnnotationFlag.HIDDEN);
  775. }
  776. _decodeFormValue(formValue) {
  777. if (Array.isArray(formValue)) {
  778. return formValue.filter(item => (0, _util.isString)(item)).map(item => (0, _util.stringToPDFString)(item));
  779. } else if ((0, _primitives.isName)(formValue)) {
  780. return (0, _util.stringToPDFString)(formValue.name);
  781. } else if ((0, _util.isString)(formValue)) {
  782. return (0, _util.stringToPDFString)(formValue);
  783. }
  784. return null;
  785. }
  786. hasFieldFlag(flag) {
  787. return !!(this.data.fieldFlags & flag);
  788. }
  789. getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  790. if (renderForms && !(this instanceof SignatureWidgetAnnotation)) {
  791. return Promise.resolve(new _operator_list.OperatorList());
  792. }
  793. if (!this._hasText) {
  794. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  795. }
  796. return this._getAppearance(evaluator, task, annotationStorage).then(content => {
  797. if (this.appearance && content === null) {
  798. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  799. }
  800. const operatorList = new _operator_list.OperatorList();
  801. if (!this._defaultAppearance || content === null) {
  802. return operatorList;
  803. }
  804. const matrix = [1, 0, 0, 1, 0, 0];
  805. const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
  806. const transform = getTransformMatrix(this.data.rect, bbox, matrix);
  807. operatorList.addOp(_util.OPS.beginAnnotation, [this.data.id, this.data.rect, transform, matrix]);
  808. const stream = new _stream.StringStream(content);
  809. return evaluator.getOperatorList({
  810. stream,
  811. task,
  812. resources: this._fieldResources.mergedResources,
  813. operatorList
  814. }).then(function () {
  815. operatorList.addOp(_util.OPS.endAnnotation, []);
  816. return operatorList;
  817. });
  818. });
  819. }
  820. async save(evaluator, task, annotationStorage) {
  821. if (!annotationStorage) {
  822. return null;
  823. }
  824. const storageEntry = annotationStorage.get(this.data.id);
  825. const value = storageEntry && storageEntry.value;
  826. if (value === this.data.fieldValue || value === undefined) {
  827. return null;
  828. }
  829. let appearance = await this._getAppearance(evaluator, task, annotationStorage);
  830. if (appearance === null) {
  831. return null;
  832. }
  833. const {
  834. xref
  835. } = evaluator;
  836. const dict = xref.fetchIfRef(this.ref);
  837. if (!(0, _primitives.isDict)(dict)) {
  838. return null;
  839. }
  840. const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
  841. const xfa = {
  842. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  843. value
  844. };
  845. const newRef = xref.getNewRef();
  846. const AP = new _primitives.Dict(xref);
  847. AP.set("N", newRef);
  848. const encrypt = xref.encrypt;
  849. let originalTransform = null;
  850. let newTransform = null;
  851. if (encrypt) {
  852. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  853. newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
  854. appearance = newTransform.encryptString(appearance);
  855. }
  856. dict.set("V", (0, _util.isAscii)(value) ? value : (0, _util.stringToUTF16BEString)(value));
  857. dict.set("AP", AP);
  858. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  859. const appearanceDict = new _primitives.Dict(xref);
  860. appearanceDict.set("Length", appearance.length);
  861. appearanceDict.set("Subtype", _primitives.Name.get("Form"));
  862. appearanceDict.set("Resources", this._getSaveFieldResources(xref));
  863. appearanceDict.set("BBox", bbox);
  864. const bufferOriginal = [`${this.ref.num} ${this.ref.gen} obj\n`];
  865. (0, _writer.writeDict)(dict, bufferOriginal, originalTransform);
  866. bufferOriginal.push("\nendobj\n");
  867. const bufferNew = [`${newRef.num} ${newRef.gen} obj\n`];
  868. (0, _writer.writeDict)(appearanceDict, bufferNew, newTransform);
  869. bufferNew.push(" stream\n", appearance, "\nendstream\nendobj\n");
  870. return [{
  871. ref: this.ref,
  872. data: bufferOriginal.join(""),
  873. xfa
  874. }, {
  875. ref: newRef,
  876. data: bufferNew.join(""),
  877. xfa: null
  878. }];
  879. }
  880. async _getAppearance(evaluator, task, annotationStorage) {
  881. const isPassword = this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD);
  882. if (!annotationStorage || isPassword) {
  883. return null;
  884. }
  885. const storageEntry = annotationStorage.get(this.data.id);
  886. let value = storageEntry && storageEntry.value;
  887. if (value === undefined) {
  888. return null;
  889. }
  890. value = value.trim();
  891. if (value === "") {
  892. return "";
  893. }
  894. let lineCount = -1;
  895. if (this.data.multiLine) {
  896. lineCount = value.split(/\r\n|\r|\n/).length;
  897. }
  898. const defaultPadding = 2;
  899. const hPadding = defaultPadding;
  900. const totalHeight = this.data.rect[3] - this.data.rect[1];
  901. const totalWidth = this.data.rect[2] - this.data.rect[0];
  902. if (!this._defaultAppearance) {
  903. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  904. }
  905. const [defaultAppearance, fontSize] = this._computeFontSize(totalHeight, lineCount);
  906. const font = await this._getFontData(evaluator, task);
  907. let descent = font.descent;
  908. if (isNaN(descent)) {
  909. descent = 0;
  910. }
  911. const vPadding = defaultPadding + Math.abs(descent) * fontSize;
  912. const alignment = this.data.textAlignment;
  913. if (this.data.multiLine) {
  914. return this._getMultilineAppearance(defaultAppearance, value, font, fontSize, totalWidth, totalHeight, alignment, hPadding, vPadding);
  915. }
  916. const encodedString = font.encodeString(value).join("");
  917. if (this.data.comb) {
  918. return this._getCombAppearance(defaultAppearance, font, encodedString, totalWidth, hPadding, vPadding);
  919. }
  920. if (alignment === 0 || alignment > 2) {
  921. return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm (${(0, _util.escapeString)(encodedString)}) Tj` + " ET Q EMC";
  922. }
  923. const renderedText = this._renderText(encodedString, font, fontSize, totalWidth, alignment, hPadding, vPadding);
  924. return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC";
  925. }
  926. async _getFontData(evaluator, task) {
  927. const operatorList = new _operator_list.OperatorList();
  928. const initialState = {
  929. font: null,
  930. clone() {
  931. return this;
  932. }
  933. };
  934. const {
  935. fontName,
  936. fontSize
  937. } = this.data.defaultAppearanceData;
  938. await evaluator.handleSetFont(this._fieldResources.mergedResources, [fontName && _primitives.Name.get(fontName), fontSize], null, operatorList, task, initialState, null);
  939. return initialState.font;
  940. }
  941. _computeFontSize(height, lineCount) {
  942. let {
  943. fontSize
  944. } = this.data.defaultAppearanceData;
  945. if (!fontSize) {
  946. const roundWithOneDigit = x => Math.round(x * 10) / 10;
  947. const FONT_FACTOR = 0.8;
  948. if (lineCount === -1) {
  949. fontSize = roundWithOneDigit(FONT_FACTOR * height);
  950. } else {
  951. fontSize = 10;
  952. let lineHeight = fontSize / FONT_FACTOR;
  953. let numberOfLines = Math.round(height / lineHeight);
  954. numberOfLines = Math.max(numberOfLines, lineCount);
  955. lineHeight = height / numberOfLines;
  956. fontSize = roundWithOneDigit(FONT_FACTOR * lineHeight);
  957. }
  958. const {
  959. fontName,
  960. fontColor
  961. } = this.data.defaultAppearanceData;
  962. this._defaultAppearance = (0, _default_appearance.createDefaultAppearance)({
  963. fontSize,
  964. fontName,
  965. fontColor
  966. });
  967. }
  968. return [this._defaultAppearance, fontSize];
  969. }
  970. _renderText(text, font, fontSize, totalWidth, alignment, hPadding, vPadding) {
  971. const glyphs = font.charsToGlyphs(text);
  972. const scale = fontSize / 1000;
  973. let width = 0;
  974. for (const glyph of glyphs) {
  975. width += glyph.width * scale;
  976. }
  977. let shift;
  978. if (alignment === 1) {
  979. shift = (totalWidth - width) / 2;
  980. } else if (alignment === 2) {
  981. shift = totalWidth - width - hPadding;
  982. } else {
  983. shift = hPadding;
  984. }
  985. shift = shift.toFixed(2);
  986. vPadding = vPadding.toFixed(2);
  987. return `${shift} ${vPadding} Td (${(0, _util.escapeString)(text)}) Tj`;
  988. }
  989. _getSaveFieldResources(xref) {
  990. const {
  991. localResources,
  992. appearanceResources,
  993. acroFormResources
  994. } = this._fieldResources;
  995. const fontName = this.data.defaultAppearanceData && this.data.defaultAppearanceData.fontName;
  996. if (!fontName) {
  997. return localResources || _primitives.Dict.empty;
  998. }
  999. for (const resources of [localResources, appearanceResources]) {
  1000. if (resources instanceof _primitives.Dict) {
  1001. const localFont = resources.get("Font");
  1002. if (localFont instanceof _primitives.Dict && localFont.has(fontName)) {
  1003. return resources;
  1004. }
  1005. }
  1006. }
  1007. if (acroFormResources instanceof _primitives.Dict) {
  1008. const acroFormFont = acroFormResources.get("Font");
  1009. if (acroFormFont instanceof _primitives.Dict && acroFormFont.has(fontName)) {
  1010. const subFontDict = new _primitives.Dict(xref);
  1011. subFontDict.set(fontName, acroFormFont.getRaw(fontName));
  1012. const subResourcesDict = new _primitives.Dict(xref);
  1013. subResourcesDict.set("Font", subFontDict);
  1014. return _primitives.Dict.merge({
  1015. xref,
  1016. dictArray: [subResourcesDict, localResources],
  1017. mergeSubDicts: true
  1018. });
  1019. }
  1020. }
  1021. return localResources || _primitives.Dict.empty;
  1022. }
  1023. getFieldObject() {
  1024. return null;
  1025. }
  1026. }
  1027. class TextWidgetAnnotation extends WidgetAnnotation {
  1028. constructor(params) {
  1029. super(params);
  1030. this._hasText = true;
  1031. const dict = params.dict;
  1032. if (!(0, _util.isString)(this.data.fieldValue)) {
  1033. this.data.fieldValue = "";
  1034. }
  1035. let alignment = (0, _core_utils.getInheritableProperty)({
  1036. dict,
  1037. key: "Q"
  1038. });
  1039. if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
  1040. alignment = null;
  1041. }
  1042. this.data.textAlignment = alignment;
  1043. let maximumLength = (0, _core_utils.getInheritableProperty)({
  1044. dict,
  1045. key: "MaxLen"
  1046. });
  1047. if (!Number.isInteger(maximumLength) || maximumLength < 0) {
  1048. maximumLength = null;
  1049. }
  1050. this.data.maxLen = maximumLength;
  1051. this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
  1052. this.data.comb = this.hasFieldFlag(_util.AnnotationFieldFlag.COMB) && !this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD) && !this.hasFieldFlag(_util.AnnotationFieldFlag.FILESELECT) && this.data.maxLen !== null;
  1053. }
  1054. _getCombAppearance(defaultAppearance, font, text, width, hPadding, vPadding) {
  1055. const combWidth = (width / this.data.maxLen).toFixed(2);
  1056. const buf = [];
  1057. const positions = font.getCharPositions(text);
  1058. for (const [start, end] of positions) {
  1059. buf.push(`(${(0, _util.escapeString)(text.substring(start, end))}) Tj`);
  1060. }
  1061. const renderedComb = buf.join(` ${combWidth} 0 Td `);
  1062. return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm ${renderedComb}` + " ET Q EMC";
  1063. }
  1064. _getMultilineAppearance(defaultAppearance, text, font, fontSize, width, height, alignment, hPadding, vPadding) {
  1065. const lines = text.split(/\r\n|\r|\n/);
  1066. const buf = [];
  1067. const totalWidth = width - 2 * hPadding;
  1068. for (const line of lines) {
  1069. const chunks = this._splitLine(line, font, fontSize, totalWidth);
  1070. for (const chunk of chunks) {
  1071. const padding = buf.length === 0 ? hPadding : 0;
  1072. buf.push(this._renderText(chunk, font, fontSize, width, alignment, padding, -fontSize));
  1073. }
  1074. }
  1075. const renderedText = buf.join("\n");
  1076. return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 0 ${height} Tm ${renderedText}` + " ET Q EMC";
  1077. }
  1078. _splitLine(line, font, fontSize, width) {
  1079. line = font.encodeString(line).join("");
  1080. const glyphs = font.charsToGlyphs(line);
  1081. if (glyphs.length <= 1) {
  1082. return [line];
  1083. }
  1084. const positions = font.getCharPositions(line);
  1085. const scale = fontSize / 1000;
  1086. const chunks = [];
  1087. let lastSpacePosInStringStart = -1,
  1088. lastSpacePosInStringEnd = -1,
  1089. lastSpacePos = -1,
  1090. startChunk = 0,
  1091. currentWidth = 0;
  1092. for (let i = 0, ii = glyphs.length; i < ii; i++) {
  1093. const [start, end] = positions[i];
  1094. const glyph = glyphs[i];
  1095. const glyphWidth = glyph.width * scale;
  1096. if (glyph.unicode === " ") {
  1097. if (currentWidth + glyphWidth > width) {
  1098. chunks.push(line.substring(startChunk, start));
  1099. startChunk = start;
  1100. currentWidth = glyphWidth;
  1101. lastSpacePosInStringStart = -1;
  1102. lastSpacePos = -1;
  1103. } else {
  1104. currentWidth += glyphWidth;
  1105. lastSpacePosInStringStart = start;
  1106. lastSpacePosInStringEnd = end;
  1107. lastSpacePos = i;
  1108. }
  1109. } else {
  1110. if (currentWidth + glyphWidth > width) {
  1111. if (lastSpacePosInStringStart !== -1) {
  1112. chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
  1113. startChunk = lastSpacePosInStringEnd;
  1114. i = lastSpacePos + 1;
  1115. lastSpacePosInStringStart = -1;
  1116. currentWidth = 0;
  1117. } else {
  1118. chunks.push(line.substring(startChunk, start));
  1119. startChunk = start;
  1120. currentWidth = glyphWidth;
  1121. }
  1122. } else {
  1123. currentWidth += glyphWidth;
  1124. }
  1125. }
  1126. }
  1127. if (startChunk < line.length) {
  1128. chunks.push(line.substring(startChunk, line.length));
  1129. }
  1130. return chunks;
  1131. }
  1132. getFieldObject() {
  1133. return {
  1134. id: this.data.id,
  1135. value: this.data.fieldValue,
  1136. defaultValue: this.data.defaultFieldValue,
  1137. multiline: this.data.multiLine,
  1138. password: this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD),
  1139. charLimit: this.data.maxLen,
  1140. comb: this.data.comb,
  1141. editable: !this.data.readOnly,
  1142. hidden: this.data.hidden,
  1143. name: this.data.fieldName,
  1144. rect: this.data.rect,
  1145. actions: this.data.actions,
  1146. page: this.data.pageIndex,
  1147. strokeColor: this.data.borderColor,
  1148. fillColor: this.data.backgroundColor,
  1149. type: "text"
  1150. };
  1151. }
  1152. }
  1153. class ButtonWidgetAnnotation extends WidgetAnnotation {
  1154. constructor(params) {
  1155. super(params);
  1156. this.checkedAppearance = null;
  1157. this.uncheckedAppearance = null;
  1158. this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1159. this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1160. this.data.pushButton = this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1161. this.data.isTooltipOnly = false;
  1162. if (this.data.checkBox) {
  1163. this._processCheckBox(params);
  1164. } else if (this.data.radioButton) {
  1165. this._processRadioButton(params);
  1166. } else if (this.data.pushButton) {
  1167. this.data.hasOwnCanvas = true;
  1168. this._processPushButton(params);
  1169. } else {
  1170. (0, _util.warn)("Invalid field flags for button widget annotation");
  1171. }
  1172. }
  1173. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  1174. if (this.data.pushButton) {
  1175. return super.getOperatorList(evaluator, task, intent, false, annotationStorage);
  1176. }
  1177. let value = null;
  1178. if (annotationStorage) {
  1179. const storageEntry = annotationStorage.get(this.data.id);
  1180. value = storageEntry ? storageEntry.value : null;
  1181. }
  1182. if (value === null) {
  1183. if (this.appearance) {
  1184. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1185. }
  1186. if (this.data.checkBox) {
  1187. value = this.data.fieldValue === this.data.exportValue;
  1188. } else {
  1189. value = this.data.fieldValue === this.data.buttonValue;
  1190. }
  1191. }
  1192. const appearance = value ? this.checkedAppearance : this.uncheckedAppearance;
  1193. if (appearance) {
  1194. const savedAppearance = this.appearance;
  1195. this.appearance = appearance;
  1196. const operatorList = super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1197. this.appearance = savedAppearance;
  1198. return operatorList;
  1199. }
  1200. return new _operator_list.OperatorList();
  1201. }
  1202. async save(evaluator, task, annotationStorage) {
  1203. if (this.data.checkBox) {
  1204. return this._saveCheckbox(evaluator, task, annotationStorage);
  1205. }
  1206. if (this.data.radioButton) {
  1207. return this._saveRadioButton(evaluator, task, annotationStorage);
  1208. }
  1209. return null;
  1210. }
  1211. async _saveCheckbox(evaluator, task, annotationStorage) {
  1212. if (!annotationStorage) {
  1213. return null;
  1214. }
  1215. const storageEntry = annotationStorage.get(this.data.id);
  1216. const value = storageEntry && storageEntry.value;
  1217. if (value === undefined) {
  1218. return null;
  1219. }
  1220. const defaultValue = this.data.fieldValue === this.data.exportValue;
  1221. if (defaultValue === value) {
  1222. return null;
  1223. }
  1224. const dict = evaluator.xref.fetchIfRef(this.ref);
  1225. if (!(0, _primitives.isDict)(dict)) {
  1226. return null;
  1227. }
  1228. const xfa = {
  1229. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1230. value: value ? this.data.exportValue : ""
  1231. };
  1232. const name = _primitives.Name.get(value ? this.data.exportValue : "Off");
  1233. dict.set("V", name);
  1234. dict.set("AS", name);
  1235. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1236. const encrypt = evaluator.xref.encrypt;
  1237. let originalTransform = null;
  1238. if (encrypt) {
  1239. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1240. }
  1241. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1242. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1243. buffer.push("\nendobj\n");
  1244. return [{
  1245. ref: this.ref,
  1246. data: buffer.join(""),
  1247. xfa
  1248. }];
  1249. }
  1250. async _saveRadioButton(evaluator, task, annotationStorage) {
  1251. if (!annotationStorage) {
  1252. return null;
  1253. }
  1254. const storageEntry = annotationStorage.get(this.data.id);
  1255. const value = storageEntry && storageEntry.value;
  1256. if (value === undefined) {
  1257. return null;
  1258. }
  1259. const defaultValue = this.data.fieldValue === this.data.buttonValue;
  1260. if (defaultValue === value) {
  1261. return null;
  1262. }
  1263. const dict = evaluator.xref.fetchIfRef(this.ref);
  1264. if (!(0, _primitives.isDict)(dict)) {
  1265. return null;
  1266. }
  1267. const xfa = {
  1268. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1269. value: value ? this.data.buttonValue : ""
  1270. };
  1271. const name = _primitives.Name.get(value ? this.data.buttonValue : "Off");
  1272. let parentBuffer = null;
  1273. const encrypt = evaluator.xref.encrypt;
  1274. if (value) {
  1275. if ((0, _primitives.isRef)(this.parent)) {
  1276. const parent = evaluator.xref.fetch(this.parent);
  1277. let parentTransform = null;
  1278. if (encrypt) {
  1279. parentTransform = encrypt.createCipherTransform(this.parent.num, this.parent.gen);
  1280. }
  1281. parent.set("V", name);
  1282. parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
  1283. (0, _writer.writeDict)(parent, parentBuffer, parentTransform);
  1284. parentBuffer.push("\nendobj\n");
  1285. } else if ((0, _primitives.isDict)(this.parent)) {
  1286. this.parent.set("V", name);
  1287. }
  1288. }
  1289. dict.set("AS", name);
  1290. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1291. let originalTransform = null;
  1292. if (encrypt) {
  1293. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1294. }
  1295. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1296. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1297. buffer.push("\nendobj\n");
  1298. const newRefs = [{
  1299. ref: this.ref,
  1300. data: buffer.join(""),
  1301. xfa
  1302. }];
  1303. if (parentBuffer !== null) {
  1304. newRefs.push({
  1305. ref: this.parent,
  1306. data: parentBuffer.join(""),
  1307. xfa: null
  1308. });
  1309. }
  1310. return newRefs;
  1311. }
  1312. _getDefaultCheckedAppearance(params, type) {
  1313. const width = this.data.rect[2] - this.data.rect[0];
  1314. const height = this.data.rect[3] - this.data.rect[1];
  1315. const bbox = [0, 0, width, height];
  1316. const FONT_RATIO = 0.8;
  1317. const fontSize = Math.min(width, height) * FONT_RATIO;
  1318. let metrics, char;
  1319. if (type === "check") {
  1320. metrics = {
  1321. width: 0.755 * fontSize,
  1322. height: 0.705 * fontSize
  1323. };
  1324. char = "\x33";
  1325. } else if (type === "disc") {
  1326. metrics = {
  1327. width: 0.791 * fontSize,
  1328. height: 0.705 * fontSize
  1329. };
  1330. char = "\x6C";
  1331. } else {
  1332. (0, _util.unreachable)(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
  1333. }
  1334. const xShift = (width - metrics.width) / 2;
  1335. const yShift = (height - metrics.height) / 2;
  1336. const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
  1337. const appearanceStreamDict = new _primitives.Dict(params.xref);
  1338. appearanceStreamDict.set("FormType", 1);
  1339. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  1340. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  1341. appearanceStreamDict.set("BBox", bbox);
  1342. appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
  1343. appearanceStreamDict.set("Length", appearance.length);
  1344. const resources = new _primitives.Dict(params.xref);
  1345. const font = new _primitives.Dict(params.xref);
  1346. font.set("PdfJsZaDb", this.fallbackFontDict);
  1347. resources.set("Font", font);
  1348. appearanceStreamDict.set("Resources", resources);
  1349. this.checkedAppearance = new _stream.StringStream(appearance);
  1350. this.checkedAppearance.dict = appearanceStreamDict;
  1351. this._streams.push(this.checkedAppearance);
  1352. }
  1353. _processCheckBox(params) {
  1354. const customAppearance = params.dict.get("AP");
  1355. if (!(0, _primitives.isDict)(customAppearance)) {
  1356. return;
  1357. }
  1358. const normalAppearance = customAppearance.get("N");
  1359. if (!(0, _primitives.isDict)(normalAppearance)) {
  1360. return;
  1361. }
  1362. const asValue = this._decodeFormValue(params.dict.get("AS"));
  1363. if (typeof asValue === "string") {
  1364. this.data.fieldValue = asValue;
  1365. }
  1366. const yes = this.data.fieldValue !== null && this.data.fieldValue !== "Off" ? this.data.fieldValue : "Yes";
  1367. const exportValues = normalAppearance.getKeys();
  1368. if (exportValues.length === 0) {
  1369. exportValues.push("Off", yes);
  1370. } else if (exportValues.length === 1) {
  1371. if (exportValues[0] === "Off") {
  1372. exportValues.push(yes);
  1373. } else {
  1374. exportValues.unshift("Off");
  1375. }
  1376. } else if (exportValues.includes(yes)) {
  1377. exportValues.length = 0;
  1378. exportValues.push("Off", yes);
  1379. } else {
  1380. const otherYes = exportValues.find(v => v !== "Off");
  1381. exportValues.length = 0;
  1382. exportValues.push("Off", otherYes);
  1383. }
  1384. if (!exportValues.includes(this.data.fieldValue)) {
  1385. this.data.fieldValue = "Off";
  1386. }
  1387. this.data.exportValue = exportValues[1];
  1388. this.checkedAppearance = normalAppearance.get(this.data.exportValue) || null;
  1389. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1390. if (this.checkedAppearance) {
  1391. this._streams.push(this.checkedAppearance);
  1392. } else {
  1393. this._getDefaultCheckedAppearance(params, "check");
  1394. }
  1395. if (this.uncheckedAppearance) {
  1396. this._streams.push(this.uncheckedAppearance);
  1397. }
  1398. this._fallbackFontDict = this.fallbackFontDict;
  1399. }
  1400. _processRadioButton(params) {
  1401. this.data.fieldValue = this.data.buttonValue = null;
  1402. const fieldParent = params.dict.get("Parent");
  1403. if ((0, _primitives.isDict)(fieldParent)) {
  1404. this.parent = params.dict.getRaw("Parent");
  1405. const fieldParentValue = fieldParent.get("V");
  1406. if ((0, _primitives.isName)(fieldParentValue)) {
  1407. this.data.fieldValue = this._decodeFormValue(fieldParentValue);
  1408. }
  1409. }
  1410. const appearanceStates = params.dict.get("AP");
  1411. if (!(0, _primitives.isDict)(appearanceStates)) {
  1412. return;
  1413. }
  1414. const normalAppearance = appearanceStates.get("N");
  1415. if (!(0, _primitives.isDict)(normalAppearance)) {
  1416. return;
  1417. }
  1418. for (const key of normalAppearance.getKeys()) {
  1419. if (key !== "Off") {
  1420. this.data.buttonValue = this._decodeFormValue(key);
  1421. break;
  1422. }
  1423. }
  1424. this.checkedAppearance = normalAppearance.get(this.data.buttonValue) || null;
  1425. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1426. if (this.checkedAppearance) {
  1427. this._streams.push(this.checkedAppearance);
  1428. } else {
  1429. this._getDefaultCheckedAppearance(params, "disc");
  1430. }
  1431. if (this.uncheckedAppearance) {
  1432. this._streams.push(this.uncheckedAppearance);
  1433. }
  1434. this._fallbackFontDict = this.fallbackFontDict;
  1435. }
  1436. _processPushButton(params) {
  1437. if (!params.dict.has("A") && !params.dict.has("AA") && !this.data.alternativeText) {
  1438. (0, _util.warn)("Push buttons without action dictionaries are not supported");
  1439. return;
  1440. }
  1441. this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
  1442. _catalog.Catalog.parseDestDictionary({
  1443. destDict: params.dict,
  1444. resultObj: this.data,
  1445. docBaseUrl: params.pdfManager.docBaseUrl
  1446. });
  1447. }
  1448. getFieldObject() {
  1449. let type = "button";
  1450. let exportValues;
  1451. if (this.data.checkBox) {
  1452. type = "checkbox";
  1453. exportValues = this.data.exportValue;
  1454. } else if (this.data.radioButton) {
  1455. type = "radiobutton";
  1456. exportValues = this.data.buttonValue;
  1457. }
  1458. return {
  1459. id: this.data.id,
  1460. value: this.data.fieldValue || "Off",
  1461. defaultValue: this.data.defaultFieldValue,
  1462. exportValues,
  1463. editable: !this.data.readOnly,
  1464. name: this.data.fieldName,
  1465. rect: this.data.rect,
  1466. hidden: this.data.hidden,
  1467. actions: this.data.actions,
  1468. page: this.data.pageIndex,
  1469. strokeColor: this.data.borderColor,
  1470. fillColor: this.data.backgroundColor,
  1471. type
  1472. };
  1473. }
  1474. get fallbackFontDict() {
  1475. const dict = new _primitives.Dict();
  1476. dict.set("BaseFont", _primitives.Name.get("ZapfDingbats"));
  1477. dict.set("Type", _primitives.Name.get("FallbackType"));
  1478. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  1479. dict.set("Encoding", _primitives.Name.get("ZapfDingbatsEncoding"));
  1480. return (0, _util.shadow)(this, "fallbackFontDict", dict);
  1481. }
  1482. }
  1483. class ChoiceWidgetAnnotation extends WidgetAnnotation {
  1484. constructor(params) {
  1485. super(params);
  1486. this.data.options = [];
  1487. const options = (0, _core_utils.getInheritableProperty)({
  1488. dict: params.dict,
  1489. key: "Opt"
  1490. });
  1491. if (Array.isArray(options)) {
  1492. const xref = params.xref;
  1493. for (let i = 0, ii = options.length; i < ii; i++) {
  1494. const option = xref.fetchIfRef(options[i]);
  1495. const isOptionArray = Array.isArray(option);
  1496. this.data.options[i] = {
  1497. exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
  1498. displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
  1499. };
  1500. }
  1501. }
  1502. if ((0, _util.isString)(this.data.fieldValue)) {
  1503. this.data.fieldValue = [this.data.fieldValue];
  1504. } else if (!this.data.fieldValue) {
  1505. this.data.fieldValue = [];
  1506. }
  1507. this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
  1508. this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
  1509. this._hasText = true;
  1510. }
  1511. getFieldObject() {
  1512. const type = this.data.combo ? "combobox" : "listbox";
  1513. const value = this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
  1514. return {
  1515. id: this.data.id,
  1516. value,
  1517. defaultValue: this.data.defaultFieldValue,
  1518. editable: !this.data.readOnly,
  1519. name: this.data.fieldName,
  1520. rect: this.data.rect,
  1521. numItems: this.data.fieldValue.length,
  1522. multipleSelection: this.data.multiSelect,
  1523. hidden: this.data.hidden,
  1524. actions: this.data.actions,
  1525. items: this.data.options,
  1526. page: this.data.pageIndex,
  1527. strokeColor: this.data.borderColor,
  1528. fillColor: this.data.backgroundColor,
  1529. type
  1530. };
  1531. }
  1532. }
  1533. class SignatureWidgetAnnotation extends WidgetAnnotation {
  1534. constructor(params) {
  1535. super(params);
  1536. this.data.fieldValue = null;
  1537. }
  1538. getFieldObject() {
  1539. return {
  1540. id: this.data.id,
  1541. value: null,
  1542. page: this.data.pageIndex,
  1543. type: "signature"
  1544. };
  1545. }
  1546. }
  1547. class TextAnnotation extends MarkupAnnotation {
  1548. constructor(parameters) {
  1549. const DEFAULT_ICON_SIZE = 22;
  1550. super(parameters);
  1551. const dict = parameters.dict;
  1552. this.data.annotationType = _util.AnnotationType.TEXT;
  1553. if (this.data.hasAppearance) {
  1554. this.data.name = "NoIcon";
  1555. } else {
  1556. this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
  1557. this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
  1558. this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
  1559. }
  1560. if (dict.has("State")) {
  1561. this.data.state = dict.get("State") || null;
  1562. this.data.stateModel = dict.get("StateModel") || null;
  1563. } else {
  1564. this.data.state = null;
  1565. this.data.stateModel = null;
  1566. }
  1567. }
  1568. }
  1569. class LinkAnnotation extends Annotation {
  1570. constructor(params) {
  1571. super(params);
  1572. this.data.annotationType = _util.AnnotationType.LINK;
  1573. const quadPoints = getQuadPoints(params.dict, this.rectangle);
  1574. if (quadPoints) {
  1575. this.data.quadPoints = quadPoints;
  1576. }
  1577. _catalog.Catalog.parseDestDictionary({
  1578. destDict: params.dict,
  1579. resultObj: this.data,
  1580. docBaseUrl: params.pdfManager.docBaseUrl
  1581. });
  1582. }
  1583. }
  1584. class PopupAnnotation extends Annotation {
  1585. constructor(parameters) {
  1586. super(parameters);
  1587. this.data.annotationType = _util.AnnotationType.POPUP;
  1588. let parentItem = parameters.dict.get("Parent");
  1589. if (!parentItem) {
  1590. (0, _util.warn)("Popup annotation has a missing or invalid parent annotation.");
  1591. return;
  1592. }
  1593. const parentSubtype = parentItem.get("Subtype");
  1594. this.data.parentType = (0, _primitives.isName)(parentSubtype) ? parentSubtype.name : null;
  1595. const rawParent = parameters.dict.getRaw("Parent");
  1596. this.data.parentId = (0, _primitives.isRef)(rawParent) ? rawParent.toString() : null;
  1597. const parentRect = parentItem.getArray("Rect");
  1598. if (Array.isArray(parentRect) && parentRect.length === 4) {
  1599. this.data.parentRect = _util.Util.normalizeRect(parentRect);
  1600. } else {
  1601. this.data.parentRect = [0, 0, 0, 0];
  1602. }
  1603. const rt = parentItem.get("RT");
  1604. if ((0, _primitives.isName)(rt, _util.AnnotationReplyType.GROUP)) {
  1605. parentItem = parentItem.get("IRT");
  1606. }
  1607. if (!parentItem.has("M")) {
  1608. this.data.modificationDate = null;
  1609. } else {
  1610. this.setModificationDate(parentItem.get("M"));
  1611. this.data.modificationDate = this.modificationDate;
  1612. }
  1613. if (!parentItem.has("C")) {
  1614. this.data.color = null;
  1615. } else {
  1616. this.setColor(parentItem.getArray("C"));
  1617. this.data.color = this.color;
  1618. }
  1619. if (!this.viewable) {
  1620. const parentFlags = parentItem.get("F");
  1621. if (this._isViewable(parentFlags)) {
  1622. this.setFlags(parentFlags);
  1623. }
  1624. }
  1625. this.setTitle(parentItem.get("T"));
  1626. this.data.titleObj = this._title;
  1627. this.setContents(parentItem.get("Contents"));
  1628. this.data.contentsObj = this._contents;
  1629. if (parentItem.has("RC")) {
  1630. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
  1631. }
  1632. }
  1633. }
  1634. class FreeTextAnnotation extends MarkupAnnotation {
  1635. constructor(parameters) {
  1636. super(parameters);
  1637. this.data.annotationType = _util.AnnotationType.FREETEXT;
  1638. }
  1639. }
  1640. class LineAnnotation extends MarkupAnnotation {
  1641. constructor(parameters) {
  1642. super(parameters);
  1643. this.data.annotationType = _util.AnnotationType.LINE;
  1644. const lineCoordinates = parameters.dict.getArray("L");
  1645. this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates);
  1646. if (!this.appearance) {
  1647. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1648. const strokeAlpha = parameters.dict.get("CA");
  1649. let fillColor = null,
  1650. interiorColor = parameters.dict.getArray("IC");
  1651. if (interiorColor) {
  1652. interiorColor = getRgbColor(interiorColor, null);
  1653. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  1654. }
  1655. const fillAlpha = fillColor ? strokeAlpha : null;
  1656. const borderWidth = this.borderStyle.width || 1,
  1657. borderAdjust = 2 * borderWidth;
  1658. const bbox = [this.data.lineCoordinates[0] - borderAdjust, this.data.lineCoordinates[1] - borderAdjust, this.data.lineCoordinates[2] + borderAdjust, this.data.lineCoordinates[3] + borderAdjust];
  1659. if (!_util.Util.intersect(this.rectangle, bbox)) {
  1660. this.rectangle = bbox;
  1661. }
  1662. this._setDefaultAppearance({
  1663. xref: parameters.xref,
  1664. extra: `${borderWidth} w`,
  1665. strokeColor,
  1666. fillColor,
  1667. strokeAlpha,
  1668. fillAlpha,
  1669. pointsCallback: (buffer, points) => {
  1670. buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`, `${lineCoordinates[2]} ${lineCoordinates[3]} l`, "S");
  1671. return [points[0].x - borderWidth, points[1].x + borderWidth, points[3].y - borderWidth, points[1].y + borderWidth];
  1672. }
  1673. });
  1674. }
  1675. }
  1676. }
  1677. class SquareAnnotation extends MarkupAnnotation {
  1678. constructor(parameters) {
  1679. super(parameters);
  1680. this.data.annotationType = _util.AnnotationType.SQUARE;
  1681. if (!this.appearance) {
  1682. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1683. const strokeAlpha = parameters.dict.get("CA");
  1684. let fillColor = null,
  1685. interiorColor = parameters.dict.getArray("IC");
  1686. if (interiorColor) {
  1687. interiorColor = getRgbColor(interiorColor, null);
  1688. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  1689. }
  1690. const fillAlpha = fillColor ? strokeAlpha : null;
  1691. if (this.borderStyle.width === 0 && !fillColor) {
  1692. return;
  1693. }
  1694. this._setDefaultAppearance({
  1695. xref: parameters.xref,
  1696. extra: `${this.borderStyle.width} w`,
  1697. strokeColor,
  1698. fillColor,
  1699. strokeAlpha,
  1700. fillAlpha,
  1701. pointsCallback: (buffer, points) => {
  1702. const x = points[2].x + this.borderStyle.width / 2;
  1703. const y = points[2].y + this.borderStyle.width / 2;
  1704. const width = points[3].x - points[2].x - this.borderStyle.width;
  1705. const height = points[1].y - points[3].y - this.borderStyle.width;
  1706. buffer.push(`${x} ${y} ${width} ${height} re`);
  1707. if (fillColor) {
  1708. buffer.push("B");
  1709. } else {
  1710. buffer.push("S");
  1711. }
  1712. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1713. }
  1714. });
  1715. }
  1716. }
  1717. }
  1718. class CircleAnnotation extends MarkupAnnotation {
  1719. constructor(parameters) {
  1720. super(parameters);
  1721. this.data.annotationType = _util.AnnotationType.CIRCLE;
  1722. if (!this.appearance) {
  1723. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1724. const strokeAlpha = parameters.dict.get("CA");
  1725. let fillColor = null;
  1726. let interiorColor = parameters.dict.getArray("IC");
  1727. if (interiorColor) {
  1728. interiorColor = getRgbColor(interiorColor, null);
  1729. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  1730. }
  1731. const fillAlpha = fillColor ? strokeAlpha : null;
  1732. if (this.borderStyle.width === 0 && !fillColor) {
  1733. return;
  1734. }
  1735. const controlPointsDistance = 4 / 3 * Math.tan(Math.PI / (2 * 4));
  1736. this._setDefaultAppearance({
  1737. xref: parameters.xref,
  1738. extra: `${this.borderStyle.width} w`,
  1739. strokeColor,
  1740. fillColor,
  1741. strokeAlpha,
  1742. fillAlpha,
  1743. pointsCallback: (buffer, points) => {
  1744. const x0 = points[0].x + this.borderStyle.width / 2;
  1745. const y0 = points[0].y - this.borderStyle.width / 2;
  1746. const x1 = points[3].x - this.borderStyle.width / 2;
  1747. const y1 = points[3].y + this.borderStyle.width / 2;
  1748. const xMid = x0 + (x1 - x0) / 2;
  1749. const yMid = y0 + (y1 - y0) / 2;
  1750. const xOffset = (x1 - x0) / 2 * controlPointsDistance;
  1751. const yOffset = (y1 - y0) / 2 * controlPointsDistance;
  1752. buffer.push(`${xMid} ${y1} m`, `${xMid + xOffset} ${y1} ${x1} ${yMid + yOffset} ${x1} ${yMid} c`, `${x1} ${yMid - yOffset} ${xMid + xOffset} ${y0} ${xMid} ${y0} c`, `${xMid - xOffset} ${y0} ${x0} ${yMid - yOffset} ${x0} ${yMid} c`, `${x0} ${yMid + yOffset} ${xMid - xOffset} ${y1} ${xMid} ${y1} c`, "h");
  1753. if (fillColor) {
  1754. buffer.push("B");
  1755. } else {
  1756. buffer.push("S");
  1757. }
  1758. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1759. }
  1760. });
  1761. }
  1762. }
  1763. }
  1764. class PolylineAnnotation extends MarkupAnnotation {
  1765. constructor(parameters) {
  1766. super(parameters);
  1767. this.data.annotationType = _util.AnnotationType.POLYLINE;
  1768. this.data.vertices = [];
  1769. const rawVertices = parameters.dict.getArray("Vertices");
  1770. if (!Array.isArray(rawVertices)) {
  1771. return;
  1772. }
  1773. for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
  1774. this.data.vertices.push({
  1775. x: rawVertices[i],
  1776. y: rawVertices[i + 1]
  1777. });
  1778. }
  1779. if (!this.appearance) {
  1780. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1781. const strokeAlpha = parameters.dict.get("CA");
  1782. const borderWidth = this.borderStyle.width || 1,
  1783. borderAdjust = 2 * borderWidth;
  1784. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  1785. for (const vertex of this.data.vertices) {
  1786. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  1787. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  1788. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  1789. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  1790. }
  1791. if (!_util.Util.intersect(this.rectangle, bbox)) {
  1792. this.rectangle = bbox;
  1793. }
  1794. this._setDefaultAppearance({
  1795. xref: parameters.xref,
  1796. extra: `${borderWidth} w`,
  1797. strokeColor,
  1798. strokeAlpha,
  1799. pointsCallback: (buffer, points) => {
  1800. const vertices = this.data.vertices;
  1801. for (let i = 0, ii = vertices.length; i < ii; i++) {
  1802. buffer.push(`${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`);
  1803. }
  1804. buffer.push("S");
  1805. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1806. }
  1807. });
  1808. }
  1809. }
  1810. }
  1811. class PolygonAnnotation extends PolylineAnnotation {
  1812. constructor(parameters) {
  1813. super(parameters);
  1814. this.data.annotationType = _util.AnnotationType.POLYGON;
  1815. }
  1816. }
  1817. class CaretAnnotation extends MarkupAnnotation {
  1818. constructor(parameters) {
  1819. super(parameters);
  1820. this.data.annotationType = _util.AnnotationType.CARET;
  1821. }
  1822. }
  1823. class InkAnnotation extends MarkupAnnotation {
  1824. constructor(parameters) {
  1825. super(parameters);
  1826. this.data.annotationType = _util.AnnotationType.INK;
  1827. this.data.inkLists = [];
  1828. const rawInkLists = parameters.dict.getArray("InkList");
  1829. if (!Array.isArray(rawInkLists)) {
  1830. return;
  1831. }
  1832. const xref = parameters.xref;
  1833. for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
  1834. this.data.inkLists.push([]);
  1835. for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
  1836. this.data.inkLists[i].push({
  1837. x: xref.fetchIfRef(rawInkLists[i][j]),
  1838. y: xref.fetchIfRef(rawInkLists[i][j + 1])
  1839. });
  1840. }
  1841. }
  1842. if (!this.appearance) {
  1843. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1844. const strokeAlpha = parameters.dict.get("CA");
  1845. const borderWidth = this.borderStyle.width || 1,
  1846. borderAdjust = 2 * borderWidth;
  1847. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  1848. for (const inkLists of this.data.inkLists) {
  1849. for (const vertex of inkLists) {
  1850. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  1851. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  1852. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  1853. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  1854. }
  1855. }
  1856. if (!_util.Util.intersect(this.rectangle, bbox)) {
  1857. this.rectangle = bbox;
  1858. }
  1859. this._setDefaultAppearance({
  1860. xref: parameters.xref,
  1861. extra: `${borderWidth} w`,
  1862. strokeColor,
  1863. strokeAlpha,
  1864. pointsCallback: (buffer, points) => {
  1865. for (const inkList of this.data.inkLists) {
  1866. for (let i = 0, ii = inkList.length; i < ii; i++) {
  1867. buffer.push(`${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`);
  1868. }
  1869. buffer.push("S");
  1870. }
  1871. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1872. }
  1873. });
  1874. }
  1875. }
  1876. }
  1877. class HighlightAnnotation extends MarkupAnnotation {
  1878. constructor(parameters) {
  1879. super(parameters);
  1880. this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
  1881. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1882. if (quadPoints) {
  1883. const resources = this.appearance && this.appearance.dict.get("Resources");
  1884. if (!this.appearance || !(resources && resources.has("ExtGState"))) {
  1885. if (this.appearance) {
  1886. (0, _util.warn)("HighlightAnnotation - ignoring built-in appearance stream.");
  1887. }
  1888. const fillColor = this.color ? Array.from(this.color).map(c => c / 255) : [1, 1, 0];
  1889. const fillAlpha = parameters.dict.get("CA");
  1890. this._setDefaultAppearance({
  1891. xref: parameters.xref,
  1892. fillColor,
  1893. blendMode: "Multiply",
  1894. fillAlpha,
  1895. pointsCallback: (buffer, points) => {
  1896. buffer.push(`${points[0].x} ${points[0].y} m`, `${points[1].x} ${points[1].y} l`, `${points[3].x} ${points[3].y} l`, `${points[2].x} ${points[2].y} l`, "f");
  1897. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1898. }
  1899. });
  1900. }
  1901. } else {
  1902. this.data.hasPopup = false;
  1903. }
  1904. }
  1905. }
  1906. class UnderlineAnnotation extends MarkupAnnotation {
  1907. constructor(parameters) {
  1908. super(parameters);
  1909. this.data.annotationType = _util.AnnotationType.UNDERLINE;
  1910. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1911. if (quadPoints) {
  1912. if (!this.appearance) {
  1913. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1914. const strokeAlpha = parameters.dict.get("CA");
  1915. this._setDefaultAppearance({
  1916. xref: parameters.xref,
  1917. extra: "[] 0 d 1 w",
  1918. strokeColor,
  1919. strokeAlpha,
  1920. pointsCallback: (buffer, points) => {
  1921. buffer.push(`${points[2].x} ${points[2].y} m`, `${points[3].x} ${points[3].y} l`, "S");
  1922. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1923. }
  1924. });
  1925. }
  1926. } else {
  1927. this.data.hasPopup = false;
  1928. }
  1929. }
  1930. }
  1931. class SquigglyAnnotation extends MarkupAnnotation {
  1932. constructor(parameters) {
  1933. super(parameters);
  1934. this.data.annotationType = _util.AnnotationType.SQUIGGLY;
  1935. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1936. if (quadPoints) {
  1937. if (!this.appearance) {
  1938. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1939. const strokeAlpha = parameters.dict.get("CA");
  1940. this._setDefaultAppearance({
  1941. xref: parameters.xref,
  1942. extra: "[] 0 d 1 w",
  1943. strokeColor,
  1944. strokeAlpha,
  1945. pointsCallback: (buffer, points) => {
  1946. const dy = (points[0].y - points[2].y) / 6;
  1947. let shift = dy;
  1948. let x = points[2].x;
  1949. const y = points[2].y;
  1950. const xEnd = points[3].x;
  1951. buffer.push(`${x} ${y + shift} m`);
  1952. do {
  1953. x += 2;
  1954. shift = shift === 0 ? dy : 0;
  1955. buffer.push(`${x} ${y + shift} l`);
  1956. } while (x < xEnd);
  1957. buffer.push("S");
  1958. return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
  1959. }
  1960. });
  1961. }
  1962. } else {
  1963. this.data.hasPopup = false;
  1964. }
  1965. }
  1966. }
  1967. class StrikeOutAnnotation extends MarkupAnnotation {
  1968. constructor(parameters) {
  1969. super(parameters);
  1970. this.data.annotationType = _util.AnnotationType.STRIKEOUT;
  1971. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1972. if (quadPoints) {
  1973. if (!this.appearance) {
  1974. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1975. const strokeAlpha = parameters.dict.get("CA");
  1976. this._setDefaultAppearance({
  1977. xref: parameters.xref,
  1978. extra: "[] 0 d 1 w",
  1979. strokeColor,
  1980. strokeAlpha,
  1981. pointsCallback: (buffer, points) => {
  1982. buffer.push(`${(points[0].x + points[2].x) / 2} ` + `${(points[0].y + points[2].y) / 2} m`, `${(points[1].x + points[3].x) / 2} ` + `${(points[1].y + points[3].y) / 2} l`, "S");
  1983. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1984. }
  1985. });
  1986. }
  1987. } else {
  1988. this.data.hasPopup = false;
  1989. }
  1990. }
  1991. }
  1992. class StampAnnotation extends MarkupAnnotation {
  1993. constructor(parameters) {
  1994. super(parameters);
  1995. this.data.annotationType = _util.AnnotationType.STAMP;
  1996. }
  1997. }
  1998. class FileAttachmentAnnotation extends MarkupAnnotation {
  1999. constructor(parameters) {
  2000. super(parameters);
  2001. const file = new _file_spec.FileSpec(parameters.dict.get("FS"), parameters.xref);
  2002. this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
  2003. this.data.file = file.serializable;
  2004. }
  2005. }