annotation.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328
  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.id, 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.id, 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.includes(this.data.fieldValue)) {
  1278. this.data.fieldValue = null;
  1279. }
  1280. if (exportValues.length !== 2) {
  1281. return;
  1282. }
  1283. this.data.exportValue = exportValues[0] === "Off" ? exportValues[1] : exportValues[0];
  1284. this.checkedAppearance = normalAppearance.get(this.data.exportValue);
  1285. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1286. this._streams.push(this.checkedAppearance);
  1287. if (this.uncheckedAppearance) {
  1288. this._streams.push(this.uncheckedAppearance);
  1289. }
  1290. this._fallbackFontDict = this.fallbackFontDict;
  1291. }
  1292. _processRadioButton(params) {
  1293. this.data.fieldValue = this.data.buttonValue = null;
  1294. const fieldParent = params.dict.get("Parent");
  1295. if ((0, _primitives.isDict)(fieldParent)) {
  1296. this.parent = params.dict.getRaw("Parent");
  1297. const fieldParentValue = fieldParent.get("V");
  1298. if ((0, _primitives.isName)(fieldParentValue)) {
  1299. this.data.fieldValue = this._decodeFormValue(fieldParentValue);
  1300. }
  1301. }
  1302. const appearanceStates = params.dict.get("AP");
  1303. if (!(0, _primitives.isDict)(appearanceStates)) {
  1304. return;
  1305. }
  1306. const normalAppearance = appearanceStates.get("N");
  1307. if (!(0, _primitives.isDict)(normalAppearance)) {
  1308. return;
  1309. }
  1310. for (const key of normalAppearance.getKeys()) {
  1311. if (key !== "Off") {
  1312. this.data.buttonValue = this._decodeFormValue(key);
  1313. break;
  1314. }
  1315. }
  1316. this.checkedAppearance = normalAppearance.get(this.data.buttonValue);
  1317. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1318. this._streams.push(this.checkedAppearance);
  1319. if (this.uncheckedAppearance) {
  1320. this._streams.push(this.uncheckedAppearance);
  1321. }
  1322. this._fallbackFontDict = this.fallbackFontDict;
  1323. }
  1324. _processPushButton(params) {
  1325. if (!params.dict.has("A") && !params.dict.has("AA") && !this.data.alternativeText) {
  1326. (0, _util.warn)("Push buttons without action dictionaries are not supported");
  1327. return;
  1328. }
  1329. this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
  1330. _catalog.Catalog.parseDestDictionary({
  1331. destDict: params.dict,
  1332. resultObj: this.data,
  1333. docBaseUrl: params.pdfManager.docBaseUrl
  1334. });
  1335. }
  1336. getFieldObject() {
  1337. let type = "button";
  1338. let exportValues;
  1339. if (this.data.checkBox) {
  1340. type = "checkbox";
  1341. exportValues = this.data.exportValue;
  1342. } else if (this.data.radioButton) {
  1343. type = "radiobutton";
  1344. exportValues = this.data.buttonValue;
  1345. }
  1346. return {
  1347. id: this.data.id,
  1348. value: this.data.fieldValue || "Off",
  1349. defaultValue: this.data.defaultFieldValue,
  1350. exportValues,
  1351. editable: !this.data.readOnly,
  1352. name: this.data.fieldName,
  1353. rect: this.data.rect,
  1354. hidden: this.data.hidden,
  1355. actions: this.data.actions,
  1356. page: this.data.pageIndex,
  1357. type
  1358. };
  1359. }
  1360. get fallbackFontDict() {
  1361. const dict = new _primitives.Dict();
  1362. dict.set("BaseFont", _primitives.Name.get("ZapfDingbats"));
  1363. dict.set("Type", _primitives.Name.get("FallbackType"));
  1364. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  1365. dict.set("Encoding", _primitives.Name.get("ZapfDingbatsEncoding"));
  1366. return (0, _util.shadow)(this, "fallbackFontDict", dict);
  1367. }
  1368. }
  1369. class ChoiceWidgetAnnotation extends WidgetAnnotation {
  1370. constructor(params) {
  1371. super(params);
  1372. this.data.options = [];
  1373. const options = (0, _core_utils.getInheritableProperty)({
  1374. dict: params.dict,
  1375. key: "Opt"
  1376. });
  1377. if (Array.isArray(options)) {
  1378. const xref = params.xref;
  1379. for (let i = 0, ii = options.length; i < ii; i++) {
  1380. const option = xref.fetchIfRef(options[i]);
  1381. const isOptionArray = Array.isArray(option);
  1382. this.data.options[i] = {
  1383. exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
  1384. displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
  1385. };
  1386. }
  1387. }
  1388. if ((0, _util.isString)(this.data.fieldValue)) {
  1389. this.data.fieldValue = [this.data.fieldValue];
  1390. } else if (!this.data.fieldValue) {
  1391. this.data.fieldValue = [];
  1392. }
  1393. this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
  1394. this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
  1395. this._hasText = true;
  1396. }
  1397. getFieldObject() {
  1398. const type = this.data.combo ? "combobox" : "listbox";
  1399. const value = this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
  1400. return {
  1401. id: this.data.id,
  1402. value,
  1403. defaultValue: this.data.defaultFieldValue,
  1404. editable: !this.data.readOnly,
  1405. name: this.data.fieldName,
  1406. rect: this.data.rect,
  1407. numItems: this.data.fieldValue.length,
  1408. multipleSelection: this.data.multiSelect,
  1409. hidden: this.data.hidden,
  1410. actions: this.data.actions,
  1411. items: this.data.options,
  1412. page: this.data.pageIndex,
  1413. type
  1414. };
  1415. }
  1416. }
  1417. class SignatureWidgetAnnotation extends WidgetAnnotation {
  1418. constructor(params) {
  1419. super(params);
  1420. this.data.fieldValue = null;
  1421. }
  1422. getFieldObject() {
  1423. return {
  1424. id: this.data.id,
  1425. value: null,
  1426. page: this.data.pageIndex,
  1427. type: "signature"
  1428. };
  1429. }
  1430. }
  1431. class TextAnnotation extends MarkupAnnotation {
  1432. constructor(parameters) {
  1433. const DEFAULT_ICON_SIZE = 22;
  1434. super(parameters);
  1435. const dict = parameters.dict;
  1436. this.data.annotationType = _util.AnnotationType.TEXT;
  1437. if (this.data.hasAppearance) {
  1438. this.data.name = "NoIcon";
  1439. } else {
  1440. this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
  1441. this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
  1442. this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
  1443. }
  1444. if (dict.has("State")) {
  1445. this.data.state = dict.get("State") || null;
  1446. this.data.stateModel = dict.get("StateModel") || null;
  1447. } else {
  1448. this.data.state = null;
  1449. this.data.stateModel = null;
  1450. }
  1451. }
  1452. }
  1453. class LinkAnnotation extends Annotation {
  1454. constructor(params) {
  1455. super(params);
  1456. this.data.annotationType = _util.AnnotationType.LINK;
  1457. const quadPoints = getQuadPoints(params.dict, this.rectangle);
  1458. if (quadPoints) {
  1459. this.data.quadPoints = quadPoints;
  1460. }
  1461. _catalog.Catalog.parseDestDictionary({
  1462. destDict: params.dict,
  1463. resultObj: this.data,
  1464. docBaseUrl: params.pdfManager.docBaseUrl
  1465. });
  1466. }
  1467. }
  1468. class PopupAnnotation extends Annotation {
  1469. constructor(parameters) {
  1470. super(parameters);
  1471. this.data.annotationType = _util.AnnotationType.POPUP;
  1472. let parentItem = parameters.dict.get("Parent");
  1473. if (!parentItem) {
  1474. (0, _util.warn)("Popup annotation has a missing or invalid parent annotation.");
  1475. return;
  1476. }
  1477. const parentSubtype = parentItem.get("Subtype");
  1478. this.data.parentType = (0, _primitives.isName)(parentSubtype) ? parentSubtype.name : null;
  1479. const rawParent = parameters.dict.getRaw("Parent");
  1480. this.data.parentId = (0, _primitives.isRef)(rawParent) ? rawParent.toString() : null;
  1481. const parentRect = parentItem.getArray("Rect");
  1482. if (Array.isArray(parentRect) && parentRect.length === 4) {
  1483. this.data.parentRect = _util.Util.normalizeRect(parentRect);
  1484. } else {
  1485. this.data.parentRect = [0, 0, 0, 0];
  1486. }
  1487. const rt = parentItem.get("RT");
  1488. if ((0, _primitives.isName)(rt, _util.AnnotationReplyType.GROUP)) {
  1489. parentItem = parentItem.get("IRT");
  1490. }
  1491. if (!parentItem.has("M")) {
  1492. this.data.modificationDate = null;
  1493. } else {
  1494. this.setModificationDate(parentItem.get("M"));
  1495. this.data.modificationDate = this.modificationDate;
  1496. }
  1497. if (!parentItem.has("C")) {
  1498. this.data.color = null;
  1499. } else {
  1500. this.setColor(parentItem.getArray("C"));
  1501. this.data.color = this.color;
  1502. }
  1503. if (!this.viewable) {
  1504. const parentFlags = parentItem.get("F");
  1505. if (this._isViewable(parentFlags)) {
  1506. this.setFlags(parentFlags);
  1507. }
  1508. }
  1509. this.data.title = (0, _util.stringToPDFString)(parentItem.get("T") || "");
  1510. this.data.contents = (0, _util.stringToPDFString)(parentItem.get("Contents") || "");
  1511. }
  1512. }
  1513. class FreeTextAnnotation extends MarkupAnnotation {
  1514. constructor(parameters) {
  1515. super(parameters);
  1516. this.data.annotationType = _util.AnnotationType.FREETEXT;
  1517. }
  1518. }
  1519. class LineAnnotation extends MarkupAnnotation {
  1520. constructor(parameters) {
  1521. super(parameters);
  1522. this.data.annotationType = _util.AnnotationType.LINE;
  1523. const lineCoordinates = parameters.dict.getArray("L");
  1524. this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates);
  1525. if (!this.appearance) {
  1526. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1527. const strokeAlpha = parameters.dict.get("CA");
  1528. let fillColor = null,
  1529. interiorColor = parameters.dict.getArray("IC");
  1530. if (interiorColor) {
  1531. interiorColor = getRgbColor(interiorColor);
  1532. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  1533. }
  1534. const fillAlpha = fillColor ? strokeAlpha : null;
  1535. const borderWidth = this.borderStyle.width || 1,
  1536. borderAdjust = 2 * borderWidth;
  1537. const bbox = [this.data.lineCoordinates[0] - borderAdjust, this.data.lineCoordinates[1] - borderAdjust, this.data.lineCoordinates[2] + borderAdjust, this.data.lineCoordinates[3] + borderAdjust];
  1538. if (!_util.Util.intersect(this.rectangle, bbox)) {
  1539. this.rectangle = bbox;
  1540. }
  1541. this._setDefaultAppearance({
  1542. xref: parameters.xref,
  1543. extra: `${borderWidth} w`,
  1544. strokeColor,
  1545. fillColor,
  1546. strokeAlpha,
  1547. fillAlpha,
  1548. pointsCallback: (buffer, points) => {
  1549. buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`, `${lineCoordinates[2]} ${lineCoordinates[3]} l`, "S");
  1550. return [points[0].x - borderWidth, points[1].x + borderWidth, points[3].y - borderWidth, points[1].y + borderWidth];
  1551. }
  1552. });
  1553. }
  1554. }
  1555. }
  1556. class SquareAnnotation extends MarkupAnnotation {
  1557. constructor(parameters) {
  1558. super(parameters);
  1559. this.data.annotationType = _util.AnnotationType.SQUARE;
  1560. if (!this.appearance) {
  1561. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1562. const strokeAlpha = parameters.dict.get("CA");
  1563. let fillColor = null,
  1564. interiorColor = parameters.dict.getArray("IC");
  1565. if (interiorColor) {
  1566. interiorColor = getRgbColor(interiorColor);
  1567. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  1568. }
  1569. const fillAlpha = fillColor ? strokeAlpha : null;
  1570. this._setDefaultAppearance({
  1571. xref: parameters.xref,
  1572. extra: `${this.borderStyle.width} w`,
  1573. strokeColor,
  1574. fillColor,
  1575. strokeAlpha,
  1576. fillAlpha,
  1577. pointsCallback: (buffer, points) => {
  1578. const x = points[2].x + this.borderStyle.width / 2;
  1579. const y = points[2].y + this.borderStyle.width / 2;
  1580. const width = points[3].x - points[2].x - this.borderStyle.width;
  1581. const height = points[1].y - points[3].y - this.borderStyle.width;
  1582. buffer.push(`${x} ${y} ${width} ${height} re`);
  1583. if (fillColor) {
  1584. buffer.push("B");
  1585. } else {
  1586. buffer.push("S");
  1587. }
  1588. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1589. }
  1590. });
  1591. }
  1592. }
  1593. }
  1594. class CircleAnnotation extends MarkupAnnotation {
  1595. constructor(parameters) {
  1596. super(parameters);
  1597. this.data.annotationType = _util.AnnotationType.CIRCLE;
  1598. if (!this.appearance) {
  1599. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1600. const strokeAlpha = parameters.dict.get("CA");
  1601. let fillColor = null;
  1602. let interiorColor = parameters.dict.getArray("IC");
  1603. if (interiorColor) {
  1604. interiorColor = getRgbColor(interiorColor);
  1605. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  1606. }
  1607. const fillAlpha = fillColor ? strokeAlpha : null;
  1608. const controlPointsDistance = 4 / 3 * Math.tan(Math.PI / (2 * 4));
  1609. this._setDefaultAppearance({
  1610. xref: parameters.xref,
  1611. extra: `${this.borderStyle.width} w`,
  1612. strokeColor,
  1613. fillColor,
  1614. strokeAlpha,
  1615. fillAlpha,
  1616. pointsCallback: (buffer, points) => {
  1617. const x0 = points[0].x + this.borderStyle.width / 2;
  1618. const y0 = points[0].y - this.borderStyle.width / 2;
  1619. const x1 = points[3].x - this.borderStyle.width / 2;
  1620. const y1 = points[3].y + this.borderStyle.width / 2;
  1621. const xMid = x0 + (x1 - x0) / 2;
  1622. const yMid = y0 + (y1 - y0) / 2;
  1623. const xOffset = (x1 - x0) / 2 * controlPointsDistance;
  1624. const yOffset = (y1 - y0) / 2 * controlPointsDistance;
  1625. 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");
  1626. if (fillColor) {
  1627. buffer.push("B");
  1628. } else {
  1629. buffer.push("S");
  1630. }
  1631. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1632. }
  1633. });
  1634. }
  1635. }
  1636. }
  1637. class PolylineAnnotation extends MarkupAnnotation {
  1638. constructor(parameters) {
  1639. super(parameters);
  1640. this.data.annotationType = _util.AnnotationType.POLYLINE;
  1641. this.data.vertices = [];
  1642. const rawVertices = parameters.dict.getArray("Vertices");
  1643. if (!Array.isArray(rawVertices)) {
  1644. return;
  1645. }
  1646. for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
  1647. this.data.vertices.push({
  1648. x: rawVertices[i],
  1649. y: rawVertices[i + 1]
  1650. });
  1651. }
  1652. if (!this.appearance) {
  1653. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1654. const strokeAlpha = parameters.dict.get("CA");
  1655. const borderWidth = this.borderStyle.width || 1,
  1656. borderAdjust = 2 * borderWidth;
  1657. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  1658. for (const vertex of this.data.vertices) {
  1659. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  1660. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  1661. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  1662. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  1663. }
  1664. if (!_util.Util.intersect(this.rectangle, bbox)) {
  1665. this.rectangle = bbox;
  1666. }
  1667. this._setDefaultAppearance({
  1668. xref: parameters.xref,
  1669. extra: `${borderWidth} w`,
  1670. strokeColor,
  1671. strokeAlpha,
  1672. pointsCallback: (buffer, points) => {
  1673. const vertices = this.data.vertices;
  1674. for (let i = 0, ii = vertices.length; i < ii; i++) {
  1675. buffer.push(`${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`);
  1676. }
  1677. buffer.push("S");
  1678. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1679. }
  1680. });
  1681. }
  1682. }
  1683. }
  1684. class PolygonAnnotation extends PolylineAnnotation {
  1685. constructor(parameters) {
  1686. super(parameters);
  1687. this.data.annotationType = _util.AnnotationType.POLYGON;
  1688. }
  1689. }
  1690. class CaretAnnotation extends MarkupAnnotation {
  1691. constructor(parameters) {
  1692. super(parameters);
  1693. this.data.annotationType = _util.AnnotationType.CARET;
  1694. }
  1695. }
  1696. class InkAnnotation extends MarkupAnnotation {
  1697. constructor(parameters) {
  1698. super(parameters);
  1699. this.data.annotationType = _util.AnnotationType.INK;
  1700. this.data.inkLists = [];
  1701. const rawInkLists = parameters.dict.getArray("InkList");
  1702. if (!Array.isArray(rawInkLists)) {
  1703. return;
  1704. }
  1705. const xref = parameters.xref;
  1706. for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
  1707. this.data.inkLists.push([]);
  1708. for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
  1709. this.data.inkLists[i].push({
  1710. x: xref.fetchIfRef(rawInkLists[i][j]),
  1711. y: xref.fetchIfRef(rawInkLists[i][j + 1])
  1712. });
  1713. }
  1714. }
  1715. if (!this.appearance) {
  1716. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1717. const strokeAlpha = parameters.dict.get("CA");
  1718. const borderWidth = this.borderStyle.width || 1,
  1719. borderAdjust = 2 * borderWidth;
  1720. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  1721. for (const inkLists of this.data.inkLists) {
  1722. for (const vertex of inkLists) {
  1723. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  1724. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  1725. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  1726. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  1727. }
  1728. }
  1729. if (!_util.Util.intersect(this.rectangle, bbox)) {
  1730. this.rectangle = bbox;
  1731. }
  1732. this._setDefaultAppearance({
  1733. xref: parameters.xref,
  1734. extra: `${borderWidth} w`,
  1735. strokeColor,
  1736. strokeAlpha,
  1737. pointsCallback: (buffer, points) => {
  1738. for (const inkList of this.data.inkLists) {
  1739. for (let i = 0, ii = inkList.length; i < ii; i++) {
  1740. buffer.push(`${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`);
  1741. }
  1742. buffer.push("S");
  1743. }
  1744. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1745. }
  1746. });
  1747. }
  1748. }
  1749. }
  1750. class HighlightAnnotation extends MarkupAnnotation {
  1751. constructor(parameters) {
  1752. super(parameters);
  1753. this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
  1754. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1755. if (quadPoints) {
  1756. const resources = this.appearance && this.appearance.dict.get("Resources");
  1757. if (!this.appearance || !(resources && resources.has("ExtGState"))) {
  1758. if (this.appearance) {
  1759. (0, _util.warn)("HighlightAnnotation - ignoring built-in appearance stream.");
  1760. }
  1761. const fillColor = this.color ? Array.from(this.color).map(c => c / 255) : [1, 1, 0];
  1762. const fillAlpha = parameters.dict.get("CA");
  1763. this._setDefaultAppearance({
  1764. xref: parameters.xref,
  1765. fillColor,
  1766. blendMode: "Multiply",
  1767. fillAlpha,
  1768. pointsCallback: (buffer, points) => {
  1769. 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");
  1770. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1771. }
  1772. });
  1773. }
  1774. } else {
  1775. this.data.hasPopup = false;
  1776. }
  1777. }
  1778. }
  1779. class UnderlineAnnotation extends MarkupAnnotation {
  1780. constructor(parameters) {
  1781. super(parameters);
  1782. this.data.annotationType = _util.AnnotationType.UNDERLINE;
  1783. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1784. if (quadPoints) {
  1785. if (!this.appearance) {
  1786. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1787. const strokeAlpha = parameters.dict.get("CA");
  1788. this._setDefaultAppearance({
  1789. xref: parameters.xref,
  1790. extra: "[] 0 d 1 w",
  1791. strokeColor,
  1792. strokeAlpha,
  1793. pointsCallback: (buffer, points) => {
  1794. buffer.push(`${points[2].x} ${points[2].y} m`, `${points[3].x} ${points[3].y} l`, "S");
  1795. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1796. }
  1797. });
  1798. }
  1799. } else {
  1800. this.data.hasPopup = false;
  1801. }
  1802. }
  1803. }
  1804. class SquigglyAnnotation extends MarkupAnnotation {
  1805. constructor(parameters) {
  1806. super(parameters);
  1807. this.data.annotationType = _util.AnnotationType.SQUIGGLY;
  1808. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1809. if (quadPoints) {
  1810. if (!this.appearance) {
  1811. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1812. const strokeAlpha = parameters.dict.get("CA");
  1813. this._setDefaultAppearance({
  1814. xref: parameters.xref,
  1815. extra: "[] 0 d 1 w",
  1816. strokeColor,
  1817. strokeAlpha,
  1818. pointsCallback: (buffer, points) => {
  1819. const dy = (points[0].y - points[2].y) / 6;
  1820. let shift = dy;
  1821. let x = points[2].x;
  1822. const y = points[2].y;
  1823. const xEnd = points[3].x;
  1824. buffer.push(`${x} ${y + shift} m`);
  1825. do {
  1826. x += 2;
  1827. shift = shift === 0 ? dy : 0;
  1828. buffer.push(`${x} ${y + shift} l`);
  1829. } while (x < xEnd);
  1830. buffer.push("S");
  1831. return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
  1832. }
  1833. });
  1834. }
  1835. } else {
  1836. this.data.hasPopup = false;
  1837. }
  1838. }
  1839. }
  1840. class StrikeOutAnnotation extends MarkupAnnotation {
  1841. constructor(parameters) {
  1842. super(parameters);
  1843. this.data.annotationType = _util.AnnotationType.STRIKEOUT;
  1844. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  1845. if (quadPoints) {
  1846. if (!this.appearance) {
  1847. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  1848. const strokeAlpha = parameters.dict.get("CA");
  1849. this._setDefaultAppearance({
  1850. xref: parameters.xref,
  1851. extra: "[] 0 d 1 w",
  1852. strokeColor,
  1853. strokeAlpha,
  1854. pointsCallback: (buffer, points) => {
  1855. 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");
  1856. return [points[0].x, points[1].x, points[3].y, points[1].y];
  1857. }
  1858. });
  1859. }
  1860. } else {
  1861. this.data.hasPopup = false;
  1862. }
  1863. }
  1864. }
  1865. class StampAnnotation extends MarkupAnnotation {
  1866. constructor(parameters) {
  1867. super(parameters);
  1868. this.data.annotationType = _util.AnnotationType.STAMP;
  1869. }
  1870. }
  1871. class FileAttachmentAnnotation extends MarkupAnnotation {
  1872. constructor(parameters) {
  1873. super(parameters);
  1874. const file = new _file_spec.FileSpec(parameters.dict.get("FS"), parameters.xref);
  1875. this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
  1876. this.data.file = file.serializable;
  1877. }
  1878. }