annotation.js 66 KB

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