annotation.js 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.MarkupAnnotation = exports.AnnotationFactory = exports.AnnotationBorderStyle = exports.Annotation = void 0;
  27. exports.getQuadPoints = getQuadPoints;
  28. var _util = require("../shared/util.js");
  29. var _core_utils = require("./core_utils.js");
  30. var _default_appearance = require("./default_appearance.js");
  31. var _primitives = require("./primitives.js");
  32. var _writer = require("./writer.js");
  33. var _base_stream = require("./base_stream.js");
  34. var _bidi = require("./bidi.js");
  35. var _catalog = require("./catalog.js");
  36. var _colorspace = require("./colorspace.js");
  37. var _file_spec = require("./file_spec.js");
  38. var _object_loader = require("./object_loader.js");
  39. var _operator_list = require("./operator_list.js");
  40. var _stream = require("./stream.js");
  41. var _factory = require("./xfa/factory.js");
  42. class AnnotationFactory {
  43. static create(xref, ref, pdfManager, idFactory, collectFields) {
  44. return Promise.all([pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("baseUrl"), pdfManager.ensureDoc("xfaDatasets"), collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1]).then(([acroForm, baseUrl, xfaDatasets, pageIndex]) => pdfManager.ensure(this, "_create", [xref, ref, pdfManager, idFactory, acroForm, xfaDatasets, collectFields, pageIndex]));
  45. }
  46. static _create(xref, ref, pdfManager, idFactory, acroForm, xfaDatasets, collectFields, pageIndex = -1) {
  47. const dict = xref.fetchIfRef(ref);
  48. if (!(dict instanceof _primitives.Dict)) {
  49. return undefined;
  50. }
  51. const id = ref instanceof _primitives.Ref ? ref.toString() : `annot_${idFactory.createObjId()}`;
  52. let subtype = dict.get("Subtype");
  53. subtype = subtype instanceof _primitives.Name ? subtype.name : null;
  54. const parameters = {
  55. xref,
  56. ref,
  57. dict,
  58. subtype,
  59. id,
  60. pdfManager,
  61. acroForm: acroForm instanceof _primitives.Dict ? acroForm : _primitives.Dict.empty,
  62. xfaDatasets,
  63. collectFields,
  64. pageIndex
  65. };
  66. switch (subtype) {
  67. case "Link":
  68. return new LinkAnnotation(parameters);
  69. case "Text":
  70. return new TextAnnotation(parameters);
  71. case "Widget":
  72. let fieldType = (0, _core_utils.getInheritableProperty)({
  73. dict,
  74. key: "FT"
  75. });
  76. fieldType = fieldType instanceof _primitives.Name ? fieldType.name : null;
  77. switch (fieldType) {
  78. case "Tx":
  79. return new TextWidgetAnnotation(parameters);
  80. case "Btn":
  81. return new ButtonWidgetAnnotation(parameters);
  82. case "Ch":
  83. return new ChoiceWidgetAnnotation(parameters);
  84. case "Sig":
  85. return new SignatureWidgetAnnotation(parameters);
  86. }
  87. (0, _util.warn)(`Unimplemented widget field type "${fieldType}", ` + "falling back to base field type.");
  88. return new WidgetAnnotation(parameters);
  89. case "Popup":
  90. return new PopupAnnotation(parameters);
  91. case "FreeText":
  92. return new FreeTextAnnotation(parameters);
  93. case "Line":
  94. return new LineAnnotation(parameters);
  95. case "Square":
  96. return new SquareAnnotation(parameters);
  97. case "Circle":
  98. return new CircleAnnotation(parameters);
  99. case "PolyLine":
  100. return new PolylineAnnotation(parameters);
  101. case "Polygon":
  102. return new PolygonAnnotation(parameters);
  103. case "Caret":
  104. return new CaretAnnotation(parameters);
  105. case "Ink":
  106. return new InkAnnotation(parameters);
  107. case "Highlight":
  108. return new HighlightAnnotation(parameters);
  109. case "Underline":
  110. return new UnderlineAnnotation(parameters);
  111. case "Squiggly":
  112. return new SquigglyAnnotation(parameters);
  113. case "StrikeOut":
  114. return new StrikeOutAnnotation(parameters);
  115. case "Stamp":
  116. return new StampAnnotation(parameters);
  117. case "FileAttachment":
  118. return new FileAttachmentAnnotation(parameters);
  119. default:
  120. if (!collectFields) {
  121. if (!subtype) {
  122. (0, _util.warn)("Annotation is missing the required /Subtype.");
  123. } else {
  124. (0, _util.warn)(`Unimplemented annotation type "${subtype}", ` + "falling back to base annotation.");
  125. }
  126. }
  127. return new Annotation(parameters);
  128. }
  129. }
  130. static async _getPageIndex(xref, ref, pdfManager) {
  131. try {
  132. const annotDict = await xref.fetchIfRefAsync(ref);
  133. if (!(annotDict instanceof _primitives.Dict)) {
  134. return -1;
  135. }
  136. const pageRef = annotDict.getRaw("P");
  137. if (!(pageRef instanceof _primitives.Ref)) {
  138. return -1;
  139. }
  140. const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [pageRef]);
  141. return pageIndex;
  142. } catch (ex) {
  143. (0, _util.warn)(`_getPageIndex: "${ex}".`);
  144. return -1;
  145. }
  146. }
  147. static async saveNewAnnotations(evaluator, task, annotations) {
  148. const xref = evaluator.xref;
  149. let baseFontRef;
  150. const dependencies = [];
  151. const promises = [];
  152. for (const annotation of annotations) {
  153. switch (annotation.annotationType) {
  154. case _util.AnnotationEditorType.FREETEXT:
  155. if (!baseFontRef) {
  156. const baseFont = new _primitives.Dict(xref);
  157. baseFont.set("BaseFont", _primitives.Name.get("Helvetica"));
  158. baseFont.set("Type", _primitives.Name.get("Font"));
  159. baseFont.set("Subtype", _primitives.Name.get("Type1"));
  160. baseFont.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
  161. const buffer = [];
  162. baseFontRef = xref.getNewRef();
  163. (0, _writer.writeObject)(baseFontRef, baseFont, buffer, null);
  164. dependencies.push({
  165. ref: baseFontRef,
  166. data: buffer.join("")
  167. });
  168. }
  169. promises.push(FreeTextAnnotation.createNewAnnotation(xref, annotation, dependencies, {
  170. evaluator,
  171. task,
  172. baseFontRef
  173. }));
  174. break;
  175. case _util.AnnotationEditorType.INK:
  176. promises.push(InkAnnotation.createNewAnnotation(xref, annotation, dependencies));
  177. }
  178. }
  179. return {
  180. annotations: await Promise.all(promises),
  181. dependencies
  182. };
  183. }
  184. static async printNewAnnotations(evaluator, task, annotations) {
  185. if (!annotations) {
  186. return null;
  187. }
  188. const xref = evaluator.xref;
  189. const promises = [];
  190. for (const annotation of annotations) {
  191. switch (annotation.annotationType) {
  192. case _util.AnnotationEditorType.FREETEXT:
  193. promises.push(FreeTextAnnotation.createNewPrintAnnotation(xref, annotation, {
  194. evaluator,
  195. task
  196. }));
  197. break;
  198. case _util.AnnotationEditorType.INK:
  199. promises.push(InkAnnotation.createNewPrintAnnotation(xref, annotation));
  200. break;
  201. }
  202. }
  203. return Promise.all(promises);
  204. }
  205. }
  206. exports.AnnotationFactory = AnnotationFactory;
  207. function getRgbColor(color, defaultColor = new Uint8ClampedArray(3)) {
  208. if (!Array.isArray(color)) {
  209. return defaultColor;
  210. }
  211. const rgbColor = defaultColor || new Uint8ClampedArray(3);
  212. switch (color.length) {
  213. case 0:
  214. return null;
  215. case 1:
  216. _colorspace.ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
  217. return rgbColor;
  218. case 3:
  219. _colorspace.ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
  220. return rgbColor;
  221. case 4:
  222. _colorspace.ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
  223. return rgbColor;
  224. default:
  225. return defaultColor;
  226. }
  227. }
  228. function getQuadPoints(dict, rect) {
  229. if (!dict.has("QuadPoints")) {
  230. return null;
  231. }
  232. const quadPoints = dict.getArray("QuadPoints");
  233. if (!Array.isArray(quadPoints) || quadPoints.length === 0 || quadPoints.length % 8 > 0) {
  234. return null;
  235. }
  236. const quadPointsLists = [];
  237. for (let i = 0, ii = quadPoints.length / 8; i < ii; i++) {
  238. quadPointsLists.push([]);
  239. for (let j = i * 8, jj = i * 8 + 8; j < jj; j += 2) {
  240. const x = quadPoints[j];
  241. const y = quadPoints[j + 1];
  242. if (rect !== null && (x < rect[0] || x > rect[2] || y < rect[1] || y > rect[3])) {
  243. return null;
  244. }
  245. quadPointsLists[i].push({
  246. x,
  247. y
  248. });
  249. }
  250. }
  251. return quadPointsLists.map(quadPointsList => {
  252. 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]);
  253. return [{
  254. x: minX,
  255. y: maxY
  256. }, {
  257. x: maxX,
  258. y: maxY
  259. }, {
  260. x: minX,
  261. y: minY
  262. }, {
  263. x: maxX,
  264. y: minY
  265. }];
  266. });
  267. }
  268. function getTransformMatrix(rect, bbox, matrix) {
  269. const [minX, minY, maxX, maxY] = _util.Util.getAxialAlignedBoundingBox(bbox, matrix);
  270. if (minX === maxX || minY === maxY) {
  271. return [1, 0, 0, 1, rect[0], rect[1]];
  272. }
  273. const xRatio = (rect[2] - rect[0]) / (maxX - minX);
  274. const yRatio = (rect[3] - rect[1]) / (maxY - minY);
  275. return [xRatio, 0, 0, yRatio, rect[0] - minX * xRatio, rect[1] - minY * yRatio];
  276. }
  277. class Annotation {
  278. constructor(params) {
  279. const dict = params.dict;
  280. this.setTitle(dict.get("T"));
  281. this.setContents(dict.get("Contents"));
  282. this.setModificationDate(dict.get("M"));
  283. this.setFlags(dict.get("F"));
  284. this.setRectangle(dict.getArray("Rect"));
  285. this.setColor(dict.getArray("C"));
  286. this.setBorderStyle(dict);
  287. this.setAppearance(dict);
  288. this.setOptionalContent(dict);
  289. const MK = dict.get("MK");
  290. this.setBorderAndBackgroundColors(MK);
  291. this.setRotation(MK);
  292. this._streams = [];
  293. if (this.appearance) {
  294. this._streams.push(this.appearance);
  295. }
  296. this.data = {
  297. annotationFlags: this.flags,
  298. borderStyle: this.borderStyle,
  299. color: this.color,
  300. backgroundColor: this.backgroundColor,
  301. borderColor: this.borderColor,
  302. rotation: this.rotation,
  303. contentsObj: this._contents,
  304. hasAppearance: !!this.appearance,
  305. id: params.id,
  306. modificationDate: this.modificationDate,
  307. rect: this.rectangle,
  308. subtype: params.subtype,
  309. hasOwnCanvas: false
  310. };
  311. if (params.collectFields) {
  312. const kids = dict.get("Kids");
  313. if (Array.isArray(kids)) {
  314. const kidIds = [];
  315. for (const kid of kids) {
  316. if (kid instanceof _primitives.Ref) {
  317. kidIds.push(kid.toString());
  318. }
  319. }
  320. if (kidIds.length !== 0) {
  321. this.data.kidIds = kidIds;
  322. }
  323. }
  324. this.data.actions = (0, _core_utils.collectActions)(params.xref, dict, _util.AnnotationActionEventType);
  325. this.data.fieldName = this._constructFieldName(dict);
  326. this.data.pageIndex = params.pageIndex;
  327. }
  328. this._fallbackFontDict = null;
  329. }
  330. _hasFlag(flags, flag) {
  331. return !!(flags & flag);
  332. }
  333. _isViewable(flags) {
  334. return !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, _util.AnnotationFlag.NOVIEW);
  335. }
  336. _isPrintable(flags) {
  337. return this._hasFlag(flags, _util.AnnotationFlag.PRINT) && !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE);
  338. }
  339. mustBeViewed(annotationStorage) {
  340. const storageEntry = annotationStorage && annotationStorage.get(this.data.id);
  341. if (storageEntry && storageEntry.hidden !== undefined) {
  342. return !storageEntry.hidden;
  343. }
  344. return this.viewable && !this._hasFlag(this.flags, _util.AnnotationFlag.HIDDEN);
  345. }
  346. mustBePrinted(annotationStorage) {
  347. const storageEntry = annotationStorage && annotationStorage.get(this.data.id);
  348. if (storageEntry && storageEntry.print !== undefined) {
  349. return storageEntry.print;
  350. }
  351. return this.printable;
  352. }
  353. get viewable() {
  354. if (this.data.quadPoints === null) {
  355. return false;
  356. }
  357. if (this.flags === 0) {
  358. return true;
  359. }
  360. return this._isViewable(this.flags);
  361. }
  362. get printable() {
  363. if (this.data.quadPoints === null) {
  364. return false;
  365. }
  366. if (this.flags === 0) {
  367. return false;
  368. }
  369. return this._isPrintable(this.flags);
  370. }
  371. _parseStringHelper(data) {
  372. const str = typeof data === "string" ? (0, _util.stringToPDFString)(data) : "";
  373. const dir = str && (0, _bidi.bidi)(str).dir === "rtl" ? "rtl" : "ltr";
  374. return {
  375. str,
  376. dir
  377. };
  378. }
  379. setTitle(title) {
  380. this._title = this._parseStringHelper(title);
  381. }
  382. setContents(contents) {
  383. this._contents = this._parseStringHelper(contents);
  384. }
  385. setModificationDate(modificationDate) {
  386. this.modificationDate = typeof modificationDate === "string" ? modificationDate : null;
  387. }
  388. setFlags(flags) {
  389. this.flags = Number.isInteger(flags) && flags > 0 ? flags : 0;
  390. }
  391. hasFlag(flag) {
  392. return this._hasFlag(this.flags, flag);
  393. }
  394. setRectangle(rectangle) {
  395. if (Array.isArray(rectangle) && rectangle.length === 4) {
  396. this.rectangle = _util.Util.normalizeRect(rectangle);
  397. } else {
  398. this.rectangle = [0, 0, 0, 0];
  399. }
  400. }
  401. setColor(color) {
  402. this.color = getRgbColor(color);
  403. }
  404. setLineEndings(lineEndings) {
  405. this.lineEndings = ["None", "None"];
  406. if (Array.isArray(lineEndings) && lineEndings.length === 2) {
  407. for (let i = 0; i < 2; i++) {
  408. const obj = lineEndings[i];
  409. if (obj instanceof _primitives.Name) {
  410. switch (obj.name) {
  411. case "None":
  412. continue;
  413. case "Square":
  414. case "Circle":
  415. case "Diamond":
  416. case "OpenArrow":
  417. case "ClosedArrow":
  418. case "Butt":
  419. case "ROpenArrow":
  420. case "RClosedArrow":
  421. case "Slash":
  422. this.lineEndings[i] = obj.name;
  423. continue;
  424. }
  425. }
  426. (0, _util.warn)(`Ignoring invalid lineEnding: ${obj}`);
  427. }
  428. }
  429. }
  430. setRotation(mk) {
  431. this.rotation = 0;
  432. if (mk instanceof _primitives.Dict) {
  433. let angle = mk.get("R") || 0;
  434. if (Number.isInteger(angle) && angle !== 0) {
  435. angle %= 360;
  436. if (angle < 0) {
  437. angle += 360;
  438. }
  439. if (angle % 90 === 0) {
  440. this.rotation = angle;
  441. }
  442. }
  443. }
  444. }
  445. setBorderAndBackgroundColors(mk) {
  446. if (mk instanceof _primitives.Dict) {
  447. this.borderColor = getRgbColor(mk.getArray("BC"), null);
  448. this.backgroundColor = getRgbColor(mk.getArray("BG"), null);
  449. } else {
  450. this.borderColor = this.backgroundColor = null;
  451. }
  452. }
  453. setBorderStyle(borderStyle) {
  454. this.borderStyle = new AnnotationBorderStyle();
  455. if (!(borderStyle instanceof _primitives.Dict)) {
  456. return;
  457. }
  458. if (borderStyle.has("BS")) {
  459. const dict = borderStyle.get("BS");
  460. const dictType = dict.get("Type");
  461. if (!dictType || (0, _primitives.isName)(dictType, "Border")) {
  462. this.borderStyle.setWidth(dict.get("W"), this.rectangle);
  463. this.borderStyle.setStyle(dict.get("S"));
  464. this.borderStyle.setDashArray(dict.getArray("D"));
  465. }
  466. } else if (borderStyle.has("Border")) {
  467. const array = borderStyle.getArray("Border");
  468. if (Array.isArray(array) && array.length >= 3) {
  469. this.borderStyle.setHorizontalCornerRadius(array[0]);
  470. this.borderStyle.setVerticalCornerRadius(array[1]);
  471. this.borderStyle.setWidth(array[2], this.rectangle);
  472. if (array.length === 4) {
  473. this.borderStyle.setDashArray(array[3], true);
  474. }
  475. }
  476. } else {
  477. this.borderStyle.setWidth(0);
  478. }
  479. }
  480. setAppearance(dict) {
  481. this.appearance = null;
  482. const appearanceStates = dict.get("AP");
  483. if (!(appearanceStates instanceof _primitives.Dict)) {
  484. return;
  485. }
  486. const normalAppearanceState = appearanceStates.get("N");
  487. if (normalAppearanceState instanceof _base_stream.BaseStream) {
  488. this.appearance = normalAppearanceState;
  489. return;
  490. }
  491. if (!(normalAppearanceState instanceof _primitives.Dict)) {
  492. return;
  493. }
  494. const as = dict.get("AS");
  495. if (!(as instanceof _primitives.Name) || !normalAppearanceState.has(as.name)) {
  496. return;
  497. }
  498. this.appearance = normalAppearanceState.get(as.name);
  499. }
  500. setOptionalContent(dict) {
  501. this.oc = null;
  502. const oc = dict.get("OC");
  503. if (oc instanceof _primitives.Name) {
  504. (0, _util.warn)("setOptionalContent: Support for /Name-entry is not implemented.");
  505. } else if (oc instanceof _primitives.Dict) {
  506. this.oc = oc;
  507. }
  508. }
  509. loadResources(keys, appearance) {
  510. return appearance.dict.getAsync("Resources").then(resources => {
  511. if (!resources) {
  512. return undefined;
  513. }
  514. const objectLoader = new _object_loader.ObjectLoader(resources, keys, resources.xref);
  515. return objectLoader.load().then(function () {
  516. return resources;
  517. });
  518. });
  519. }
  520. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  521. const data = this.data;
  522. let appearance = this.appearance;
  523. const isUsingOwnCanvas = !!(this.data.hasOwnCanvas && intent & _util.RenderingIntentFlag.DISPLAY);
  524. if (!appearance) {
  525. if (!isUsingOwnCanvas) {
  526. return {
  527. opList: new _operator_list.OperatorList(),
  528. separateForm: false,
  529. separateCanvas: false
  530. };
  531. }
  532. appearance = new _stream.StringStream("");
  533. appearance.dict = new _primitives.Dict();
  534. }
  535. const appearanceDict = appearance.dict;
  536. const resources = await this.loadResources(["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"], appearance);
  537. const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];
  538. const matrix = appearanceDict.getArray("Matrix") || [1, 0, 0, 1, 0, 0];
  539. const transform = getTransformMatrix(data.rect, bbox, matrix);
  540. const opList = new _operator_list.OperatorList();
  541. let optionalContent;
  542. if (this.oc) {
  543. optionalContent = await evaluator.parseMarkedContentProps(this.oc, null);
  544. }
  545. if (optionalContent !== undefined) {
  546. opList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
  547. }
  548. opList.addOp(_util.OPS.beginAnnotation, [data.id, data.rect, transform, matrix, isUsingOwnCanvas]);
  549. await evaluator.getOperatorList({
  550. stream: appearance,
  551. task,
  552. resources,
  553. operatorList: opList,
  554. fallbackFontDict: this._fallbackFontDict
  555. });
  556. opList.addOp(_util.OPS.endAnnotation, []);
  557. if (optionalContent !== undefined) {
  558. opList.addOp(_util.OPS.endMarkedContent, []);
  559. }
  560. this.reset();
  561. return {
  562. opList,
  563. separateForm: false,
  564. separateCanvas: isUsingOwnCanvas
  565. };
  566. }
  567. async save(evaluator, task, annotationStorage) {
  568. return null;
  569. }
  570. getFieldObject() {
  571. if (this.data.kidIds) {
  572. return {
  573. id: this.data.id,
  574. actions: this.data.actions,
  575. name: this.data.fieldName,
  576. strokeColor: this.data.borderColor,
  577. fillColor: this.data.backgroundColor,
  578. type: "",
  579. kidIds: this.data.kidIds,
  580. page: this.data.pageIndex,
  581. rotation: this.rotation
  582. };
  583. }
  584. return null;
  585. }
  586. reset() {
  587. for (const stream of this._streams) {
  588. stream.reset();
  589. }
  590. }
  591. _constructFieldName(dict) {
  592. if (!dict.has("T") && !dict.has("Parent")) {
  593. (0, _util.warn)("Unknown field name, falling back to empty field name.");
  594. return "";
  595. }
  596. if (!dict.has("Parent")) {
  597. return (0, _util.stringToPDFString)(dict.get("T"));
  598. }
  599. const fieldName = [];
  600. if (dict.has("T")) {
  601. fieldName.unshift((0, _util.stringToPDFString)(dict.get("T")));
  602. }
  603. let loopDict = dict;
  604. const visited = new _primitives.RefSet();
  605. if (dict.objId) {
  606. visited.put(dict.objId);
  607. }
  608. while (loopDict.has("Parent")) {
  609. loopDict = loopDict.get("Parent");
  610. if (!(loopDict instanceof _primitives.Dict) || loopDict.objId && visited.has(loopDict.objId)) {
  611. break;
  612. }
  613. if (loopDict.objId) {
  614. visited.put(loopDict.objId);
  615. }
  616. if (loopDict.has("T")) {
  617. fieldName.unshift((0, _util.stringToPDFString)(loopDict.get("T")));
  618. }
  619. }
  620. return fieldName.join(".");
  621. }
  622. }
  623. exports.Annotation = Annotation;
  624. class AnnotationBorderStyle {
  625. constructor() {
  626. this.width = 1;
  627. this.style = _util.AnnotationBorderStyleType.SOLID;
  628. this.dashArray = [3];
  629. this.horizontalCornerRadius = 0;
  630. this.verticalCornerRadius = 0;
  631. }
  632. setWidth(width, rect = [0, 0, 0, 0]) {
  633. if (width instanceof _primitives.Name) {
  634. this.width = 0;
  635. return;
  636. }
  637. if (typeof width === "number") {
  638. if (width > 0) {
  639. const maxWidth = (rect[2] - rect[0]) / 2;
  640. const maxHeight = (rect[3] - rect[1]) / 2;
  641. if (maxWidth > 0 && maxHeight > 0 && (width > maxWidth || width > maxHeight)) {
  642. (0, _util.warn)(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
  643. width = 1;
  644. }
  645. }
  646. this.width = width;
  647. }
  648. }
  649. setStyle(style) {
  650. if (!(style instanceof _primitives.Name)) {
  651. return;
  652. }
  653. switch (style.name) {
  654. case "S":
  655. this.style = _util.AnnotationBorderStyleType.SOLID;
  656. break;
  657. case "D":
  658. this.style = _util.AnnotationBorderStyleType.DASHED;
  659. break;
  660. case "B":
  661. this.style = _util.AnnotationBorderStyleType.BEVELED;
  662. break;
  663. case "I":
  664. this.style = _util.AnnotationBorderStyleType.INSET;
  665. break;
  666. case "U":
  667. this.style = _util.AnnotationBorderStyleType.UNDERLINE;
  668. break;
  669. default:
  670. break;
  671. }
  672. }
  673. setDashArray(dashArray, forceStyle = false) {
  674. if (Array.isArray(dashArray) && dashArray.length > 0) {
  675. let isValid = true;
  676. let allZeros = true;
  677. for (const element of dashArray) {
  678. const validNumber = +element >= 0;
  679. if (!validNumber) {
  680. isValid = false;
  681. break;
  682. } else if (element > 0) {
  683. allZeros = false;
  684. }
  685. }
  686. if (isValid && !allZeros) {
  687. this.dashArray = dashArray;
  688. if (forceStyle) {
  689. this.setStyle(_primitives.Name.get("D"));
  690. }
  691. } else {
  692. this.width = 0;
  693. }
  694. } else if (dashArray) {
  695. this.width = 0;
  696. }
  697. }
  698. setHorizontalCornerRadius(radius) {
  699. if (Number.isInteger(radius)) {
  700. this.horizontalCornerRadius = radius;
  701. }
  702. }
  703. setVerticalCornerRadius(radius) {
  704. if (Number.isInteger(radius)) {
  705. this.verticalCornerRadius = radius;
  706. }
  707. }
  708. }
  709. exports.AnnotationBorderStyle = AnnotationBorderStyle;
  710. class MarkupAnnotation extends Annotation {
  711. constructor(parameters) {
  712. super(parameters);
  713. const dict = parameters.dict;
  714. if (dict.has("IRT")) {
  715. const rawIRT = dict.getRaw("IRT");
  716. this.data.inReplyTo = rawIRT instanceof _primitives.Ref ? rawIRT.toString() : null;
  717. const rt = dict.get("RT");
  718. this.data.replyType = rt instanceof _primitives.Name ? rt.name : _util.AnnotationReplyType.REPLY;
  719. }
  720. if (this.data.replyType === _util.AnnotationReplyType.GROUP) {
  721. const parent = dict.get("IRT");
  722. this.setTitle(parent.get("T"));
  723. this.data.titleObj = this._title;
  724. this.setContents(parent.get("Contents"));
  725. this.data.contentsObj = this._contents;
  726. if (!parent.has("CreationDate")) {
  727. this.data.creationDate = null;
  728. } else {
  729. this.setCreationDate(parent.get("CreationDate"));
  730. this.data.creationDate = this.creationDate;
  731. }
  732. if (!parent.has("M")) {
  733. this.data.modificationDate = null;
  734. } else {
  735. this.setModificationDate(parent.get("M"));
  736. this.data.modificationDate = this.modificationDate;
  737. }
  738. this.data.hasPopup = parent.has("Popup");
  739. if (!parent.has("C")) {
  740. this.data.color = null;
  741. } else {
  742. this.setColor(parent.getArray("C"));
  743. this.data.color = this.color;
  744. }
  745. } else {
  746. this.data.titleObj = this._title;
  747. this.setCreationDate(dict.get("CreationDate"));
  748. this.data.creationDate = this.creationDate;
  749. this.data.hasPopup = dict.has("Popup");
  750. if (!dict.has("C")) {
  751. this.data.color = null;
  752. }
  753. }
  754. if (dict.has("RC")) {
  755. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(dict.get("RC"));
  756. }
  757. }
  758. setCreationDate(creationDate) {
  759. this.creationDate = typeof creationDate === "string" ? creationDate : null;
  760. }
  761. _setDefaultAppearance({
  762. xref,
  763. extra,
  764. strokeColor,
  765. fillColor,
  766. blendMode,
  767. strokeAlpha,
  768. fillAlpha,
  769. pointsCallback
  770. }) {
  771. let minX = Number.MAX_VALUE;
  772. let minY = Number.MAX_VALUE;
  773. let maxX = Number.MIN_VALUE;
  774. let maxY = Number.MIN_VALUE;
  775. const buffer = ["q"];
  776. if (extra) {
  777. buffer.push(extra);
  778. }
  779. if (strokeColor) {
  780. buffer.push(`${strokeColor[0]} ${strokeColor[1]} ${strokeColor[2]} RG`);
  781. }
  782. if (fillColor) {
  783. buffer.push(`${fillColor[0]} ${fillColor[1]} ${fillColor[2]} rg`);
  784. }
  785. let pointsArray = this.data.quadPoints;
  786. if (!pointsArray) {
  787. pointsArray = [[{
  788. x: this.rectangle[0],
  789. y: this.rectangle[3]
  790. }, {
  791. x: this.rectangle[2],
  792. y: this.rectangle[3]
  793. }, {
  794. x: this.rectangle[0],
  795. y: this.rectangle[1]
  796. }, {
  797. x: this.rectangle[2],
  798. y: this.rectangle[1]
  799. }]];
  800. }
  801. for (const points of pointsArray) {
  802. const [mX, MX, mY, MY] = pointsCallback(buffer, points);
  803. minX = Math.min(minX, mX);
  804. maxX = Math.max(maxX, MX);
  805. minY = Math.min(minY, mY);
  806. maxY = Math.max(maxY, MY);
  807. }
  808. buffer.push("Q");
  809. const formDict = new _primitives.Dict(xref);
  810. const appearanceStreamDict = new _primitives.Dict(xref);
  811. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  812. const appearanceStream = new _stream.StringStream(buffer.join(" "));
  813. appearanceStream.dict = appearanceStreamDict;
  814. formDict.set("Fm0", appearanceStream);
  815. const gsDict = new _primitives.Dict(xref);
  816. if (blendMode) {
  817. gsDict.set("BM", _primitives.Name.get(blendMode));
  818. }
  819. if (typeof strokeAlpha === "number") {
  820. gsDict.set("CA", strokeAlpha);
  821. }
  822. if (typeof fillAlpha === "number") {
  823. gsDict.set("ca", fillAlpha);
  824. }
  825. const stateDict = new _primitives.Dict(xref);
  826. stateDict.set("GS0", gsDict);
  827. const resources = new _primitives.Dict(xref);
  828. resources.set("ExtGState", stateDict);
  829. resources.set("XObject", formDict);
  830. const appearanceDict = new _primitives.Dict(xref);
  831. appearanceDict.set("Resources", resources);
  832. const bbox = this.data.rect = [minX, minY, maxX, maxY];
  833. appearanceDict.set("BBox", bbox);
  834. this.appearance = new _stream.StringStream("/GS0 gs /Fm0 Do");
  835. this.appearance.dict = appearanceDict;
  836. this._streams.push(this.appearance, appearanceStream);
  837. }
  838. static async createNewAnnotation(xref, annotation, dependencies, params) {
  839. const annotationRef = xref.getNewRef();
  840. const apRef = xref.getNewRef();
  841. const annotationDict = this.createNewDict(annotation, xref, {
  842. apRef
  843. });
  844. const ap = await this.createNewAppearanceStream(annotation, xref, params);
  845. const buffer = [];
  846. let transform = xref.encrypt ? xref.encrypt.createCipherTransform(apRef.num, apRef.gen) : null;
  847. (0, _writer.writeObject)(apRef, ap, buffer, transform);
  848. dependencies.push({
  849. ref: apRef,
  850. data: buffer.join("")
  851. });
  852. buffer.length = 0;
  853. transform = xref.encrypt ? xref.encrypt.createCipherTransform(annotationRef.num, annotationRef.gen) : null;
  854. (0, _writer.writeObject)(annotationRef, annotationDict, buffer, transform);
  855. return {
  856. ref: annotationRef,
  857. data: buffer.join("")
  858. };
  859. }
  860. static async createNewPrintAnnotation(xref, annotation, params) {
  861. const ap = await this.createNewAppearanceStream(annotation, xref, params);
  862. const annotationDict = this.createNewDict(annotation, xref, {
  863. ap
  864. });
  865. return new this.prototype.constructor({
  866. dict: annotationDict,
  867. xref
  868. });
  869. }
  870. }
  871. exports.MarkupAnnotation = MarkupAnnotation;
  872. class WidgetAnnotation extends Annotation {
  873. constructor(params) {
  874. super(params);
  875. const dict = params.dict;
  876. const data = this.data;
  877. this.ref = params.ref;
  878. data.annotationType = _util.AnnotationType.WIDGET;
  879. if (data.fieldName === undefined) {
  880. data.fieldName = this._constructFieldName(dict);
  881. }
  882. if (data.actions === undefined) {
  883. data.actions = (0, _core_utils.collectActions)(params.xref, dict, _util.AnnotationActionEventType);
  884. }
  885. let fieldValue = (0, _core_utils.getInheritableProperty)({
  886. dict,
  887. key: "V",
  888. getArray: true
  889. });
  890. data.fieldValue = this._decodeFormValue(fieldValue);
  891. const defaultFieldValue = (0, _core_utils.getInheritableProperty)({
  892. dict,
  893. key: "DV",
  894. getArray: true
  895. });
  896. data.defaultFieldValue = this._decodeFormValue(defaultFieldValue);
  897. if (fieldValue === undefined && params.xfaDatasets) {
  898. const path = this._title.str;
  899. if (path) {
  900. this._hasValueFromXFA = true;
  901. data.fieldValue = fieldValue = params.xfaDatasets.getValue(path);
  902. }
  903. }
  904. if (fieldValue === undefined && data.defaultFieldValue !== null) {
  905. data.fieldValue = data.defaultFieldValue;
  906. }
  907. data.alternativeText = (0, _util.stringToPDFString)(dict.get("TU") || "");
  908. const defaultAppearance = (0, _core_utils.getInheritableProperty)({
  909. dict,
  910. key: "DA"
  911. }) || params.acroForm.get("DA");
  912. this._defaultAppearance = typeof defaultAppearance === "string" ? defaultAppearance : "";
  913. data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance);
  914. const fieldType = (0, _core_utils.getInheritableProperty)({
  915. dict,
  916. key: "FT"
  917. });
  918. data.fieldType = fieldType instanceof _primitives.Name ? fieldType.name : null;
  919. const localResources = (0, _core_utils.getInheritableProperty)({
  920. dict,
  921. key: "DR"
  922. });
  923. const acroFormResources = params.acroForm.get("DR");
  924. const appearanceResources = this.appearance && this.appearance.dict.get("Resources");
  925. this._fieldResources = {
  926. localResources,
  927. acroFormResources,
  928. appearanceResources,
  929. mergedResources: _primitives.Dict.merge({
  930. xref: params.xref,
  931. dictArray: [localResources, appearanceResources, acroFormResources],
  932. mergeSubDicts: true
  933. })
  934. };
  935. data.fieldFlags = (0, _core_utils.getInheritableProperty)({
  936. dict,
  937. key: "Ff"
  938. });
  939. if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
  940. data.fieldFlags = 0;
  941. }
  942. data.readOnly = this.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
  943. data.required = this.hasFieldFlag(_util.AnnotationFieldFlag.REQUIRED);
  944. data.hidden = this._hasFlag(data.annotationFlags, _util.AnnotationFlag.HIDDEN);
  945. }
  946. _decodeFormValue(formValue) {
  947. if (Array.isArray(formValue)) {
  948. return formValue.filter(item => typeof item === "string").map(item => (0, _util.stringToPDFString)(item));
  949. } else if (formValue instanceof _primitives.Name) {
  950. return (0, _util.stringToPDFString)(formValue.name);
  951. } else if (typeof formValue === "string") {
  952. return (0, _util.stringToPDFString)(formValue);
  953. }
  954. return null;
  955. }
  956. hasFieldFlag(flag) {
  957. return !!(this.data.fieldFlags & flag);
  958. }
  959. static _getRotationMatrix(rotation, width, height) {
  960. switch (rotation) {
  961. case 90:
  962. return [0, 1, -1, 0, width, 0];
  963. case 180:
  964. return [-1, 0, 0, -1, width, height];
  965. case 270:
  966. return [0, -1, 1, 0, 0, height];
  967. default:
  968. throw new Error("Invalid rotation");
  969. }
  970. }
  971. getRotationMatrix(annotationStorage) {
  972. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  973. let rotation = storageEntry && storageEntry.rotation;
  974. if (rotation === undefined) {
  975. rotation = this.rotation;
  976. }
  977. if (rotation === 0) {
  978. return _util.IDENTITY_MATRIX;
  979. }
  980. const width = this.data.rect[2] - this.data.rect[0];
  981. const height = this.data.rect[3] - this.data.rect[1];
  982. return WidgetAnnotation._getRotationMatrix(rotation, width, height);
  983. }
  984. getBorderAndBackgroundAppearances(annotationStorage) {
  985. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  986. let rotation = storageEntry && storageEntry.rotation;
  987. if (rotation === undefined) {
  988. rotation = this.rotation;
  989. }
  990. if (!this.backgroundColor && !this.borderColor) {
  991. return "";
  992. }
  993. const width = this.data.rect[2] - this.data.rect[0];
  994. const height = this.data.rect[3] - this.data.rect[1];
  995. const rect = rotation === 0 || rotation === 180 ? `0 0 ${width} ${height} re` : `0 0 ${height} ${width} re`;
  996. let str = "";
  997. if (this.backgroundColor) {
  998. str = `${(0, _default_appearance.getPdfColor)(this.backgroundColor, true)} ${rect} f `;
  999. }
  1000. if (this.borderColor) {
  1001. const borderWidth = this.borderStyle.width || 1;
  1002. str += `${borderWidth} w ${(0, _default_appearance.getPdfColor)(this.borderColor, false)} ${rect} S `;
  1003. }
  1004. return str;
  1005. }
  1006. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  1007. if (renderForms && !(this instanceof SignatureWidgetAnnotation)) {
  1008. return {
  1009. opList: new _operator_list.OperatorList(),
  1010. separateForm: true,
  1011. separateCanvas: false
  1012. };
  1013. }
  1014. if (!this._hasText) {
  1015. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1016. }
  1017. const content = await this._getAppearance(evaluator, task, annotationStorage);
  1018. if (this.appearance && content === null) {
  1019. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1020. }
  1021. const opList = new _operator_list.OperatorList();
  1022. if (!this._defaultAppearance || content === null) {
  1023. return {
  1024. opList,
  1025. separateForm: false,
  1026. separateCanvas: false
  1027. };
  1028. }
  1029. const matrix = [1, 0, 0, 1, 0, 0];
  1030. const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
  1031. const transform = getTransformMatrix(this.data.rect, bbox, matrix);
  1032. let optionalContent;
  1033. if (this.oc) {
  1034. optionalContent = await evaluator.parseMarkedContentProps(this.oc, null);
  1035. }
  1036. if (optionalContent !== undefined) {
  1037. opList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
  1038. }
  1039. opList.addOp(_util.OPS.beginAnnotation, [this.data.id, this.data.rect, transform, this.getRotationMatrix(annotationStorage), false]);
  1040. const stream = new _stream.StringStream(content);
  1041. await evaluator.getOperatorList({
  1042. stream,
  1043. task,
  1044. resources: this._fieldResources.mergedResources,
  1045. operatorList: opList
  1046. });
  1047. opList.addOp(_util.OPS.endAnnotation, []);
  1048. if (optionalContent !== undefined) {
  1049. opList.addOp(_util.OPS.endMarkedContent, []);
  1050. }
  1051. return {
  1052. opList,
  1053. separateForm: false,
  1054. separateCanvas: false
  1055. };
  1056. }
  1057. _getMKDict(rotation) {
  1058. const mk = new _primitives.Dict(null);
  1059. if (rotation) {
  1060. mk.set("R", rotation);
  1061. }
  1062. if (this.borderColor) {
  1063. mk.set("BC", Array.from(this.borderColor).map(c => c / 255));
  1064. }
  1065. if (this.backgroundColor) {
  1066. mk.set("BG", Array.from(this.backgroundColor).map(c => c / 255));
  1067. }
  1068. return mk.size > 0 ? mk : null;
  1069. }
  1070. async save(evaluator, task, annotationStorage) {
  1071. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  1072. let value = storageEntry && storageEntry.value;
  1073. let rotation = storageEntry && storageEntry.rotation;
  1074. if (value === this.data.fieldValue || value === undefined) {
  1075. if (!this._hasValueFromXFA && rotation === undefined) {
  1076. return null;
  1077. }
  1078. value = value || this.data.fieldValue;
  1079. }
  1080. if (rotation === undefined && !this._hasValueFromXFA && Array.isArray(value) && Array.isArray(this.data.fieldValue) && value.length === this.data.fieldValue.length && value.every((x, i) => x === this.data.fieldValue[i])) {
  1081. return null;
  1082. }
  1083. if (rotation === undefined) {
  1084. rotation = this.rotation;
  1085. }
  1086. let appearance = await this._getAppearance(evaluator, task, annotationStorage);
  1087. if (appearance === null) {
  1088. return null;
  1089. }
  1090. const {
  1091. xref
  1092. } = evaluator;
  1093. const dict = xref.fetchIfRef(this.ref);
  1094. if (!(dict instanceof _primitives.Dict)) {
  1095. return null;
  1096. }
  1097. const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
  1098. const xfa = {
  1099. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1100. value
  1101. };
  1102. const newRef = xref.getNewRef();
  1103. const AP = new _primitives.Dict(xref);
  1104. AP.set("N", newRef);
  1105. const encrypt = xref.encrypt;
  1106. let originalTransform = null;
  1107. let newTransform = null;
  1108. if (encrypt) {
  1109. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1110. newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
  1111. appearance = newTransform.encryptString(appearance);
  1112. }
  1113. const encoder = val => (0, _util.isAscii)(val) ? val : (0, _util.stringToUTF16BEString)(val);
  1114. dict.set("V", Array.isArray(value) ? value.map(encoder) : encoder(value));
  1115. dict.set("AP", AP);
  1116. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1117. const maybeMK = this._getMKDict(rotation);
  1118. if (maybeMK) {
  1119. dict.set("MK", maybeMK);
  1120. }
  1121. const appearanceDict = new _primitives.Dict(xref);
  1122. appearanceDict.set("Length", appearance.length);
  1123. appearanceDict.set("Subtype", _primitives.Name.get("Form"));
  1124. appearanceDict.set("Resources", this._getSaveFieldResources(xref));
  1125. appearanceDict.set("BBox", bbox);
  1126. const rotationMatrix = this.getRotationMatrix(annotationStorage);
  1127. if (rotationMatrix !== _util.IDENTITY_MATRIX) {
  1128. appearanceDict.set("Matrix", rotationMatrix);
  1129. }
  1130. const bufferOriginal = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1131. (0, _writer.writeDict)(dict, bufferOriginal, originalTransform);
  1132. bufferOriginal.push("\nendobj\n");
  1133. const bufferNew = [`${newRef.num} ${newRef.gen} obj\n`];
  1134. (0, _writer.writeDict)(appearanceDict, bufferNew, newTransform);
  1135. bufferNew.push(" stream\n", appearance, "\nendstream\nendobj\n");
  1136. return [{
  1137. ref: this.ref,
  1138. data: bufferOriginal.join(""),
  1139. xfa
  1140. }, {
  1141. ref: newRef,
  1142. data: bufferNew.join(""),
  1143. xfa: null
  1144. }];
  1145. }
  1146. async _getAppearance(evaluator, task, annotationStorage) {
  1147. const isPassword = this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD);
  1148. if (isPassword) {
  1149. return null;
  1150. }
  1151. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  1152. let value, rotation;
  1153. if (storageEntry) {
  1154. value = storageEntry.formattedValue || storageEntry.value;
  1155. rotation = storageEntry.rotation;
  1156. }
  1157. if (rotation === undefined && value === undefined) {
  1158. if (!this._hasValueFromXFA || this.appearance) {
  1159. return null;
  1160. }
  1161. }
  1162. if (value === undefined) {
  1163. value = this.data.fieldValue;
  1164. if (!value) {
  1165. return "";
  1166. }
  1167. }
  1168. if (Array.isArray(value) && value.length === 1) {
  1169. value = value[0];
  1170. }
  1171. (0, _util.assert)(typeof value === "string", "Expected `value` to be a string.");
  1172. value = value.trim();
  1173. if (value === "") {
  1174. return "";
  1175. }
  1176. if (rotation === undefined) {
  1177. rotation = this.rotation;
  1178. }
  1179. let lineCount = -1;
  1180. if (this.data.multiLine) {
  1181. lineCount = value.split(/\r\n|\r|\n/).length;
  1182. }
  1183. const defaultPadding = 2;
  1184. const hPadding = defaultPadding;
  1185. let totalHeight = this.data.rect[3] - this.data.rect[1];
  1186. let totalWidth = this.data.rect[2] - this.data.rect[0];
  1187. if (rotation === 90 || rotation === 270) {
  1188. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  1189. }
  1190. if (!this._defaultAppearance) {
  1191. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  1192. }
  1193. const font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
  1194. const [defaultAppearance, fontSize] = this._computeFontSize(totalHeight - defaultPadding, totalWidth - 2 * hPadding, value, font, lineCount);
  1195. let descent = font.descent;
  1196. if (isNaN(descent)) {
  1197. descent = 0;
  1198. }
  1199. const defaultVPadding = Math.min(Math.floor((totalHeight - fontSize) / 2), defaultPadding);
  1200. const vPadding = defaultVPadding + Math.abs(descent) * fontSize;
  1201. const alignment = this.data.textAlignment;
  1202. if (this.data.multiLine) {
  1203. return this._getMultilineAppearance(defaultAppearance, value, font, fontSize, totalWidth, totalHeight, alignment, hPadding, vPadding, annotationStorage);
  1204. }
  1205. const encodedString = font.encodeString(value).join("");
  1206. if (this.data.comb) {
  1207. return this._getCombAppearance(defaultAppearance, font, encodedString, totalWidth, hPadding, vPadding, annotationStorage);
  1208. }
  1209. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1210. if (alignment === 0 || alignment > 2) {
  1211. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm (${(0, _util.escapeString)(encodedString)}) Tj` + " ET Q EMC";
  1212. }
  1213. const renderedText = this._renderText(encodedString, font, fontSize, totalWidth, alignment, hPadding, vPadding);
  1214. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC";
  1215. }
  1216. static async _getFontData(evaluator, task, appearanceData, resources) {
  1217. const operatorList = new _operator_list.OperatorList();
  1218. const initialState = {
  1219. font: null,
  1220. clone() {
  1221. return this;
  1222. }
  1223. };
  1224. const {
  1225. fontName,
  1226. fontSize
  1227. } = appearanceData;
  1228. await evaluator.handleSetFont(resources, [fontName && _primitives.Name.get(fontName), fontSize], null, operatorList, task, initialState, null);
  1229. return initialState.font;
  1230. }
  1231. _getTextWidth(text, font) {
  1232. return font.charsToGlyphs(text).reduce((width, glyph) => width + glyph.width, 0) / 1000;
  1233. }
  1234. _computeFontSize(height, width, text, font, lineCount) {
  1235. let {
  1236. fontSize
  1237. } = this.data.defaultAppearanceData;
  1238. if (!fontSize) {
  1239. const roundWithTwoDigits = x => Math.floor(x * 100) / 100;
  1240. if (lineCount === -1) {
  1241. const textWidth = this._getTextWidth(text, font);
  1242. fontSize = roundWithTwoDigits(Math.min(height / _util.LINE_FACTOR, width / textWidth));
  1243. } else {
  1244. const lines = text.split(/\r\n?|\n/);
  1245. const cachedLines = [];
  1246. for (const line of lines) {
  1247. const encoded = font.encodeString(line).join("");
  1248. const glyphs = font.charsToGlyphs(encoded);
  1249. const positions = font.getCharPositions(encoded);
  1250. cachedLines.push({
  1251. line: encoded,
  1252. glyphs,
  1253. positions
  1254. });
  1255. }
  1256. const isTooBig = fsize => {
  1257. let totalHeight = 0;
  1258. for (const cache of cachedLines) {
  1259. const chunks = this._splitLine(null, font, fsize, width, cache);
  1260. totalHeight += chunks.length * fsize;
  1261. if (totalHeight > height) {
  1262. return true;
  1263. }
  1264. }
  1265. return false;
  1266. };
  1267. fontSize = 12;
  1268. let lineHeight = fontSize * _util.LINE_FACTOR;
  1269. let numberOfLines = Math.round(height / lineHeight);
  1270. numberOfLines = Math.max(numberOfLines, lineCount);
  1271. while (true) {
  1272. lineHeight = height / numberOfLines;
  1273. fontSize = roundWithTwoDigits(lineHeight / _util.LINE_FACTOR);
  1274. if (isTooBig(fontSize)) {
  1275. numberOfLines++;
  1276. continue;
  1277. }
  1278. break;
  1279. }
  1280. }
  1281. const {
  1282. fontName,
  1283. fontColor
  1284. } = this.data.defaultAppearanceData;
  1285. this._defaultAppearance = (0, _default_appearance.createDefaultAppearance)({
  1286. fontSize,
  1287. fontName,
  1288. fontColor
  1289. });
  1290. }
  1291. return [this._defaultAppearance, fontSize];
  1292. }
  1293. _renderText(text, font, fontSize, totalWidth, alignment, hPadding, vPadding) {
  1294. let shift;
  1295. if (alignment === 1) {
  1296. const width = this._getTextWidth(text, font) * fontSize;
  1297. shift = (totalWidth - width) / 2;
  1298. } else if (alignment === 2) {
  1299. const width = this._getTextWidth(text, font) * fontSize;
  1300. shift = totalWidth - width - hPadding;
  1301. } else {
  1302. shift = hPadding;
  1303. }
  1304. shift = (0, _core_utils.numberToString)(shift);
  1305. vPadding = (0, _core_utils.numberToString)(vPadding);
  1306. return `${shift} ${vPadding} Td (${(0, _util.escapeString)(text)}) Tj`;
  1307. }
  1308. _getSaveFieldResources(xref) {
  1309. const {
  1310. localResources,
  1311. appearanceResources,
  1312. acroFormResources
  1313. } = this._fieldResources;
  1314. const fontName = this.data.defaultAppearanceData && this.data.defaultAppearanceData.fontName;
  1315. if (!fontName) {
  1316. return localResources || _primitives.Dict.empty;
  1317. }
  1318. for (const resources of [localResources, appearanceResources]) {
  1319. if (resources instanceof _primitives.Dict) {
  1320. const localFont = resources.get("Font");
  1321. if (localFont instanceof _primitives.Dict && localFont.has(fontName)) {
  1322. return resources;
  1323. }
  1324. }
  1325. }
  1326. if (acroFormResources instanceof _primitives.Dict) {
  1327. const acroFormFont = acroFormResources.get("Font");
  1328. if (acroFormFont instanceof _primitives.Dict && acroFormFont.has(fontName)) {
  1329. const subFontDict = new _primitives.Dict(xref);
  1330. subFontDict.set(fontName, acroFormFont.getRaw(fontName));
  1331. const subResourcesDict = new _primitives.Dict(xref);
  1332. subResourcesDict.set("Font", subFontDict);
  1333. return _primitives.Dict.merge({
  1334. xref,
  1335. dictArray: [subResourcesDict, localResources],
  1336. mergeSubDicts: true
  1337. });
  1338. }
  1339. }
  1340. return localResources || _primitives.Dict.empty;
  1341. }
  1342. getFieldObject() {
  1343. return null;
  1344. }
  1345. }
  1346. class TextWidgetAnnotation extends WidgetAnnotation {
  1347. constructor(params) {
  1348. super(params);
  1349. this._hasText = true;
  1350. const dict = params.dict;
  1351. if (typeof this.data.fieldValue !== "string") {
  1352. this.data.fieldValue = "";
  1353. }
  1354. let alignment = (0, _core_utils.getInheritableProperty)({
  1355. dict,
  1356. key: "Q"
  1357. });
  1358. if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
  1359. alignment = null;
  1360. }
  1361. this.data.textAlignment = alignment;
  1362. let maximumLength = (0, _core_utils.getInheritableProperty)({
  1363. dict,
  1364. key: "MaxLen"
  1365. });
  1366. if (!Number.isInteger(maximumLength) || maximumLength < 0) {
  1367. maximumLength = null;
  1368. }
  1369. this.data.maxLen = maximumLength;
  1370. this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
  1371. 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;
  1372. this.data.doNotScroll = this.hasFieldFlag(_util.AnnotationFieldFlag.DONOTSCROLL);
  1373. }
  1374. _getCombAppearance(defaultAppearance, font, text, width, hPadding, vPadding, annotationStorage) {
  1375. const combWidth = (0, _core_utils.numberToString)(width / this.data.maxLen);
  1376. const buf = [];
  1377. const positions = font.getCharPositions(text);
  1378. for (const [start, end] of positions) {
  1379. buf.push(`(${(0, _util.escapeString)(text.substring(start, end))}) Tj`);
  1380. }
  1381. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1382. const renderedComb = buf.join(` ${combWidth} 0 Td `);
  1383. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm ${renderedComb}` + " ET Q EMC";
  1384. }
  1385. _getMultilineAppearance(defaultAppearance, text, font, fontSize, width, height, alignment, hPadding, vPadding, annotationStorage) {
  1386. const lines = text.split(/\r\n?|\n/);
  1387. const buf = [];
  1388. const totalWidth = width - 2 * hPadding;
  1389. for (const line of lines) {
  1390. const chunks = this._splitLine(line, font, fontSize, totalWidth);
  1391. for (const chunk of chunks) {
  1392. const padding = buf.length === 0 ? hPadding : 0;
  1393. buf.push(this._renderText(chunk, font, fontSize, width, alignment, padding, -fontSize));
  1394. }
  1395. }
  1396. const renderedText = buf.join("\n");
  1397. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1398. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 ${height} Tm ${renderedText}` + " ET Q EMC";
  1399. }
  1400. _splitLine(line, font, fontSize, width, cache = {}) {
  1401. line = cache.line || font.encodeString(line).join("");
  1402. const glyphs = cache.glyphs || font.charsToGlyphs(line);
  1403. if (glyphs.length <= 1) {
  1404. return [line];
  1405. }
  1406. const positions = cache.positions || font.getCharPositions(line);
  1407. const scale = fontSize / 1000;
  1408. const chunks = [];
  1409. let lastSpacePosInStringStart = -1,
  1410. lastSpacePosInStringEnd = -1,
  1411. lastSpacePos = -1,
  1412. startChunk = 0,
  1413. currentWidth = 0;
  1414. for (let i = 0, ii = glyphs.length; i < ii; i++) {
  1415. const [start, end] = positions[i];
  1416. const glyph = glyphs[i];
  1417. const glyphWidth = glyph.width * scale;
  1418. if (glyph.unicode === " ") {
  1419. if (currentWidth + glyphWidth > width) {
  1420. chunks.push(line.substring(startChunk, start));
  1421. startChunk = start;
  1422. currentWidth = glyphWidth;
  1423. lastSpacePosInStringStart = -1;
  1424. lastSpacePos = -1;
  1425. } else {
  1426. currentWidth += glyphWidth;
  1427. lastSpacePosInStringStart = start;
  1428. lastSpacePosInStringEnd = end;
  1429. lastSpacePos = i;
  1430. }
  1431. } else {
  1432. if (currentWidth + glyphWidth > width) {
  1433. if (lastSpacePosInStringStart !== -1) {
  1434. chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
  1435. startChunk = lastSpacePosInStringEnd;
  1436. i = lastSpacePos + 1;
  1437. lastSpacePosInStringStart = -1;
  1438. currentWidth = 0;
  1439. } else {
  1440. chunks.push(line.substring(startChunk, start));
  1441. startChunk = start;
  1442. currentWidth = glyphWidth;
  1443. }
  1444. } else {
  1445. currentWidth += glyphWidth;
  1446. }
  1447. }
  1448. }
  1449. if (startChunk < line.length) {
  1450. chunks.push(line.substring(startChunk, line.length));
  1451. }
  1452. return chunks;
  1453. }
  1454. getFieldObject() {
  1455. return {
  1456. id: this.data.id,
  1457. value: this.data.fieldValue,
  1458. defaultValue: this.data.defaultFieldValue || "",
  1459. multiline: this.data.multiLine,
  1460. password: this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD),
  1461. charLimit: this.data.maxLen,
  1462. comb: this.data.comb,
  1463. editable: !this.data.readOnly,
  1464. hidden: this.data.hidden,
  1465. name: this.data.fieldName,
  1466. rect: this.data.rect,
  1467. actions: this.data.actions,
  1468. page: this.data.pageIndex,
  1469. strokeColor: this.data.borderColor,
  1470. fillColor: this.data.backgroundColor,
  1471. rotation: this.rotation,
  1472. type: "text"
  1473. };
  1474. }
  1475. }
  1476. class ButtonWidgetAnnotation extends WidgetAnnotation {
  1477. constructor(params) {
  1478. super(params);
  1479. this.checkedAppearance = null;
  1480. this.uncheckedAppearance = null;
  1481. this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1482. this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1483. this.data.pushButton = this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1484. this.data.isTooltipOnly = false;
  1485. if (this.data.checkBox) {
  1486. this._processCheckBox(params);
  1487. } else if (this.data.radioButton) {
  1488. this._processRadioButton(params);
  1489. } else if (this.data.pushButton) {
  1490. this.data.hasOwnCanvas = true;
  1491. this._processPushButton(params);
  1492. } else {
  1493. (0, _util.warn)("Invalid field flags for button widget annotation");
  1494. }
  1495. }
  1496. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  1497. if (this.data.pushButton) {
  1498. return super.getOperatorList(evaluator, task, intent, false, annotationStorage);
  1499. }
  1500. let value = null;
  1501. let rotation = null;
  1502. if (annotationStorage) {
  1503. const storageEntry = annotationStorage.get(this.data.id);
  1504. value = storageEntry ? storageEntry.value : null;
  1505. rotation = storageEntry ? storageEntry.rotation : null;
  1506. }
  1507. if (value === null && this.appearance) {
  1508. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1509. }
  1510. if (value === null || value === undefined) {
  1511. if (this.data.checkBox) {
  1512. value = this.data.fieldValue === this.data.exportValue;
  1513. } else {
  1514. value = this.data.fieldValue === this.data.buttonValue;
  1515. }
  1516. }
  1517. const appearance = value ? this.checkedAppearance : this.uncheckedAppearance;
  1518. if (appearance) {
  1519. const savedAppearance = this.appearance;
  1520. const savedMatrix = appearance.dict.getArray("Matrix") || _util.IDENTITY_MATRIX;
  1521. if (rotation) {
  1522. appearance.dict.set("Matrix", this.getRotationMatrix(annotationStorage));
  1523. }
  1524. this.appearance = appearance;
  1525. const operatorList = super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1526. this.appearance = savedAppearance;
  1527. appearance.dict.set("Matrix", savedMatrix);
  1528. return operatorList;
  1529. }
  1530. return {
  1531. opList: new _operator_list.OperatorList(),
  1532. separateForm: false,
  1533. separateCanvas: false
  1534. };
  1535. }
  1536. async save(evaluator, task, annotationStorage) {
  1537. if (this.data.checkBox) {
  1538. return this._saveCheckbox(evaluator, task, annotationStorage);
  1539. }
  1540. if (this.data.radioButton) {
  1541. return this._saveRadioButton(evaluator, task, annotationStorage);
  1542. }
  1543. return null;
  1544. }
  1545. async _saveCheckbox(evaluator, task, annotationStorage) {
  1546. if (!annotationStorage) {
  1547. return null;
  1548. }
  1549. const storageEntry = annotationStorage.get(this.data.id);
  1550. let rotation = storageEntry && storageEntry.rotation;
  1551. let value = storageEntry && storageEntry.value;
  1552. if (rotation === undefined) {
  1553. if (value === undefined) {
  1554. return null;
  1555. }
  1556. const defaultValue = this.data.fieldValue === this.data.exportValue;
  1557. if (defaultValue === value) {
  1558. return null;
  1559. }
  1560. }
  1561. const dict = evaluator.xref.fetchIfRef(this.ref);
  1562. if (!(dict instanceof _primitives.Dict)) {
  1563. return null;
  1564. }
  1565. if (rotation === undefined) {
  1566. rotation = this.rotation;
  1567. }
  1568. if (value === undefined) {
  1569. value = this.data.fieldValue === this.data.exportValue;
  1570. }
  1571. const xfa = {
  1572. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1573. value: value ? this.data.exportValue : ""
  1574. };
  1575. const name = _primitives.Name.get(value ? this.data.exportValue : "Off");
  1576. dict.set("V", name);
  1577. dict.set("AS", name);
  1578. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1579. const maybeMK = this._getMKDict(rotation);
  1580. if (maybeMK) {
  1581. dict.set("MK", maybeMK);
  1582. }
  1583. const encrypt = evaluator.xref.encrypt;
  1584. let originalTransform = null;
  1585. if (encrypt) {
  1586. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1587. }
  1588. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1589. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1590. buffer.push("\nendobj\n");
  1591. return [{
  1592. ref: this.ref,
  1593. data: buffer.join(""),
  1594. xfa
  1595. }];
  1596. }
  1597. async _saveRadioButton(evaluator, task, annotationStorage) {
  1598. if (!annotationStorage) {
  1599. return null;
  1600. }
  1601. const storageEntry = annotationStorage.get(this.data.id);
  1602. let rotation = storageEntry && storageEntry.rotation;
  1603. let value = storageEntry && storageEntry.value;
  1604. if (rotation === undefined) {
  1605. if (value === undefined) {
  1606. return null;
  1607. }
  1608. const defaultValue = this.data.fieldValue === this.data.buttonValue;
  1609. if (defaultValue === value) {
  1610. return null;
  1611. }
  1612. }
  1613. const dict = evaluator.xref.fetchIfRef(this.ref);
  1614. if (!(dict instanceof _primitives.Dict)) {
  1615. return null;
  1616. }
  1617. if (value === undefined) {
  1618. value = this.data.fieldValue === this.data.buttonValue;
  1619. }
  1620. if (rotation === undefined) {
  1621. rotation = this.rotation;
  1622. }
  1623. const xfa = {
  1624. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1625. value: value ? this.data.buttonValue : ""
  1626. };
  1627. const name = _primitives.Name.get(value ? this.data.buttonValue : "Off");
  1628. let parentBuffer = null;
  1629. const encrypt = evaluator.xref.encrypt;
  1630. if (value) {
  1631. if (this.parent instanceof _primitives.Ref) {
  1632. const parent = evaluator.xref.fetch(this.parent);
  1633. let parentTransform = null;
  1634. if (encrypt) {
  1635. parentTransform = encrypt.createCipherTransform(this.parent.num, this.parent.gen);
  1636. }
  1637. parent.set("V", name);
  1638. parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
  1639. (0, _writer.writeDict)(parent, parentBuffer, parentTransform);
  1640. parentBuffer.push("\nendobj\n");
  1641. } else if (this.parent instanceof _primitives.Dict) {
  1642. this.parent.set("V", name);
  1643. }
  1644. }
  1645. dict.set("AS", name);
  1646. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1647. const maybeMK = this._getMKDict(rotation);
  1648. if (maybeMK) {
  1649. dict.set("MK", maybeMK);
  1650. }
  1651. let originalTransform = null;
  1652. if (encrypt) {
  1653. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1654. }
  1655. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1656. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1657. buffer.push("\nendobj\n");
  1658. const newRefs = [{
  1659. ref: this.ref,
  1660. data: buffer.join(""),
  1661. xfa
  1662. }];
  1663. if (parentBuffer !== null) {
  1664. newRefs.push({
  1665. ref: this.parent,
  1666. data: parentBuffer.join(""),
  1667. xfa: null
  1668. });
  1669. }
  1670. return newRefs;
  1671. }
  1672. _getDefaultCheckedAppearance(params, type) {
  1673. const width = this.data.rect[2] - this.data.rect[0];
  1674. const height = this.data.rect[3] - this.data.rect[1];
  1675. const bbox = [0, 0, width, height];
  1676. const FONT_RATIO = 0.8;
  1677. const fontSize = Math.min(width, height) * FONT_RATIO;
  1678. let metrics, char;
  1679. if (type === "check") {
  1680. metrics = {
  1681. width: 0.755 * fontSize,
  1682. height: 0.705 * fontSize
  1683. };
  1684. char = "\x33";
  1685. } else if (type === "disc") {
  1686. metrics = {
  1687. width: 0.791 * fontSize,
  1688. height: 0.705 * fontSize
  1689. };
  1690. char = "\x6C";
  1691. } else {
  1692. (0, _util.unreachable)(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
  1693. }
  1694. const xShift = (0, _core_utils.numberToString)((width - metrics.width) / 2);
  1695. const yShift = (0, _core_utils.numberToString)((height - metrics.height) / 2);
  1696. const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
  1697. const appearanceStreamDict = new _primitives.Dict(params.xref);
  1698. appearanceStreamDict.set("FormType", 1);
  1699. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  1700. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  1701. appearanceStreamDict.set("BBox", bbox);
  1702. appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
  1703. appearanceStreamDict.set("Length", appearance.length);
  1704. const resources = new _primitives.Dict(params.xref);
  1705. const font = new _primitives.Dict(params.xref);
  1706. font.set("PdfJsZaDb", this.fallbackFontDict);
  1707. resources.set("Font", font);
  1708. appearanceStreamDict.set("Resources", resources);
  1709. this.checkedAppearance = new _stream.StringStream(appearance);
  1710. this.checkedAppearance.dict = appearanceStreamDict;
  1711. this._streams.push(this.checkedAppearance);
  1712. }
  1713. _processCheckBox(params) {
  1714. const customAppearance = params.dict.get("AP");
  1715. if (!(customAppearance instanceof _primitives.Dict)) {
  1716. return;
  1717. }
  1718. const normalAppearance = customAppearance.get("N");
  1719. if (!(normalAppearance instanceof _primitives.Dict)) {
  1720. return;
  1721. }
  1722. const asValue = this._decodeFormValue(params.dict.get("AS"));
  1723. if (typeof asValue === "string") {
  1724. this.data.fieldValue = asValue;
  1725. }
  1726. const yes = this.data.fieldValue !== null && this.data.fieldValue !== "Off" ? this.data.fieldValue : "Yes";
  1727. const exportValues = normalAppearance.getKeys();
  1728. if (exportValues.length === 0) {
  1729. exportValues.push("Off", yes);
  1730. } else if (exportValues.length === 1) {
  1731. if (exportValues[0] === "Off") {
  1732. exportValues.push(yes);
  1733. } else {
  1734. exportValues.unshift("Off");
  1735. }
  1736. } else if (exportValues.includes(yes)) {
  1737. exportValues.length = 0;
  1738. exportValues.push("Off", yes);
  1739. } else {
  1740. const otherYes = exportValues.find(v => v !== "Off");
  1741. exportValues.length = 0;
  1742. exportValues.push("Off", otherYes);
  1743. }
  1744. if (!exportValues.includes(this.data.fieldValue)) {
  1745. this.data.fieldValue = "Off";
  1746. }
  1747. this.data.exportValue = exportValues[1];
  1748. this.checkedAppearance = normalAppearance.get(this.data.exportValue) || null;
  1749. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1750. if (this.checkedAppearance) {
  1751. this._streams.push(this.checkedAppearance);
  1752. } else {
  1753. this._getDefaultCheckedAppearance(params, "check");
  1754. }
  1755. if (this.uncheckedAppearance) {
  1756. this._streams.push(this.uncheckedAppearance);
  1757. }
  1758. this._fallbackFontDict = this.fallbackFontDict;
  1759. }
  1760. _processRadioButton(params) {
  1761. this.data.fieldValue = this.data.buttonValue = null;
  1762. const fieldParent = params.dict.get("Parent");
  1763. if (fieldParent instanceof _primitives.Dict) {
  1764. this.parent = params.dict.getRaw("Parent");
  1765. const fieldParentValue = fieldParent.get("V");
  1766. if (fieldParentValue instanceof _primitives.Name) {
  1767. this.data.fieldValue = this._decodeFormValue(fieldParentValue);
  1768. }
  1769. }
  1770. const appearanceStates = params.dict.get("AP");
  1771. if (!(appearanceStates instanceof _primitives.Dict)) {
  1772. return;
  1773. }
  1774. const normalAppearance = appearanceStates.get("N");
  1775. if (!(normalAppearance instanceof _primitives.Dict)) {
  1776. return;
  1777. }
  1778. for (const key of normalAppearance.getKeys()) {
  1779. if (key !== "Off") {
  1780. this.data.buttonValue = this._decodeFormValue(key);
  1781. break;
  1782. }
  1783. }
  1784. this.checkedAppearance = normalAppearance.get(this.data.buttonValue) || null;
  1785. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1786. if (this.checkedAppearance) {
  1787. this._streams.push(this.checkedAppearance);
  1788. } else {
  1789. this._getDefaultCheckedAppearance(params, "disc");
  1790. }
  1791. if (this.uncheckedAppearance) {
  1792. this._streams.push(this.uncheckedAppearance);
  1793. }
  1794. this._fallbackFontDict = this.fallbackFontDict;
  1795. }
  1796. _processPushButton(params) {
  1797. if (!params.dict.has("A") && !params.dict.has("AA") && !this.data.alternativeText) {
  1798. (0, _util.warn)("Push buttons without action dictionaries are not supported");
  1799. return;
  1800. }
  1801. this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
  1802. _catalog.Catalog.parseDestDictionary({
  1803. destDict: params.dict,
  1804. resultObj: this.data,
  1805. docBaseUrl: params.pdfManager.docBaseUrl
  1806. });
  1807. }
  1808. getFieldObject() {
  1809. let type = "button";
  1810. let exportValues;
  1811. if (this.data.checkBox) {
  1812. type = "checkbox";
  1813. exportValues = this.data.exportValue;
  1814. } else if (this.data.radioButton) {
  1815. type = "radiobutton";
  1816. exportValues = this.data.buttonValue;
  1817. }
  1818. return {
  1819. id: this.data.id,
  1820. value: this.data.fieldValue || "Off",
  1821. defaultValue: this.data.defaultFieldValue,
  1822. exportValues,
  1823. editable: !this.data.readOnly,
  1824. name: this.data.fieldName,
  1825. rect: this.data.rect,
  1826. hidden: this.data.hidden,
  1827. actions: this.data.actions,
  1828. page: this.data.pageIndex,
  1829. strokeColor: this.data.borderColor,
  1830. fillColor: this.data.backgroundColor,
  1831. rotation: this.rotation,
  1832. type
  1833. };
  1834. }
  1835. get fallbackFontDict() {
  1836. const dict = new _primitives.Dict();
  1837. dict.set("BaseFont", _primitives.Name.get("ZapfDingbats"));
  1838. dict.set("Type", _primitives.Name.get("FallbackType"));
  1839. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  1840. dict.set("Encoding", _primitives.Name.get("ZapfDingbatsEncoding"));
  1841. return (0, _util.shadow)(this, "fallbackFontDict", dict);
  1842. }
  1843. }
  1844. class ChoiceWidgetAnnotation extends WidgetAnnotation {
  1845. constructor(params) {
  1846. super(params);
  1847. this.data.options = [];
  1848. const options = (0, _core_utils.getInheritableProperty)({
  1849. dict: params.dict,
  1850. key: "Opt"
  1851. });
  1852. if (Array.isArray(options)) {
  1853. const xref = params.xref;
  1854. for (let i = 0, ii = options.length; i < ii; i++) {
  1855. const option = xref.fetchIfRef(options[i]);
  1856. const isOptionArray = Array.isArray(option);
  1857. this.data.options[i] = {
  1858. exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
  1859. displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
  1860. };
  1861. }
  1862. }
  1863. if (typeof this.data.fieldValue === "string") {
  1864. this.data.fieldValue = [this.data.fieldValue];
  1865. } else if (!this.data.fieldValue) {
  1866. this.data.fieldValue = [];
  1867. }
  1868. this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
  1869. this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
  1870. this._hasText = true;
  1871. }
  1872. getFieldObject() {
  1873. const type = this.data.combo ? "combobox" : "listbox";
  1874. const value = this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
  1875. return {
  1876. id: this.data.id,
  1877. value,
  1878. defaultValue: this.data.defaultFieldValue,
  1879. editable: !this.data.readOnly,
  1880. name: this.data.fieldName,
  1881. rect: this.data.rect,
  1882. numItems: this.data.fieldValue.length,
  1883. multipleSelection: this.data.multiSelect,
  1884. hidden: this.data.hidden,
  1885. actions: this.data.actions,
  1886. items: this.data.options,
  1887. page: this.data.pageIndex,
  1888. strokeColor: this.data.borderColor,
  1889. fillColor: this.data.backgroundColor,
  1890. rotation: this.rotation,
  1891. type
  1892. };
  1893. }
  1894. async _getAppearance(evaluator, task, annotationStorage) {
  1895. if (this.data.combo) {
  1896. return super._getAppearance(evaluator, task, annotationStorage);
  1897. }
  1898. if (!annotationStorage) {
  1899. return null;
  1900. }
  1901. const storageEntry = annotationStorage.get(this.data.id);
  1902. if (!storageEntry) {
  1903. return null;
  1904. }
  1905. const rotation = storageEntry.rotation;
  1906. let exportedValue = storageEntry.value;
  1907. if (rotation === undefined && exportedValue === undefined) {
  1908. return null;
  1909. }
  1910. if (exportedValue === undefined) {
  1911. exportedValue = this.data.fieldValue;
  1912. } else if (!Array.isArray(exportedValue)) {
  1913. exportedValue = [exportedValue];
  1914. }
  1915. const defaultPadding = 2;
  1916. const hPadding = defaultPadding;
  1917. let totalHeight = this.data.rect[3] - this.data.rect[1];
  1918. let totalWidth = this.data.rect[2] - this.data.rect[0];
  1919. if (rotation === 90 || rotation === 270) {
  1920. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  1921. }
  1922. const lineCount = this.data.options.length;
  1923. const valueIndices = [];
  1924. for (let i = 0; i < lineCount; i++) {
  1925. const {
  1926. exportValue
  1927. } = this.data.options[i];
  1928. if (exportedValue.includes(exportValue)) {
  1929. valueIndices.push(i);
  1930. }
  1931. }
  1932. if (!this._defaultAppearance) {
  1933. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  1934. }
  1935. const font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
  1936. let defaultAppearance;
  1937. let {
  1938. fontSize
  1939. } = this.data.defaultAppearanceData;
  1940. if (!fontSize) {
  1941. const lineHeight = (totalHeight - defaultPadding) / lineCount;
  1942. let lineWidth = -1;
  1943. let value;
  1944. for (const {
  1945. displayValue
  1946. } of this.data.options) {
  1947. const width = this._getTextWidth(displayValue, font);
  1948. if (width > lineWidth) {
  1949. lineWidth = width;
  1950. value = displayValue;
  1951. }
  1952. }
  1953. [defaultAppearance, fontSize] = this._computeFontSize(lineHeight, totalWidth - 2 * hPadding, value, font, -1);
  1954. } else {
  1955. defaultAppearance = this._defaultAppearance;
  1956. }
  1957. const lineHeight = fontSize * _util.LINE_FACTOR;
  1958. const vPadding = (lineHeight - fontSize) / 2;
  1959. const numberOfVisibleLines = Math.floor(totalHeight / lineHeight);
  1960. let firstIndex;
  1961. if (valueIndices.length === 1) {
  1962. const valuePosition = valueIndices[0];
  1963. const indexInPage = valuePosition % numberOfVisibleLines;
  1964. firstIndex = valuePosition - indexInPage;
  1965. } else {
  1966. firstIndex = valueIndices.length ? valueIndices[0] : 0;
  1967. }
  1968. const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount);
  1969. const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`];
  1970. if (valueIndices.length) {
  1971. buf.push("0.600006 0.756866 0.854904 rg");
  1972. for (const index of valueIndices) {
  1973. if (firstIndex <= index && index < end) {
  1974. buf.push(`1 ${totalHeight - (index - firstIndex + 1) * lineHeight} ${totalWidth} ${lineHeight} re f`);
  1975. }
  1976. }
  1977. }
  1978. buf.push("BT", defaultAppearance, `1 0 0 1 0 ${totalHeight} Tm`);
  1979. for (let i = firstIndex; i < end; i++) {
  1980. const {
  1981. displayValue
  1982. } = this.data.options[i];
  1983. const hpadding = i === firstIndex ? hPadding : 0;
  1984. const vpadding = i === firstIndex ? vPadding : 0;
  1985. buf.push(this._renderText(displayValue, font, fontSize, totalWidth, 0, hpadding, -lineHeight + vpadding));
  1986. }
  1987. buf.push("ET Q EMC");
  1988. return buf.join("\n");
  1989. }
  1990. }
  1991. class SignatureWidgetAnnotation extends WidgetAnnotation {
  1992. constructor(params) {
  1993. super(params);
  1994. this.data.fieldValue = null;
  1995. }
  1996. getFieldObject() {
  1997. return {
  1998. id: this.data.id,
  1999. value: null,
  2000. page: this.data.pageIndex,
  2001. type: "signature"
  2002. };
  2003. }
  2004. }
  2005. class TextAnnotation extends MarkupAnnotation {
  2006. constructor(parameters) {
  2007. const DEFAULT_ICON_SIZE = 22;
  2008. super(parameters);
  2009. const dict = parameters.dict;
  2010. this.data.annotationType = _util.AnnotationType.TEXT;
  2011. if (this.data.hasAppearance) {
  2012. this.data.name = "NoIcon";
  2013. } else {
  2014. this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
  2015. this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
  2016. this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
  2017. }
  2018. if (dict.has("State")) {
  2019. this.data.state = dict.get("State") || null;
  2020. this.data.stateModel = dict.get("StateModel") || null;
  2021. } else {
  2022. this.data.state = null;
  2023. this.data.stateModel = null;
  2024. }
  2025. }
  2026. }
  2027. class LinkAnnotation extends Annotation {
  2028. constructor(params) {
  2029. super(params);
  2030. this.data.annotationType = _util.AnnotationType.LINK;
  2031. const quadPoints = getQuadPoints(params.dict, this.rectangle);
  2032. if (quadPoints) {
  2033. this.data.quadPoints = quadPoints;
  2034. }
  2035. this.data.borderColor = this.data.borderColor || this.data.color;
  2036. _catalog.Catalog.parseDestDictionary({
  2037. destDict: params.dict,
  2038. resultObj: this.data,
  2039. docBaseUrl: params.pdfManager.docBaseUrl
  2040. });
  2041. }
  2042. }
  2043. class PopupAnnotation extends Annotation {
  2044. constructor(parameters) {
  2045. super(parameters);
  2046. this.data.annotationType = _util.AnnotationType.POPUP;
  2047. let parentItem = parameters.dict.get("Parent");
  2048. if (!parentItem) {
  2049. (0, _util.warn)("Popup annotation has a missing or invalid parent annotation.");
  2050. return;
  2051. }
  2052. const parentSubtype = parentItem.get("Subtype");
  2053. this.data.parentType = parentSubtype instanceof _primitives.Name ? parentSubtype.name : null;
  2054. const rawParent = parameters.dict.getRaw("Parent");
  2055. this.data.parentId = rawParent instanceof _primitives.Ref ? rawParent.toString() : null;
  2056. const parentRect = parentItem.getArray("Rect");
  2057. if (Array.isArray(parentRect) && parentRect.length === 4) {
  2058. this.data.parentRect = _util.Util.normalizeRect(parentRect);
  2059. } else {
  2060. this.data.parentRect = [0, 0, 0, 0];
  2061. }
  2062. const rt = parentItem.get("RT");
  2063. if ((0, _primitives.isName)(rt, _util.AnnotationReplyType.GROUP)) {
  2064. parentItem = parentItem.get("IRT");
  2065. }
  2066. if (!parentItem.has("M")) {
  2067. this.data.modificationDate = null;
  2068. } else {
  2069. this.setModificationDate(parentItem.get("M"));
  2070. this.data.modificationDate = this.modificationDate;
  2071. }
  2072. if (!parentItem.has("C")) {
  2073. this.data.color = null;
  2074. } else {
  2075. this.setColor(parentItem.getArray("C"));
  2076. this.data.color = this.color;
  2077. }
  2078. if (!this.viewable) {
  2079. const parentFlags = parentItem.get("F");
  2080. if (this._isViewable(parentFlags)) {
  2081. this.setFlags(parentFlags);
  2082. }
  2083. }
  2084. this.setTitle(parentItem.get("T"));
  2085. this.data.titleObj = this._title;
  2086. this.setContents(parentItem.get("Contents"));
  2087. this.data.contentsObj = this._contents;
  2088. if (parentItem.has("RC")) {
  2089. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
  2090. }
  2091. }
  2092. }
  2093. class FreeTextAnnotation extends MarkupAnnotation {
  2094. constructor(parameters) {
  2095. super(parameters);
  2096. this.data.annotationType = _util.AnnotationType.FREETEXT;
  2097. }
  2098. static createNewDict(annotation, xref, {
  2099. apRef,
  2100. ap
  2101. }) {
  2102. const {
  2103. color,
  2104. fontSize,
  2105. rect,
  2106. rotation,
  2107. user,
  2108. value
  2109. } = annotation;
  2110. const freetext = new _primitives.Dict(xref);
  2111. freetext.set("Type", _primitives.Name.get("Annot"));
  2112. freetext.set("Subtype", _primitives.Name.get("FreeText"));
  2113. freetext.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
  2114. freetext.set("Rect", rect);
  2115. const da = `/Helv ${fontSize} Tf ${(0, _default_appearance.getPdfColor)(color, true)}`;
  2116. freetext.set("DA", da);
  2117. freetext.set("Contents", value);
  2118. freetext.set("F", 4);
  2119. freetext.set("Border", [0, 0, 0]);
  2120. freetext.set("Rotate", rotation);
  2121. if (user) {
  2122. freetext.set("T", (0, _util.stringToUTF8String)(user));
  2123. }
  2124. const n = new _primitives.Dict(xref);
  2125. freetext.set("AP", n);
  2126. if (apRef) {
  2127. n.set("N", apRef);
  2128. } else {
  2129. n.set("N", ap);
  2130. }
  2131. return freetext;
  2132. }
  2133. static async createNewAppearanceStream(annotation, xref, params) {
  2134. const {
  2135. baseFontRef,
  2136. evaluator,
  2137. task
  2138. } = params;
  2139. const {
  2140. color,
  2141. fontSize,
  2142. rect,
  2143. rotation,
  2144. value
  2145. } = annotation;
  2146. const resources = new _primitives.Dict(xref);
  2147. const font = new _primitives.Dict(xref);
  2148. if (baseFontRef) {
  2149. font.set("Helv", baseFontRef);
  2150. } else {
  2151. const baseFont = new _primitives.Dict(xref);
  2152. baseFont.set("BaseFont", _primitives.Name.get("Helvetica"));
  2153. baseFont.set("Type", _primitives.Name.get("Font"));
  2154. baseFont.set("Subtype", _primitives.Name.get("Type1"));
  2155. baseFont.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
  2156. font.set("Helv", baseFont);
  2157. }
  2158. resources.set("Font", font);
  2159. const helv = await WidgetAnnotation._getFontData(evaluator, task, {
  2160. fontName: "Helvetica",
  2161. fontSize
  2162. }, resources);
  2163. const [x1, y1, x2, y2] = rect;
  2164. let w = x2 - x1;
  2165. let h = y2 - y1;
  2166. if (rotation % 180 !== 0) {
  2167. [w, h] = [h, w];
  2168. }
  2169. const lines = value.split("\n");
  2170. const scale = fontSize / 1000;
  2171. let totalWidth = -Infinity;
  2172. const encodedLines = [];
  2173. for (let line of lines) {
  2174. line = helv.encodeString(line).join("");
  2175. encodedLines.push(line);
  2176. let lineWidth = 0;
  2177. const glyphs = helv.charsToGlyphs(line);
  2178. for (const glyph of glyphs) {
  2179. lineWidth += glyph.width * scale;
  2180. }
  2181. totalWidth = Math.max(totalWidth, lineWidth);
  2182. }
  2183. let hscale = 1;
  2184. if (totalWidth > w) {
  2185. hscale = w / totalWidth;
  2186. }
  2187. let vscale = 1;
  2188. const lineHeight = _util.LINE_FACTOR * fontSize;
  2189. const lineDescent = _util.LINE_DESCENT_FACTOR * fontSize;
  2190. const totalHeight = lineHeight * lines.length;
  2191. if (totalHeight > h) {
  2192. vscale = h / totalHeight;
  2193. }
  2194. const fscale = Math.min(hscale, vscale);
  2195. const newFontSize = fontSize * fscale;
  2196. const buffer = ["q", `0 0 ${(0, _core_utils.numberToString)(w)} ${(0, _core_utils.numberToString)(h)} re W n`, `BT`, `1 0 0 1 0 ${(0, _core_utils.numberToString)(h + lineDescent)} Tm 0 Tc ${(0, _default_appearance.getPdfColor)(color, true)}`, `/Helv ${(0, _core_utils.numberToString)(newFontSize)} Tf`];
  2197. const vShift = (0, _core_utils.numberToString)(lineHeight);
  2198. for (const line of encodedLines) {
  2199. buffer.push(`0 -${vShift} Td (${(0, _util.escapeString)(line)}) Tj`);
  2200. }
  2201. buffer.push("ET", "Q");
  2202. const appearance = buffer.join("\n");
  2203. const appearanceStreamDict = new _primitives.Dict(xref);
  2204. appearanceStreamDict.set("FormType", 1);
  2205. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  2206. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  2207. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  2208. appearanceStreamDict.set("Length", appearance.length);
  2209. appearanceStreamDict.set("Resources", resources);
  2210. if (rotation) {
  2211. const matrix = WidgetAnnotation._getRotationMatrix(rotation, w, h);
  2212. appearanceStreamDict.set("Matrix", matrix);
  2213. }
  2214. const ap = new _stream.StringStream(appearance);
  2215. ap.dict = appearanceStreamDict;
  2216. return ap;
  2217. }
  2218. }
  2219. class LineAnnotation extends MarkupAnnotation {
  2220. constructor(parameters) {
  2221. super(parameters);
  2222. const {
  2223. dict
  2224. } = parameters;
  2225. this.data.annotationType = _util.AnnotationType.LINE;
  2226. const lineCoordinates = dict.getArray("L");
  2227. this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates);
  2228. this.setLineEndings(dict.getArray("LE"));
  2229. this.data.lineEndings = this.lineEndings;
  2230. if (!this.appearance) {
  2231. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2232. const strokeAlpha = dict.get("CA");
  2233. let fillColor = null,
  2234. interiorColor = dict.getArray("IC");
  2235. if (interiorColor) {
  2236. interiorColor = getRgbColor(interiorColor, null);
  2237. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  2238. }
  2239. const fillAlpha = fillColor ? strokeAlpha : null;
  2240. const borderWidth = this.borderStyle.width || 1,
  2241. borderAdjust = 2 * borderWidth;
  2242. const bbox = [this.data.lineCoordinates[0] - borderAdjust, this.data.lineCoordinates[1] - borderAdjust, this.data.lineCoordinates[2] + borderAdjust, this.data.lineCoordinates[3] + borderAdjust];
  2243. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2244. this.rectangle = bbox;
  2245. }
  2246. this._setDefaultAppearance({
  2247. xref: parameters.xref,
  2248. extra: `${borderWidth} w`,
  2249. strokeColor,
  2250. fillColor,
  2251. strokeAlpha,
  2252. fillAlpha,
  2253. pointsCallback: (buffer, points) => {
  2254. buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`, `${lineCoordinates[2]} ${lineCoordinates[3]} l`, "S");
  2255. return [points[0].x - borderWidth, points[1].x + borderWidth, points[3].y - borderWidth, points[1].y + borderWidth];
  2256. }
  2257. });
  2258. }
  2259. }
  2260. }
  2261. class SquareAnnotation extends MarkupAnnotation {
  2262. constructor(parameters) {
  2263. super(parameters);
  2264. this.data.annotationType = _util.AnnotationType.SQUARE;
  2265. if (!this.appearance) {
  2266. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2267. const strokeAlpha = parameters.dict.get("CA");
  2268. let fillColor = null,
  2269. interiorColor = parameters.dict.getArray("IC");
  2270. if (interiorColor) {
  2271. interiorColor = getRgbColor(interiorColor, null);
  2272. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  2273. }
  2274. const fillAlpha = fillColor ? strokeAlpha : null;
  2275. if (this.borderStyle.width === 0 && !fillColor) {
  2276. return;
  2277. }
  2278. this._setDefaultAppearance({
  2279. xref: parameters.xref,
  2280. extra: `${this.borderStyle.width} w`,
  2281. strokeColor,
  2282. fillColor,
  2283. strokeAlpha,
  2284. fillAlpha,
  2285. pointsCallback: (buffer, points) => {
  2286. const x = points[2].x + this.borderStyle.width / 2;
  2287. const y = points[2].y + this.borderStyle.width / 2;
  2288. const width = points[3].x - points[2].x - this.borderStyle.width;
  2289. const height = points[1].y - points[3].y - this.borderStyle.width;
  2290. buffer.push(`${x} ${y} ${width} ${height} re`);
  2291. if (fillColor) {
  2292. buffer.push("B");
  2293. } else {
  2294. buffer.push("S");
  2295. }
  2296. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2297. }
  2298. });
  2299. }
  2300. }
  2301. }
  2302. class CircleAnnotation extends MarkupAnnotation {
  2303. constructor(parameters) {
  2304. super(parameters);
  2305. this.data.annotationType = _util.AnnotationType.CIRCLE;
  2306. if (!this.appearance) {
  2307. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2308. const strokeAlpha = parameters.dict.get("CA");
  2309. let fillColor = null;
  2310. let interiorColor = parameters.dict.getArray("IC");
  2311. if (interiorColor) {
  2312. interiorColor = getRgbColor(interiorColor, null);
  2313. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  2314. }
  2315. const fillAlpha = fillColor ? strokeAlpha : null;
  2316. if (this.borderStyle.width === 0 && !fillColor) {
  2317. return;
  2318. }
  2319. const controlPointsDistance = 4 / 3 * Math.tan(Math.PI / (2 * 4));
  2320. this._setDefaultAppearance({
  2321. xref: parameters.xref,
  2322. extra: `${this.borderStyle.width} w`,
  2323. strokeColor,
  2324. fillColor,
  2325. strokeAlpha,
  2326. fillAlpha,
  2327. pointsCallback: (buffer, points) => {
  2328. const x0 = points[0].x + this.borderStyle.width / 2;
  2329. const y0 = points[0].y - this.borderStyle.width / 2;
  2330. const x1 = points[3].x - this.borderStyle.width / 2;
  2331. const y1 = points[3].y + this.borderStyle.width / 2;
  2332. const xMid = x0 + (x1 - x0) / 2;
  2333. const yMid = y0 + (y1 - y0) / 2;
  2334. const xOffset = (x1 - x0) / 2 * controlPointsDistance;
  2335. const yOffset = (y1 - y0) / 2 * controlPointsDistance;
  2336. 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");
  2337. if (fillColor) {
  2338. buffer.push("B");
  2339. } else {
  2340. buffer.push("S");
  2341. }
  2342. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2343. }
  2344. });
  2345. }
  2346. }
  2347. }
  2348. class PolylineAnnotation extends MarkupAnnotation {
  2349. constructor(parameters) {
  2350. super(parameters);
  2351. const {
  2352. dict
  2353. } = parameters;
  2354. this.data.annotationType = _util.AnnotationType.POLYLINE;
  2355. this.data.vertices = [];
  2356. if (!(this instanceof PolygonAnnotation)) {
  2357. this.setLineEndings(dict.getArray("LE"));
  2358. this.data.lineEndings = this.lineEndings;
  2359. }
  2360. const rawVertices = dict.getArray("Vertices");
  2361. if (!Array.isArray(rawVertices)) {
  2362. return;
  2363. }
  2364. for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
  2365. this.data.vertices.push({
  2366. x: rawVertices[i],
  2367. y: rawVertices[i + 1]
  2368. });
  2369. }
  2370. if (!this.appearance) {
  2371. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2372. const strokeAlpha = dict.get("CA");
  2373. const borderWidth = this.borderStyle.width || 1,
  2374. borderAdjust = 2 * borderWidth;
  2375. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  2376. for (const vertex of this.data.vertices) {
  2377. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  2378. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  2379. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  2380. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  2381. }
  2382. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2383. this.rectangle = bbox;
  2384. }
  2385. this._setDefaultAppearance({
  2386. xref: parameters.xref,
  2387. extra: `${borderWidth} w`,
  2388. strokeColor,
  2389. strokeAlpha,
  2390. pointsCallback: (buffer, points) => {
  2391. const vertices = this.data.vertices;
  2392. for (let i = 0, ii = vertices.length; i < ii; i++) {
  2393. buffer.push(`${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`);
  2394. }
  2395. buffer.push("S");
  2396. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2397. }
  2398. });
  2399. }
  2400. }
  2401. }
  2402. class PolygonAnnotation extends PolylineAnnotation {
  2403. constructor(parameters) {
  2404. super(parameters);
  2405. this.data.annotationType = _util.AnnotationType.POLYGON;
  2406. }
  2407. }
  2408. class CaretAnnotation extends MarkupAnnotation {
  2409. constructor(parameters) {
  2410. super(parameters);
  2411. this.data.annotationType = _util.AnnotationType.CARET;
  2412. }
  2413. }
  2414. class InkAnnotation extends MarkupAnnotation {
  2415. constructor(parameters) {
  2416. super(parameters);
  2417. this.data.annotationType = _util.AnnotationType.INK;
  2418. this.data.inkLists = [];
  2419. const rawInkLists = parameters.dict.getArray("InkList");
  2420. if (!Array.isArray(rawInkLists)) {
  2421. return;
  2422. }
  2423. const xref = parameters.xref;
  2424. for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
  2425. this.data.inkLists.push([]);
  2426. for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
  2427. this.data.inkLists[i].push({
  2428. x: xref.fetchIfRef(rawInkLists[i][j]),
  2429. y: xref.fetchIfRef(rawInkLists[i][j + 1])
  2430. });
  2431. }
  2432. }
  2433. if (!this.appearance) {
  2434. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2435. const strokeAlpha = parameters.dict.get("CA");
  2436. const borderWidth = this.borderStyle.width || 1,
  2437. borderAdjust = 2 * borderWidth;
  2438. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  2439. for (const inkLists of this.data.inkLists) {
  2440. for (const vertex of inkLists) {
  2441. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  2442. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  2443. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  2444. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  2445. }
  2446. }
  2447. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2448. this.rectangle = bbox;
  2449. }
  2450. this._setDefaultAppearance({
  2451. xref: parameters.xref,
  2452. extra: `${borderWidth} w`,
  2453. strokeColor,
  2454. strokeAlpha,
  2455. pointsCallback: (buffer, points) => {
  2456. for (const inkList of this.data.inkLists) {
  2457. for (let i = 0, ii = inkList.length; i < ii; i++) {
  2458. buffer.push(`${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`);
  2459. }
  2460. buffer.push("S");
  2461. }
  2462. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2463. }
  2464. });
  2465. }
  2466. }
  2467. static createNewDict(annotation, xref, {
  2468. apRef,
  2469. ap
  2470. }) {
  2471. const {
  2472. paths,
  2473. rect,
  2474. rotation
  2475. } = annotation;
  2476. const ink = new _primitives.Dict(xref);
  2477. ink.set("Type", _primitives.Name.get("Annot"));
  2478. ink.set("Subtype", _primitives.Name.get("Ink"));
  2479. ink.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
  2480. ink.set("Rect", rect);
  2481. ink.set("InkList", paths.map(p => p.points));
  2482. ink.set("F", 4);
  2483. ink.set("Border", [0, 0, 0]);
  2484. ink.set("Rotate", rotation);
  2485. const n = new _primitives.Dict(xref);
  2486. ink.set("AP", n);
  2487. if (apRef) {
  2488. n.set("N", apRef);
  2489. } else {
  2490. n.set("N", ap);
  2491. }
  2492. return ink;
  2493. }
  2494. static async createNewAppearanceStream(annotation, xref, params) {
  2495. const {
  2496. color,
  2497. rect,
  2498. rotation,
  2499. paths,
  2500. thickness,
  2501. opacity
  2502. } = annotation;
  2503. const [x1, y1, x2, y2] = rect;
  2504. let w = x2 - x1;
  2505. let h = y2 - y1;
  2506. if (rotation % 180 !== 0) {
  2507. [w, h] = [h, w];
  2508. }
  2509. const appearanceBuffer = [`${thickness} w 1 J 1 j`, `${(0, _default_appearance.getPdfColor)(color, false)}`];
  2510. if (opacity !== 1) {
  2511. appearanceBuffer.push("/R0 gs");
  2512. }
  2513. const buffer = [];
  2514. for (const {
  2515. bezier
  2516. } of paths) {
  2517. buffer.length = 0;
  2518. buffer.push(`${(0, _core_utils.numberToString)(bezier[0])} ${(0, _core_utils.numberToString)(bezier[1])} m`);
  2519. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  2520. const curve = bezier.slice(i, i + 6).map(_core_utils.numberToString).join(" ");
  2521. buffer.push(`${curve} c`);
  2522. }
  2523. buffer.push("S");
  2524. appearanceBuffer.push(buffer.join("\n"));
  2525. }
  2526. const appearance = appearanceBuffer.join("\n");
  2527. const appearanceStreamDict = new _primitives.Dict(xref);
  2528. appearanceStreamDict.set("FormType", 1);
  2529. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  2530. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  2531. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  2532. appearanceStreamDict.set("Length", appearance.length);
  2533. if (rotation) {
  2534. const matrix = WidgetAnnotation._getRotationMatrix(rotation, w, h);
  2535. appearanceStreamDict.set("Matrix", matrix);
  2536. }
  2537. if (opacity !== 1) {
  2538. const resources = new _primitives.Dict(xref);
  2539. const extGState = new _primitives.Dict(xref);
  2540. const r0 = new _primitives.Dict(xref);
  2541. r0.set("CA", opacity);
  2542. r0.set("Type", _primitives.Name.get("ExtGState"));
  2543. extGState.set("R0", r0);
  2544. resources.set("ExtGState", extGState);
  2545. appearanceStreamDict.set("Resources", resources);
  2546. }
  2547. const ap = new _stream.StringStream(appearance);
  2548. ap.dict = appearanceStreamDict;
  2549. return ap;
  2550. }
  2551. }
  2552. class HighlightAnnotation extends MarkupAnnotation {
  2553. constructor(parameters) {
  2554. super(parameters);
  2555. this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
  2556. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2557. if (quadPoints) {
  2558. const resources = this.appearance && this.appearance.dict.get("Resources");
  2559. if (!this.appearance || !(resources && resources.has("ExtGState"))) {
  2560. if (this.appearance) {
  2561. (0, _util.warn)("HighlightAnnotation - ignoring built-in appearance stream.");
  2562. }
  2563. const fillColor = this.color ? Array.from(this.color).map(c => c / 255) : [1, 1, 0];
  2564. const fillAlpha = parameters.dict.get("CA");
  2565. this._setDefaultAppearance({
  2566. xref: parameters.xref,
  2567. fillColor,
  2568. blendMode: "Multiply",
  2569. fillAlpha,
  2570. pointsCallback: (buffer, points) => {
  2571. 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");
  2572. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2573. }
  2574. });
  2575. }
  2576. } else {
  2577. this.data.hasPopup = false;
  2578. }
  2579. }
  2580. }
  2581. class UnderlineAnnotation extends MarkupAnnotation {
  2582. constructor(parameters) {
  2583. super(parameters);
  2584. this.data.annotationType = _util.AnnotationType.UNDERLINE;
  2585. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2586. if (quadPoints) {
  2587. if (!this.appearance) {
  2588. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2589. const strokeAlpha = parameters.dict.get("CA");
  2590. this._setDefaultAppearance({
  2591. xref: parameters.xref,
  2592. extra: "[] 0 d 1 w",
  2593. strokeColor,
  2594. strokeAlpha,
  2595. pointsCallback: (buffer, points) => {
  2596. buffer.push(`${points[2].x} ${points[2].y} m`, `${points[3].x} ${points[3].y} l`, "S");
  2597. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2598. }
  2599. });
  2600. }
  2601. } else {
  2602. this.data.hasPopup = false;
  2603. }
  2604. }
  2605. }
  2606. class SquigglyAnnotation extends MarkupAnnotation {
  2607. constructor(parameters) {
  2608. super(parameters);
  2609. this.data.annotationType = _util.AnnotationType.SQUIGGLY;
  2610. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2611. if (quadPoints) {
  2612. if (!this.appearance) {
  2613. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2614. const strokeAlpha = parameters.dict.get("CA");
  2615. this._setDefaultAppearance({
  2616. xref: parameters.xref,
  2617. extra: "[] 0 d 1 w",
  2618. strokeColor,
  2619. strokeAlpha,
  2620. pointsCallback: (buffer, points) => {
  2621. const dy = (points[0].y - points[2].y) / 6;
  2622. let shift = dy;
  2623. let x = points[2].x;
  2624. const y = points[2].y;
  2625. const xEnd = points[3].x;
  2626. buffer.push(`${x} ${y + shift} m`);
  2627. do {
  2628. x += 2;
  2629. shift = shift === 0 ? dy : 0;
  2630. buffer.push(`${x} ${y + shift} l`);
  2631. } while (x < xEnd);
  2632. buffer.push("S");
  2633. return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
  2634. }
  2635. });
  2636. }
  2637. } else {
  2638. this.data.hasPopup = false;
  2639. }
  2640. }
  2641. }
  2642. class StrikeOutAnnotation extends MarkupAnnotation {
  2643. constructor(parameters) {
  2644. super(parameters);
  2645. this.data.annotationType = _util.AnnotationType.STRIKEOUT;
  2646. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2647. if (quadPoints) {
  2648. if (!this.appearance) {
  2649. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2650. const strokeAlpha = parameters.dict.get("CA");
  2651. this._setDefaultAppearance({
  2652. xref: parameters.xref,
  2653. extra: "[] 0 d 1 w",
  2654. strokeColor,
  2655. strokeAlpha,
  2656. pointsCallback: (buffer, points) => {
  2657. 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");
  2658. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2659. }
  2660. });
  2661. }
  2662. } else {
  2663. this.data.hasPopup = false;
  2664. }
  2665. }
  2666. }
  2667. class StampAnnotation extends MarkupAnnotation {
  2668. constructor(parameters) {
  2669. super(parameters);
  2670. this.data.annotationType = _util.AnnotationType.STAMP;
  2671. }
  2672. }
  2673. class FileAttachmentAnnotation extends MarkupAnnotation {
  2674. constructor(parameters) {
  2675. super(parameters);
  2676. const file = new _file_spec.FileSpec(parameters.dict.get("FS"), parameters.xref);
  2677. this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
  2678. this.data.file = file.serializable;
  2679. }
  2680. }