annotation.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369
  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.PopupAnnotation = 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. get hasTextContent() {
  571. return false;
  572. }
  573. async extractTextContent(evaluator, task, viewBox) {
  574. if (!this.appearance) {
  575. return;
  576. }
  577. const resources = await this.loadResources(["ExtGState", "Font", "Properties", "XObject"], this.appearance);
  578. const text = [];
  579. const buffer = [];
  580. const sink = {
  581. desiredSize: Math.Infinity,
  582. ready: true,
  583. enqueue(chunk, size) {
  584. for (const item of chunk.items) {
  585. buffer.push(item.str);
  586. if (item.hasEOL) {
  587. text.push(buffer.join(""));
  588. buffer.length = 0;
  589. }
  590. }
  591. }
  592. };
  593. await evaluator.getTextContent({
  594. stream: this.appearance,
  595. task,
  596. resources,
  597. includeMarkedContent: true,
  598. combineTextItems: true,
  599. sink,
  600. viewBox
  601. });
  602. this.reset();
  603. if (buffer.length) {
  604. text.push(buffer.join(""));
  605. }
  606. if (text.length > 0) {
  607. this.data.textContent = text;
  608. }
  609. }
  610. getFieldObject() {
  611. if (this.data.kidIds) {
  612. return {
  613. id: this.data.id,
  614. actions: this.data.actions,
  615. name: this.data.fieldName,
  616. strokeColor: this.data.borderColor,
  617. fillColor: this.data.backgroundColor,
  618. type: "",
  619. kidIds: this.data.kidIds,
  620. page: this.data.pageIndex,
  621. rotation: this.rotation
  622. };
  623. }
  624. return null;
  625. }
  626. reset() {
  627. for (const stream of this._streams) {
  628. stream.reset();
  629. }
  630. }
  631. _constructFieldName(dict) {
  632. if (!dict.has("T") && !dict.has("Parent")) {
  633. (0, _util.warn)("Unknown field name, falling back to empty field name.");
  634. return "";
  635. }
  636. if (!dict.has("Parent")) {
  637. return (0, _util.stringToPDFString)(dict.get("T"));
  638. }
  639. const fieldName = [];
  640. if (dict.has("T")) {
  641. fieldName.unshift((0, _util.stringToPDFString)(dict.get("T")));
  642. }
  643. let loopDict = dict;
  644. const visited = new _primitives.RefSet();
  645. if (dict.objId) {
  646. visited.put(dict.objId);
  647. }
  648. while (loopDict.has("Parent")) {
  649. loopDict = loopDict.get("Parent");
  650. if (!(loopDict instanceof _primitives.Dict) || loopDict.objId && visited.has(loopDict.objId)) {
  651. break;
  652. }
  653. if (loopDict.objId) {
  654. visited.put(loopDict.objId);
  655. }
  656. if (loopDict.has("T")) {
  657. fieldName.unshift((0, _util.stringToPDFString)(loopDict.get("T")));
  658. }
  659. }
  660. return fieldName.join(".");
  661. }
  662. }
  663. exports.Annotation = Annotation;
  664. class AnnotationBorderStyle {
  665. constructor() {
  666. this.width = 1;
  667. this.style = _util.AnnotationBorderStyleType.SOLID;
  668. this.dashArray = [3];
  669. this.horizontalCornerRadius = 0;
  670. this.verticalCornerRadius = 0;
  671. }
  672. setWidth(width, rect = [0, 0, 0, 0]) {
  673. if (width instanceof _primitives.Name) {
  674. this.width = 0;
  675. return;
  676. }
  677. if (typeof width === "number") {
  678. if (width > 0) {
  679. const maxWidth = (rect[2] - rect[0]) / 2;
  680. const maxHeight = (rect[3] - rect[1]) / 2;
  681. if (maxWidth > 0 && maxHeight > 0 && (width > maxWidth || width > maxHeight)) {
  682. (0, _util.warn)(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
  683. width = 1;
  684. }
  685. }
  686. this.width = width;
  687. }
  688. }
  689. setStyle(style) {
  690. if (!(style instanceof _primitives.Name)) {
  691. return;
  692. }
  693. switch (style.name) {
  694. case "S":
  695. this.style = _util.AnnotationBorderStyleType.SOLID;
  696. break;
  697. case "D":
  698. this.style = _util.AnnotationBorderStyleType.DASHED;
  699. break;
  700. case "B":
  701. this.style = _util.AnnotationBorderStyleType.BEVELED;
  702. break;
  703. case "I":
  704. this.style = _util.AnnotationBorderStyleType.INSET;
  705. break;
  706. case "U":
  707. this.style = _util.AnnotationBorderStyleType.UNDERLINE;
  708. break;
  709. default:
  710. break;
  711. }
  712. }
  713. setDashArray(dashArray, forceStyle = false) {
  714. if (Array.isArray(dashArray) && dashArray.length > 0) {
  715. let isValid = true;
  716. let allZeros = true;
  717. for (const element of dashArray) {
  718. const validNumber = +element >= 0;
  719. if (!validNumber) {
  720. isValid = false;
  721. break;
  722. } else if (element > 0) {
  723. allZeros = false;
  724. }
  725. }
  726. if (isValid && !allZeros) {
  727. this.dashArray = dashArray;
  728. if (forceStyle) {
  729. this.setStyle(_primitives.Name.get("D"));
  730. }
  731. } else {
  732. this.width = 0;
  733. }
  734. } else if (dashArray) {
  735. this.width = 0;
  736. }
  737. }
  738. setHorizontalCornerRadius(radius) {
  739. if (Number.isInteger(radius)) {
  740. this.horizontalCornerRadius = radius;
  741. }
  742. }
  743. setVerticalCornerRadius(radius) {
  744. if (Number.isInteger(radius)) {
  745. this.verticalCornerRadius = radius;
  746. }
  747. }
  748. }
  749. exports.AnnotationBorderStyle = AnnotationBorderStyle;
  750. class MarkupAnnotation extends Annotation {
  751. constructor(parameters) {
  752. super(parameters);
  753. const dict = parameters.dict;
  754. if (dict.has("IRT")) {
  755. const rawIRT = dict.getRaw("IRT");
  756. this.data.inReplyTo = rawIRT instanceof _primitives.Ref ? rawIRT.toString() : null;
  757. const rt = dict.get("RT");
  758. this.data.replyType = rt instanceof _primitives.Name ? rt.name : _util.AnnotationReplyType.REPLY;
  759. }
  760. if (this.data.replyType === _util.AnnotationReplyType.GROUP) {
  761. const parent = dict.get("IRT");
  762. this.setTitle(parent.get("T"));
  763. this.data.titleObj = this._title;
  764. this.setContents(parent.get("Contents"));
  765. this.data.contentsObj = this._contents;
  766. if (!parent.has("CreationDate")) {
  767. this.data.creationDate = null;
  768. } else {
  769. this.setCreationDate(parent.get("CreationDate"));
  770. this.data.creationDate = this.creationDate;
  771. }
  772. if (!parent.has("M")) {
  773. this.data.modificationDate = null;
  774. } else {
  775. this.setModificationDate(parent.get("M"));
  776. this.data.modificationDate = this.modificationDate;
  777. }
  778. this.data.hasPopup = parent.has("Popup");
  779. if (!parent.has("C")) {
  780. this.data.color = null;
  781. } else {
  782. this.setColor(parent.getArray("C"));
  783. this.data.color = this.color;
  784. }
  785. } else {
  786. this.data.titleObj = this._title;
  787. this.setCreationDate(dict.get("CreationDate"));
  788. this.data.creationDate = this.creationDate;
  789. this.data.hasPopup = dict.has("Popup");
  790. if (!dict.has("C")) {
  791. this.data.color = null;
  792. }
  793. }
  794. if (dict.has("RC")) {
  795. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(dict.get("RC"));
  796. }
  797. }
  798. setCreationDate(creationDate) {
  799. this.creationDate = typeof creationDate === "string" ? creationDate : null;
  800. }
  801. _setDefaultAppearance({
  802. xref,
  803. extra,
  804. strokeColor,
  805. fillColor,
  806. blendMode,
  807. strokeAlpha,
  808. fillAlpha,
  809. pointsCallback
  810. }) {
  811. let minX = Number.MAX_VALUE;
  812. let minY = Number.MAX_VALUE;
  813. let maxX = Number.MIN_VALUE;
  814. let maxY = Number.MIN_VALUE;
  815. const buffer = ["q"];
  816. if (extra) {
  817. buffer.push(extra);
  818. }
  819. if (strokeColor) {
  820. buffer.push(`${strokeColor[0]} ${strokeColor[1]} ${strokeColor[2]} RG`);
  821. }
  822. if (fillColor) {
  823. buffer.push(`${fillColor[0]} ${fillColor[1]} ${fillColor[2]} rg`);
  824. }
  825. let pointsArray = this.data.quadPoints;
  826. if (!pointsArray) {
  827. pointsArray = [[{
  828. x: this.rectangle[0],
  829. y: this.rectangle[3]
  830. }, {
  831. x: this.rectangle[2],
  832. y: this.rectangle[3]
  833. }, {
  834. x: this.rectangle[0],
  835. y: this.rectangle[1]
  836. }, {
  837. x: this.rectangle[2],
  838. y: this.rectangle[1]
  839. }]];
  840. }
  841. for (const points of pointsArray) {
  842. const [mX, MX, mY, MY] = pointsCallback(buffer, points);
  843. minX = Math.min(minX, mX);
  844. maxX = Math.max(maxX, MX);
  845. minY = Math.min(minY, mY);
  846. maxY = Math.max(maxY, MY);
  847. }
  848. buffer.push("Q");
  849. const formDict = new _primitives.Dict(xref);
  850. const appearanceStreamDict = new _primitives.Dict(xref);
  851. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  852. const appearanceStream = new _stream.StringStream(buffer.join(" "));
  853. appearanceStream.dict = appearanceStreamDict;
  854. formDict.set("Fm0", appearanceStream);
  855. const gsDict = new _primitives.Dict(xref);
  856. if (blendMode) {
  857. gsDict.set("BM", _primitives.Name.get(blendMode));
  858. }
  859. if (typeof strokeAlpha === "number") {
  860. gsDict.set("CA", strokeAlpha);
  861. }
  862. if (typeof fillAlpha === "number") {
  863. gsDict.set("ca", fillAlpha);
  864. }
  865. const stateDict = new _primitives.Dict(xref);
  866. stateDict.set("GS0", gsDict);
  867. const resources = new _primitives.Dict(xref);
  868. resources.set("ExtGState", stateDict);
  869. resources.set("XObject", formDict);
  870. const appearanceDict = new _primitives.Dict(xref);
  871. appearanceDict.set("Resources", resources);
  872. const bbox = this.data.rect = [minX, minY, maxX, maxY];
  873. appearanceDict.set("BBox", bbox);
  874. this.appearance = new _stream.StringStream("/GS0 gs /Fm0 Do");
  875. this.appearance.dict = appearanceDict;
  876. this._streams.push(this.appearance, appearanceStream);
  877. }
  878. static async createNewAnnotation(xref, annotation, dependencies, params) {
  879. const annotationRef = xref.getNewRef();
  880. const apRef = xref.getNewRef();
  881. const annotationDict = this.createNewDict(annotation, xref, {
  882. apRef
  883. });
  884. const ap = await this.createNewAppearanceStream(annotation, xref, params);
  885. const buffer = [];
  886. let transform = xref.encrypt ? xref.encrypt.createCipherTransform(apRef.num, apRef.gen) : null;
  887. (0, _writer.writeObject)(apRef, ap, buffer, transform);
  888. dependencies.push({
  889. ref: apRef,
  890. data: buffer.join("")
  891. });
  892. buffer.length = 0;
  893. transform = xref.encrypt ? xref.encrypt.createCipherTransform(annotationRef.num, annotationRef.gen) : null;
  894. (0, _writer.writeObject)(annotationRef, annotationDict, buffer, transform);
  895. return {
  896. ref: annotationRef,
  897. data: buffer.join("")
  898. };
  899. }
  900. static async createNewPrintAnnotation(xref, annotation, params) {
  901. const ap = await this.createNewAppearanceStream(annotation, xref, params);
  902. const annotationDict = this.createNewDict(annotation, xref, {
  903. ap
  904. });
  905. return new this.prototype.constructor({
  906. dict: annotationDict,
  907. xref
  908. });
  909. }
  910. }
  911. exports.MarkupAnnotation = MarkupAnnotation;
  912. class WidgetAnnotation extends Annotation {
  913. constructor(params) {
  914. super(params);
  915. const dict = params.dict;
  916. const data = this.data;
  917. this.ref = params.ref;
  918. data.annotationType = _util.AnnotationType.WIDGET;
  919. if (data.fieldName === undefined) {
  920. data.fieldName = this._constructFieldName(dict);
  921. }
  922. if (data.actions === undefined) {
  923. data.actions = (0, _core_utils.collectActions)(params.xref, dict, _util.AnnotationActionEventType);
  924. }
  925. let fieldValue = (0, _core_utils.getInheritableProperty)({
  926. dict,
  927. key: "V",
  928. getArray: true
  929. });
  930. data.fieldValue = this._decodeFormValue(fieldValue);
  931. const defaultFieldValue = (0, _core_utils.getInheritableProperty)({
  932. dict,
  933. key: "DV",
  934. getArray: true
  935. });
  936. data.defaultFieldValue = this._decodeFormValue(defaultFieldValue);
  937. if (fieldValue === undefined && params.xfaDatasets) {
  938. const path = this._title.str;
  939. if (path) {
  940. this._hasValueFromXFA = true;
  941. data.fieldValue = fieldValue = params.xfaDatasets.getValue(path);
  942. }
  943. }
  944. if (fieldValue === undefined && data.defaultFieldValue !== null) {
  945. data.fieldValue = data.defaultFieldValue;
  946. }
  947. data.alternativeText = (0, _util.stringToPDFString)(dict.get("TU") || "");
  948. const defaultAppearance = (0, _core_utils.getInheritableProperty)({
  949. dict,
  950. key: "DA"
  951. }) || params.acroForm.get("DA");
  952. this._defaultAppearance = typeof defaultAppearance === "string" ? defaultAppearance : "";
  953. data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance);
  954. const fieldType = (0, _core_utils.getInheritableProperty)({
  955. dict,
  956. key: "FT"
  957. });
  958. data.fieldType = fieldType instanceof _primitives.Name ? fieldType.name : null;
  959. const localResources = (0, _core_utils.getInheritableProperty)({
  960. dict,
  961. key: "DR"
  962. });
  963. const acroFormResources = params.acroForm.get("DR");
  964. const appearanceResources = this.appearance && this.appearance.dict.get("Resources");
  965. this._fieldResources = {
  966. localResources,
  967. acroFormResources,
  968. appearanceResources,
  969. mergedResources: _primitives.Dict.merge({
  970. xref: params.xref,
  971. dictArray: [localResources, appearanceResources, acroFormResources],
  972. mergeSubDicts: true
  973. })
  974. };
  975. data.fieldFlags = (0, _core_utils.getInheritableProperty)({
  976. dict,
  977. key: "Ff"
  978. });
  979. if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
  980. data.fieldFlags = 0;
  981. }
  982. data.readOnly = this.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
  983. data.required = this.hasFieldFlag(_util.AnnotationFieldFlag.REQUIRED);
  984. data.hidden = this._hasFlag(data.annotationFlags, _util.AnnotationFlag.HIDDEN);
  985. }
  986. _decodeFormValue(formValue) {
  987. if (Array.isArray(formValue)) {
  988. return formValue.filter(item => typeof item === "string").map(item => (0, _util.stringToPDFString)(item));
  989. } else if (formValue instanceof _primitives.Name) {
  990. return (0, _util.stringToPDFString)(formValue.name);
  991. } else if (typeof formValue === "string") {
  992. return (0, _util.stringToPDFString)(formValue);
  993. }
  994. return null;
  995. }
  996. hasFieldFlag(flag) {
  997. return !!(this.data.fieldFlags & flag);
  998. }
  999. static _getRotationMatrix(rotation, width, height) {
  1000. switch (rotation) {
  1001. case 90:
  1002. return [0, 1, -1, 0, width, 0];
  1003. case 180:
  1004. return [-1, 0, 0, -1, width, height];
  1005. case 270:
  1006. return [0, -1, 1, 0, 0, height];
  1007. default:
  1008. throw new Error("Invalid rotation");
  1009. }
  1010. }
  1011. getRotationMatrix(annotationStorage) {
  1012. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  1013. let rotation = storageEntry && storageEntry.rotation;
  1014. if (rotation === undefined) {
  1015. rotation = this.rotation;
  1016. }
  1017. if (rotation === 0) {
  1018. return _util.IDENTITY_MATRIX;
  1019. }
  1020. const width = this.data.rect[2] - this.data.rect[0];
  1021. const height = this.data.rect[3] - this.data.rect[1];
  1022. return WidgetAnnotation._getRotationMatrix(rotation, width, height);
  1023. }
  1024. getBorderAndBackgroundAppearances(annotationStorage) {
  1025. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  1026. let rotation = storageEntry && storageEntry.rotation;
  1027. if (rotation === undefined) {
  1028. rotation = this.rotation;
  1029. }
  1030. if (!this.backgroundColor && !this.borderColor) {
  1031. return "";
  1032. }
  1033. const width = this.data.rect[2] - this.data.rect[0];
  1034. const height = this.data.rect[3] - this.data.rect[1];
  1035. const rect = rotation === 0 || rotation === 180 ? `0 0 ${width} ${height} re` : `0 0 ${height} ${width} re`;
  1036. let str = "";
  1037. if (this.backgroundColor) {
  1038. str = `${(0, _default_appearance.getPdfColor)(this.backgroundColor, true)} ${rect} f `;
  1039. }
  1040. if (this.borderColor) {
  1041. const borderWidth = this.borderStyle.width || 1;
  1042. str += `${borderWidth} w ${(0, _default_appearance.getPdfColor)(this.borderColor, false)} ${rect} S `;
  1043. }
  1044. return str;
  1045. }
  1046. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  1047. if (renderForms && !(this instanceof SignatureWidgetAnnotation)) {
  1048. return {
  1049. opList: new _operator_list.OperatorList(),
  1050. separateForm: true,
  1051. separateCanvas: false
  1052. };
  1053. }
  1054. if (!this._hasText) {
  1055. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1056. }
  1057. const content = await this._getAppearance(evaluator, task, annotationStorage);
  1058. if (this.appearance && content === null) {
  1059. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1060. }
  1061. const opList = new _operator_list.OperatorList();
  1062. if (!this._defaultAppearance || content === null) {
  1063. return {
  1064. opList,
  1065. separateForm: false,
  1066. separateCanvas: false
  1067. };
  1068. }
  1069. const matrix = [1, 0, 0, 1, 0, 0];
  1070. const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
  1071. const transform = getTransformMatrix(this.data.rect, bbox, matrix);
  1072. let optionalContent;
  1073. if (this.oc) {
  1074. optionalContent = await evaluator.parseMarkedContentProps(this.oc, null);
  1075. }
  1076. if (optionalContent !== undefined) {
  1077. opList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
  1078. }
  1079. opList.addOp(_util.OPS.beginAnnotation, [this.data.id, this.data.rect, transform, this.getRotationMatrix(annotationStorage), false]);
  1080. const stream = new _stream.StringStream(content);
  1081. await evaluator.getOperatorList({
  1082. stream,
  1083. task,
  1084. resources: this._fieldResources.mergedResources,
  1085. operatorList: opList
  1086. });
  1087. opList.addOp(_util.OPS.endAnnotation, []);
  1088. if (optionalContent !== undefined) {
  1089. opList.addOp(_util.OPS.endMarkedContent, []);
  1090. }
  1091. return {
  1092. opList,
  1093. separateForm: false,
  1094. separateCanvas: false
  1095. };
  1096. }
  1097. _getMKDict(rotation) {
  1098. const mk = new _primitives.Dict(null);
  1099. if (rotation) {
  1100. mk.set("R", rotation);
  1101. }
  1102. if (this.borderColor) {
  1103. mk.set("BC", Array.from(this.borderColor).map(c => c / 255));
  1104. }
  1105. if (this.backgroundColor) {
  1106. mk.set("BG", Array.from(this.backgroundColor).map(c => c / 255));
  1107. }
  1108. return mk.size > 0 ? mk : null;
  1109. }
  1110. async save(evaluator, task, annotationStorage) {
  1111. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  1112. let value = storageEntry && storageEntry.value;
  1113. let rotation = storageEntry && storageEntry.rotation;
  1114. if (value === this.data.fieldValue || value === undefined) {
  1115. if (!this._hasValueFromXFA && rotation === undefined) {
  1116. return null;
  1117. }
  1118. value = value || this.data.fieldValue;
  1119. }
  1120. 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])) {
  1121. return null;
  1122. }
  1123. if (rotation === undefined) {
  1124. rotation = this.rotation;
  1125. }
  1126. let appearance = await this._getAppearance(evaluator, task, annotationStorage);
  1127. if (appearance === null) {
  1128. return null;
  1129. }
  1130. const {
  1131. xref
  1132. } = evaluator;
  1133. const dict = xref.fetchIfRef(this.ref);
  1134. if (!(dict instanceof _primitives.Dict)) {
  1135. return null;
  1136. }
  1137. const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
  1138. const xfa = {
  1139. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1140. value
  1141. };
  1142. const newRef = xref.getNewRef();
  1143. const AP = new _primitives.Dict(xref);
  1144. AP.set("N", newRef);
  1145. const encrypt = xref.encrypt;
  1146. let originalTransform = null;
  1147. let newTransform = null;
  1148. if (encrypt) {
  1149. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1150. newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
  1151. appearance = newTransform.encryptString(appearance);
  1152. }
  1153. const encoder = val => (0, _util.isAscii)(val) ? val : (0, _util.stringToUTF16BEString)(val);
  1154. dict.set("V", Array.isArray(value) ? value.map(encoder) : encoder(value));
  1155. dict.set("AP", AP);
  1156. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1157. const maybeMK = this._getMKDict(rotation);
  1158. if (maybeMK) {
  1159. dict.set("MK", maybeMK);
  1160. }
  1161. const appearanceDict = new _primitives.Dict(xref);
  1162. appearanceDict.set("Length", appearance.length);
  1163. appearanceDict.set("Subtype", _primitives.Name.get("Form"));
  1164. appearanceDict.set("Resources", this._getSaveFieldResources(xref));
  1165. appearanceDict.set("BBox", bbox);
  1166. const rotationMatrix = this.getRotationMatrix(annotationStorage);
  1167. if (rotationMatrix !== _util.IDENTITY_MATRIX) {
  1168. appearanceDict.set("Matrix", rotationMatrix);
  1169. }
  1170. const bufferOriginal = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1171. (0, _writer.writeDict)(dict, bufferOriginal, originalTransform);
  1172. bufferOriginal.push("\nendobj\n");
  1173. const bufferNew = [`${newRef.num} ${newRef.gen} obj\n`];
  1174. (0, _writer.writeDict)(appearanceDict, bufferNew, newTransform);
  1175. bufferNew.push(" stream\n", appearance, "\nendstream\nendobj\n");
  1176. return [{
  1177. ref: this.ref,
  1178. data: bufferOriginal.join(""),
  1179. xfa
  1180. }, {
  1181. ref: newRef,
  1182. data: bufferNew.join(""),
  1183. xfa: null
  1184. }];
  1185. }
  1186. async _getAppearance(evaluator, task, annotationStorage) {
  1187. const isPassword = this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD);
  1188. if (isPassword) {
  1189. return null;
  1190. }
  1191. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  1192. let value, rotation;
  1193. if (storageEntry) {
  1194. value = storageEntry.formattedValue || storageEntry.value;
  1195. rotation = storageEntry.rotation;
  1196. }
  1197. if (rotation === undefined && value === undefined) {
  1198. if (!this._hasValueFromXFA || this.appearance) {
  1199. return null;
  1200. }
  1201. }
  1202. if (value === undefined) {
  1203. value = this.data.fieldValue;
  1204. if (!value) {
  1205. return "";
  1206. }
  1207. }
  1208. if (Array.isArray(value) && value.length === 1) {
  1209. value = value[0];
  1210. }
  1211. (0, _util.assert)(typeof value === "string", "Expected `value` to be a string.");
  1212. value = value.trim();
  1213. if (value === "") {
  1214. return "";
  1215. }
  1216. if (rotation === undefined) {
  1217. rotation = this.rotation;
  1218. }
  1219. let lineCount = -1;
  1220. if (this.data.multiLine) {
  1221. lineCount = value.split(/\r\n|\r|\n/).length;
  1222. }
  1223. const defaultPadding = 2;
  1224. const hPadding = defaultPadding;
  1225. let totalHeight = this.data.rect[3] - this.data.rect[1];
  1226. let totalWidth = this.data.rect[2] - this.data.rect[0];
  1227. if (rotation === 90 || rotation === 270) {
  1228. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  1229. }
  1230. if (!this._defaultAppearance) {
  1231. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  1232. }
  1233. const font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
  1234. const [defaultAppearance, fontSize] = this._computeFontSize(totalHeight - defaultPadding, totalWidth - 2 * hPadding, value, font, lineCount);
  1235. let descent = font.descent;
  1236. if (isNaN(descent)) {
  1237. descent = 0;
  1238. }
  1239. const defaultVPadding = Math.min(Math.floor((totalHeight - fontSize) / 2), defaultPadding);
  1240. const vPadding = defaultVPadding + Math.abs(descent) * fontSize;
  1241. const alignment = this.data.textAlignment;
  1242. if (this.data.multiLine) {
  1243. return this._getMultilineAppearance(defaultAppearance, value, font, fontSize, totalWidth, totalHeight, alignment, hPadding, vPadding, annotationStorage);
  1244. }
  1245. const encodedString = font.encodeString(value).join("");
  1246. if (this.data.comb) {
  1247. return this._getCombAppearance(defaultAppearance, font, encodedString, totalWidth, hPadding, vPadding, annotationStorage);
  1248. }
  1249. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1250. if (alignment === 0 || alignment > 2) {
  1251. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm (${(0, _util.escapeString)(encodedString)}) Tj` + " ET Q EMC";
  1252. }
  1253. const renderedText = this._renderText(encodedString, font, fontSize, totalWidth, alignment, hPadding, vPadding);
  1254. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC";
  1255. }
  1256. static async _getFontData(evaluator, task, appearanceData, resources) {
  1257. const operatorList = new _operator_list.OperatorList();
  1258. const initialState = {
  1259. font: null,
  1260. clone() {
  1261. return this;
  1262. }
  1263. };
  1264. const {
  1265. fontName,
  1266. fontSize
  1267. } = appearanceData;
  1268. await evaluator.handleSetFont(resources, [fontName && _primitives.Name.get(fontName), fontSize], null, operatorList, task, initialState, null);
  1269. return initialState.font;
  1270. }
  1271. _getTextWidth(text, font) {
  1272. return font.charsToGlyphs(text).reduce((width, glyph) => width + glyph.width, 0) / 1000;
  1273. }
  1274. _computeFontSize(height, width, text, font, lineCount) {
  1275. let {
  1276. fontSize
  1277. } = this.data.defaultAppearanceData;
  1278. if (!fontSize) {
  1279. const roundWithTwoDigits = x => Math.floor(x * 100) / 100;
  1280. if (lineCount === -1) {
  1281. const textWidth = this._getTextWidth(text, font);
  1282. fontSize = roundWithTwoDigits(Math.min(height / _util.LINE_FACTOR, width / textWidth));
  1283. } else {
  1284. const lines = text.split(/\r\n?|\n/);
  1285. const cachedLines = [];
  1286. for (const line of lines) {
  1287. const encoded = font.encodeString(line).join("");
  1288. const glyphs = font.charsToGlyphs(encoded);
  1289. const positions = font.getCharPositions(encoded);
  1290. cachedLines.push({
  1291. line: encoded,
  1292. glyphs,
  1293. positions
  1294. });
  1295. }
  1296. const isTooBig = fsize => {
  1297. let totalHeight = 0;
  1298. for (const cache of cachedLines) {
  1299. const chunks = this._splitLine(null, font, fsize, width, cache);
  1300. totalHeight += chunks.length * fsize;
  1301. if (totalHeight > height) {
  1302. return true;
  1303. }
  1304. }
  1305. return false;
  1306. };
  1307. fontSize = 12;
  1308. let lineHeight = fontSize * _util.LINE_FACTOR;
  1309. let numberOfLines = Math.round(height / lineHeight);
  1310. numberOfLines = Math.max(numberOfLines, lineCount);
  1311. while (true) {
  1312. lineHeight = height / numberOfLines;
  1313. fontSize = roundWithTwoDigits(lineHeight / _util.LINE_FACTOR);
  1314. if (isTooBig(fontSize)) {
  1315. numberOfLines++;
  1316. continue;
  1317. }
  1318. break;
  1319. }
  1320. }
  1321. const {
  1322. fontName,
  1323. fontColor
  1324. } = this.data.defaultAppearanceData;
  1325. this._defaultAppearance = (0, _default_appearance.createDefaultAppearance)({
  1326. fontSize,
  1327. fontName,
  1328. fontColor
  1329. });
  1330. }
  1331. return [this._defaultAppearance, fontSize];
  1332. }
  1333. _renderText(text, font, fontSize, totalWidth, alignment, hPadding, vPadding) {
  1334. let shift;
  1335. if (alignment === 1) {
  1336. const width = this._getTextWidth(text, font) * fontSize;
  1337. shift = (totalWidth - width) / 2;
  1338. } else if (alignment === 2) {
  1339. const width = this._getTextWidth(text, font) * fontSize;
  1340. shift = totalWidth - width - hPadding;
  1341. } else {
  1342. shift = hPadding;
  1343. }
  1344. shift = (0, _core_utils.numberToString)(shift);
  1345. vPadding = (0, _core_utils.numberToString)(vPadding);
  1346. return `${shift} ${vPadding} Td (${(0, _util.escapeString)(text)}) Tj`;
  1347. }
  1348. _getSaveFieldResources(xref) {
  1349. const {
  1350. localResources,
  1351. appearanceResources,
  1352. acroFormResources
  1353. } = this._fieldResources;
  1354. const fontName = this.data.defaultAppearanceData && this.data.defaultAppearanceData.fontName;
  1355. if (!fontName) {
  1356. return localResources || _primitives.Dict.empty;
  1357. }
  1358. for (const resources of [localResources, appearanceResources]) {
  1359. if (resources instanceof _primitives.Dict) {
  1360. const localFont = resources.get("Font");
  1361. if (localFont instanceof _primitives.Dict && localFont.has(fontName)) {
  1362. return resources;
  1363. }
  1364. }
  1365. }
  1366. if (acroFormResources instanceof _primitives.Dict) {
  1367. const acroFormFont = acroFormResources.get("Font");
  1368. if (acroFormFont instanceof _primitives.Dict && acroFormFont.has(fontName)) {
  1369. const subFontDict = new _primitives.Dict(xref);
  1370. subFontDict.set(fontName, acroFormFont.getRaw(fontName));
  1371. const subResourcesDict = new _primitives.Dict(xref);
  1372. subResourcesDict.set("Font", subFontDict);
  1373. return _primitives.Dict.merge({
  1374. xref,
  1375. dictArray: [subResourcesDict, localResources],
  1376. mergeSubDicts: true
  1377. });
  1378. }
  1379. }
  1380. return localResources || _primitives.Dict.empty;
  1381. }
  1382. getFieldObject() {
  1383. return null;
  1384. }
  1385. }
  1386. class TextWidgetAnnotation extends WidgetAnnotation {
  1387. constructor(params) {
  1388. super(params);
  1389. this._hasText = true;
  1390. const dict = params.dict;
  1391. if (typeof this.data.fieldValue !== "string") {
  1392. this.data.fieldValue = "";
  1393. }
  1394. let alignment = (0, _core_utils.getInheritableProperty)({
  1395. dict,
  1396. key: "Q"
  1397. });
  1398. if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
  1399. alignment = null;
  1400. }
  1401. this.data.textAlignment = alignment;
  1402. let maximumLength = (0, _core_utils.getInheritableProperty)({
  1403. dict,
  1404. key: "MaxLen"
  1405. });
  1406. if (!Number.isInteger(maximumLength) || maximumLength < 0) {
  1407. maximumLength = 0;
  1408. }
  1409. this.data.maxLen = maximumLength;
  1410. this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
  1411. 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 !== 0;
  1412. this.data.doNotScroll = this.hasFieldFlag(_util.AnnotationFieldFlag.DONOTSCROLL);
  1413. }
  1414. _getCombAppearance(defaultAppearance, font, text, width, hPadding, vPadding, annotationStorage) {
  1415. const combWidth = (0, _core_utils.numberToString)(width / this.data.maxLen);
  1416. const buf = [];
  1417. const positions = font.getCharPositions(text);
  1418. for (const [start, end] of positions) {
  1419. buf.push(`(${(0, _util.escapeString)(text.substring(start, end))}) Tj`);
  1420. }
  1421. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1422. const renderedComb = buf.join(` ${combWidth} 0 Td `);
  1423. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm ${renderedComb}` + " ET Q EMC";
  1424. }
  1425. _getMultilineAppearance(defaultAppearance, text, font, fontSize, width, height, alignment, hPadding, vPadding, annotationStorage) {
  1426. const lines = text.split(/\r\n?|\n/);
  1427. const buf = [];
  1428. const totalWidth = width - 2 * hPadding;
  1429. for (const line of lines) {
  1430. const chunks = this._splitLine(line, font, fontSize, totalWidth);
  1431. for (const chunk of chunks) {
  1432. const padding = buf.length === 0 ? hPadding : 0;
  1433. buf.push(this._renderText(chunk, font, fontSize, width, alignment, padding, -fontSize));
  1434. }
  1435. }
  1436. const renderedText = buf.join("\n");
  1437. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1438. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 ${height} Tm ${renderedText}` + " ET Q EMC";
  1439. }
  1440. _splitLine(line, font, fontSize, width, cache = {}) {
  1441. line = cache.line || font.encodeString(line).join("");
  1442. const glyphs = cache.glyphs || font.charsToGlyphs(line);
  1443. if (glyphs.length <= 1) {
  1444. return [line];
  1445. }
  1446. const positions = cache.positions || font.getCharPositions(line);
  1447. const scale = fontSize / 1000;
  1448. const chunks = [];
  1449. let lastSpacePosInStringStart = -1,
  1450. lastSpacePosInStringEnd = -1,
  1451. lastSpacePos = -1,
  1452. startChunk = 0,
  1453. currentWidth = 0;
  1454. for (let i = 0, ii = glyphs.length; i < ii; i++) {
  1455. const [start, end] = positions[i];
  1456. const glyph = glyphs[i];
  1457. const glyphWidth = glyph.width * scale;
  1458. if (glyph.unicode === " ") {
  1459. if (currentWidth + glyphWidth > width) {
  1460. chunks.push(line.substring(startChunk, start));
  1461. startChunk = start;
  1462. currentWidth = glyphWidth;
  1463. lastSpacePosInStringStart = -1;
  1464. lastSpacePos = -1;
  1465. } else {
  1466. currentWidth += glyphWidth;
  1467. lastSpacePosInStringStart = start;
  1468. lastSpacePosInStringEnd = end;
  1469. lastSpacePos = i;
  1470. }
  1471. } else {
  1472. if (currentWidth + glyphWidth > width) {
  1473. if (lastSpacePosInStringStart !== -1) {
  1474. chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
  1475. startChunk = lastSpacePosInStringEnd;
  1476. i = lastSpacePos + 1;
  1477. lastSpacePosInStringStart = -1;
  1478. currentWidth = 0;
  1479. } else {
  1480. chunks.push(line.substring(startChunk, start));
  1481. startChunk = start;
  1482. currentWidth = glyphWidth;
  1483. }
  1484. } else {
  1485. currentWidth += glyphWidth;
  1486. }
  1487. }
  1488. }
  1489. if (startChunk < line.length) {
  1490. chunks.push(line.substring(startChunk, line.length));
  1491. }
  1492. return chunks;
  1493. }
  1494. getFieldObject() {
  1495. return {
  1496. id: this.data.id,
  1497. value: this.data.fieldValue,
  1498. defaultValue: this.data.defaultFieldValue || "",
  1499. multiline: this.data.multiLine,
  1500. password: this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD),
  1501. charLimit: this.data.maxLen,
  1502. comb: this.data.comb,
  1503. editable: !this.data.readOnly,
  1504. hidden: this.data.hidden,
  1505. name: this.data.fieldName,
  1506. rect: this.data.rect,
  1507. actions: this.data.actions,
  1508. page: this.data.pageIndex,
  1509. strokeColor: this.data.borderColor,
  1510. fillColor: this.data.backgroundColor,
  1511. rotation: this.rotation,
  1512. type: "text"
  1513. };
  1514. }
  1515. }
  1516. class ButtonWidgetAnnotation extends WidgetAnnotation {
  1517. constructor(params) {
  1518. super(params);
  1519. this.checkedAppearance = null;
  1520. this.uncheckedAppearance = null;
  1521. this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1522. this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1523. this.data.pushButton = this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1524. this.data.isTooltipOnly = false;
  1525. if (this.data.checkBox) {
  1526. this._processCheckBox(params);
  1527. } else if (this.data.radioButton) {
  1528. this._processRadioButton(params);
  1529. } else if (this.data.pushButton) {
  1530. this.data.hasOwnCanvas = true;
  1531. this._processPushButton(params);
  1532. } else {
  1533. (0, _util.warn)("Invalid field flags for button widget annotation");
  1534. }
  1535. }
  1536. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  1537. if (this.data.pushButton) {
  1538. return super.getOperatorList(evaluator, task, intent, false, annotationStorage);
  1539. }
  1540. let value = null;
  1541. let rotation = null;
  1542. if (annotationStorage) {
  1543. const storageEntry = annotationStorage.get(this.data.id);
  1544. value = storageEntry ? storageEntry.value : null;
  1545. rotation = storageEntry ? storageEntry.rotation : null;
  1546. }
  1547. if (value === null && this.appearance) {
  1548. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1549. }
  1550. if (value === null || value === undefined) {
  1551. if (this.data.checkBox) {
  1552. value = this.data.fieldValue === this.data.exportValue;
  1553. } else {
  1554. value = this.data.fieldValue === this.data.buttonValue;
  1555. }
  1556. }
  1557. const appearance = value ? this.checkedAppearance : this.uncheckedAppearance;
  1558. if (appearance) {
  1559. const savedAppearance = this.appearance;
  1560. const savedMatrix = appearance.dict.getArray("Matrix") || _util.IDENTITY_MATRIX;
  1561. if (rotation) {
  1562. appearance.dict.set("Matrix", this.getRotationMatrix(annotationStorage));
  1563. }
  1564. this.appearance = appearance;
  1565. const operatorList = super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1566. this.appearance = savedAppearance;
  1567. appearance.dict.set("Matrix", savedMatrix);
  1568. return operatorList;
  1569. }
  1570. return {
  1571. opList: new _operator_list.OperatorList(),
  1572. separateForm: false,
  1573. separateCanvas: false
  1574. };
  1575. }
  1576. async save(evaluator, task, annotationStorage) {
  1577. if (this.data.checkBox) {
  1578. return this._saveCheckbox(evaluator, task, annotationStorage);
  1579. }
  1580. if (this.data.radioButton) {
  1581. return this._saveRadioButton(evaluator, task, annotationStorage);
  1582. }
  1583. return null;
  1584. }
  1585. async _saveCheckbox(evaluator, task, annotationStorage) {
  1586. if (!annotationStorage) {
  1587. return null;
  1588. }
  1589. const storageEntry = annotationStorage.get(this.data.id);
  1590. let rotation = storageEntry && storageEntry.rotation;
  1591. let value = storageEntry && storageEntry.value;
  1592. if (rotation === undefined) {
  1593. if (value === undefined) {
  1594. return null;
  1595. }
  1596. const defaultValue = this.data.fieldValue === this.data.exportValue;
  1597. if (defaultValue === value) {
  1598. return null;
  1599. }
  1600. }
  1601. const dict = evaluator.xref.fetchIfRef(this.ref);
  1602. if (!(dict instanceof _primitives.Dict)) {
  1603. return null;
  1604. }
  1605. if (rotation === undefined) {
  1606. rotation = this.rotation;
  1607. }
  1608. if (value === undefined) {
  1609. value = this.data.fieldValue === this.data.exportValue;
  1610. }
  1611. const xfa = {
  1612. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1613. value: value ? this.data.exportValue : ""
  1614. };
  1615. const name = _primitives.Name.get(value ? this.data.exportValue : "Off");
  1616. dict.set("V", name);
  1617. dict.set("AS", name);
  1618. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1619. const maybeMK = this._getMKDict(rotation);
  1620. if (maybeMK) {
  1621. dict.set("MK", maybeMK);
  1622. }
  1623. const encrypt = evaluator.xref.encrypt;
  1624. let originalTransform = null;
  1625. if (encrypt) {
  1626. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1627. }
  1628. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1629. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1630. buffer.push("\nendobj\n");
  1631. return [{
  1632. ref: this.ref,
  1633. data: buffer.join(""),
  1634. xfa
  1635. }];
  1636. }
  1637. async _saveRadioButton(evaluator, task, annotationStorage) {
  1638. if (!annotationStorage) {
  1639. return null;
  1640. }
  1641. const storageEntry = annotationStorage.get(this.data.id);
  1642. let rotation = storageEntry && storageEntry.rotation;
  1643. let value = storageEntry && storageEntry.value;
  1644. if (rotation === undefined) {
  1645. if (value === undefined) {
  1646. return null;
  1647. }
  1648. const defaultValue = this.data.fieldValue === this.data.buttonValue;
  1649. if (defaultValue === value) {
  1650. return null;
  1651. }
  1652. }
  1653. const dict = evaluator.xref.fetchIfRef(this.ref);
  1654. if (!(dict instanceof _primitives.Dict)) {
  1655. return null;
  1656. }
  1657. if (value === undefined) {
  1658. value = this.data.fieldValue === this.data.buttonValue;
  1659. }
  1660. if (rotation === undefined) {
  1661. rotation = this.rotation;
  1662. }
  1663. const xfa = {
  1664. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1665. value: value ? this.data.buttonValue : ""
  1666. };
  1667. const name = _primitives.Name.get(value ? this.data.buttonValue : "Off");
  1668. let parentBuffer = null;
  1669. const encrypt = evaluator.xref.encrypt;
  1670. if (value) {
  1671. if (this.parent instanceof _primitives.Ref) {
  1672. const parent = evaluator.xref.fetch(this.parent);
  1673. let parentTransform = null;
  1674. if (encrypt) {
  1675. parentTransform = encrypt.createCipherTransform(this.parent.num, this.parent.gen);
  1676. }
  1677. parent.set("V", name);
  1678. parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
  1679. (0, _writer.writeDict)(parent, parentBuffer, parentTransform);
  1680. parentBuffer.push("\nendobj\n");
  1681. } else if (this.parent instanceof _primitives.Dict) {
  1682. this.parent.set("V", name);
  1683. }
  1684. }
  1685. dict.set("AS", name);
  1686. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1687. const maybeMK = this._getMKDict(rotation);
  1688. if (maybeMK) {
  1689. dict.set("MK", maybeMK);
  1690. }
  1691. let originalTransform = null;
  1692. if (encrypt) {
  1693. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1694. }
  1695. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1696. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1697. buffer.push("\nendobj\n");
  1698. const newRefs = [{
  1699. ref: this.ref,
  1700. data: buffer.join(""),
  1701. xfa
  1702. }];
  1703. if (parentBuffer !== null) {
  1704. newRefs.push({
  1705. ref: this.parent,
  1706. data: parentBuffer.join(""),
  1707. xfa: null
  1708. });
  1709. }
  1710. return newRefs;
  1711. }
  1712. _getDefaultCheckedAppearance(params, type) {
  1713. const width = this.data.rect[2] - this.data.rect[0];
  1714. const height = this.data.rect[3] - this.data.rect[1];
  1715. const bbox = [0, 0, width, height];
  1716. const FONT_RATIO = 0.8;
  1717. const fontSize = Math.min(width, height) * FONT_RATIO;
  1718. let metrics, char;
  1719. if (type === "check") {
  1720. metrics = {
  1721. width: 0.755 * fontSize,
  1722. height: 0.705 * fontSize
  1723. };
  1724. char = "\x33";
  1725. } else if (type === "disc") {
  1726. metrics = {
  1727. width: 0.791 * fontSize,
  1728. height: 0.705 * fontSize
  1729. };
  1730. char = "\x6C";
  1731. } else {
  1732. (0, _util.unreachable)(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
  1733. }
  1734. const xShift = (0, _core_utils.numberToString)((width - metrics.width) / 2);
  1735. const yShift = (0, _core_utils.numberToString)((height - metrics.height) / 2);
  1736. const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
  1737. const appearanceStreamDict = new _primitives.Dict(params.xref);
  1738. appearanceStreamDict.set("FormType", 1);
  1739. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  1740. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  1741. appearanceStreamDict.set("BBox", bbox);
  1742. appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
  1743. appearanceStreamDict.set("Length", appearance.length);
  1744. const resources = new _primitives.Dict(params.xref);
  1745. const font = new _primitives.Dict(params.xref);
  1746. font.set("PdfJsZaDb", this.fallbackFontDict);
  1747. resources.set("Font", font);
  1748. appearanceStreamDict.set("Resources", resources);
  1749. this.checkedAppearance = new _stream.StringStream(appearance);
  1750. this.checkedAppearance.dict = appearanceStreamDict;
  1751. this._streams.push(this.checkedAppearance);
  1752. }
  1753. _processCheckBox(params) {
  1754. const customAppearance = params.dict.get("AP");
  1755. if (!(customAppearance instanceof _primitives.Dict)) {
  1756. return;
  1757. }
  1758. const normalAppearance = customAppearance.get("N");
  1759. if (!(normalAppearance instanceof _primitives.Dict)) {
  1760. return;
  1761. }
  1762. const asValue = this._decodeFormValue(params.dict.get("AS"));
  1763. if (typeof asValue === "string") {
  1764. this.data.fieldValue = asValue;
  1765. }
  1766. const yes = this.data.fieldValue !== null && this.data.fieldValue !== "Off" ? this.data.fieldValue : "Yes";
  1767. const exportValues = normalAppearance.getKeys();
  1768. if (exportValues.length === 0) {
  1769. exportValues.push("Off", yes);
  1770. } else if (exportValues.length === 1) {
  1771. if (exportValues[0] === "Off") {
  1772. exportValues.push(yes);
  1773. } else {
  1774. exportValues.unshift("Off");
  1775. }
  1776. } else if (exportValues.includes(yes)) {
  1777. exportValues.length = 0;
  1778. exportValues.push("Off", yes);
  1779. } else {
  1780. const otherYes = exportValues.find(v => v !== "Off");
  1781. exportValues.length = 0;
  1782. exportValues.push("Off", otherYes);
  1783. }
  1784. if (!exportValues.includes(this.data.fieldValue)) {
  1785. this.data.fieldValue = "Off";
  1786. }
  1787. this.data.exportValue = exportValues[1];
  1788. this.checkedAppearance = normalAppearance.get(this.data.exportValue) || null;
  1789. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1790. if (this.checkedAppearance) {
  1791. this._streams.push(this.checkedAppearance);
  1792. } else {
  1793. this._getDefaultCheckedAppearance(params, "check");
  1794. }
  1795. if (this.uncheckedAppearance) {
  1796. this._streams.push(this.uncheckedAppearance);
  1797. }
  1798. this._fallbackFontDict = this.fallbackFontDict;
  1799. }
  1800. _processRadioButton(params) {
  1801. this.data.fieldValue = this.data.buttonValue = null;
  1802. const fieldParent = params.dict.get("Parent");
  1803. if (fieldParent instanceof _primitives.Dict) {
  1804. this.parent = params.dict.getRaw("Parent");
  1805. const fieldParentValue = fieldParent.get("V");
  1806. if (fieldParentValue instanceof _primitives.Name) {
  1807. this.data.fieldValue = this._decodeFormValue(fieldParentValue);
  1808. }
  1809. }
  1810. const appearanceStates = params.dict.get("AP");
  1811. if (!(appearanceStates instanceof _primitives.Dict)) {
  1812. return;
  1813. }
  1814. const normalAppearance = appearanceStates.get("N");
  1815. if (!(normalAppearance instanceof _primitives.Dict)) {
  1816. return;
  1817. }
  1818. for (const key of normalAppearance.getKeys()) {
  1819. if (key !== "Off") {
  1820. this.data.buttonValue = this._decodeFormValue(key);
  1821. break;
  1822. }
  1823. }
  1824. this.checkedAppearance = normalAppearance.get(this.data.buttonValue) || null;
  1825. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1826. if (this.checkedAppearance) {
  1827. this._streams.push(this.checkedAppearance);
  1828. } else {
  1829. this._getDefaultCheckedAppearance(params, "disc");
  1830. }
  1831. if (this.uncheckedAppearance) {
  1832. this._streams.push(this.uncheckedAppearance);
  1833. }
  1834. this._fallbackFontDict = this.fallbackFontDict;
  1835. }
  1836. _processPushButton(params) {
  1837. if (!params.dict.has("A") && !params.dict.has("AA") && !this.data.alternativeText) {
  1838. (0, _util.warn)("Push buttons without action dictionaries are not supported");
  1839. return;
  1840. }
  1841. this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
  1842. _catalog.Catalog.parseDestDictionary({
  1843. destDict: params.dict,
  1844. resultObj: this.data,
  1845. docBaseUrl: params.pdfManager.docBaseUrl
  1846. });
  1847. }
  1848. getFieldObject() {
  1849. let type = "button";
  1850. let exportValues;
  1851. if (this.data.checkBox) {
  1852. type = "checkbox";
  1853. exportValues = this.data.exportValue;
  1854. } else if (this.data.radioButton) {
  1855. type = "radiobutton";
  1856. exportValues = this.data.buttonValue;
  1857. }
  1858. return {
  1859. id: this.data.id,
  1860. value: this.data.fieldValue || "Off",
  1861. defaultValue: this.data.defaultFieldValue,
  1862. exportValues,
  1863. editable: !this.data.readOnly,
  1864. name: this.data.fieldName,
  1865. rect: this.data.rect,
  1866. hidden: this.data.hidden,
  1867. actions: this.data.actions,
  1868. page: this.data.pageIndex,
  1869. strokeColor: this.data.borderColor,
  1870. fillColor: this.data.backgroundColor,
  1871. rotation: this.rotation,
  1872. type
  1873. };
  1874. }
  1875. get fallbackFontDict() {
  1876. const dict = new _primitives.Dict();
  1877. dict.set("BaseFont", _primitives.Name.get("ZapfDingbats"));
  1878. dict.set("Type", _primitives.Name.get("FallbackType"));
  1879. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  1880. dict.set("Encoding", _primitives.Name.get("ZapfDingbatsEncoding"));
  1881. return (0, _util.shadow)(this, "fallbackFontDict", dict);
  1882. }
  1883. }
  1884. class ChoiceWidgetAnnotation extends WidgetAnnotation {
  1885. constructor(params) {
  1886. super(params);
  1887. this.data.options = [];
  1888. const options = (0, _core_utils.getInheritableProperty)({
  1889. dict: params.dict,
  1890. key: "Opt"
  1891. });
  1892. if (Array.isArray(options)) {
  1893. const xref = params.xref;
  1894. for (let i = 0, ii = options.length; i < ii; i++) {
  1895. const option = xref.fetchIfRef(options[i]);
  1896. const isOptionArray = Array.isArray(option);
  1897. this.data.options[i] = {
  1898. exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
  1899. displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
  1900. };
  1901. }
  1902. }
  1903. if (typeof this.data.fieldValue === "string") {
  1904. this.data.fieldValue = [this.data.fieldValue];
  1905. } else if (!this.data.fieldValue) {
  1906. this.data.fieldValue = [];
  1907. }
  1908. this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
  1909. this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
  1910. this._hasText = true;
  1911. }
  1912. getFieldObject() {
  1913. const type = this.data.combo ? "combobox" : "listbox";
  1914. const value = this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
  1915. return {
  1916. id: this.data.id,
  1917. value,
  1918. defaultValue: this.data.defaultFieldValue,
  1919. editable: !this.data.readOnly,
  1920. name: this.data.fieldName,
  1921. rect: this.data.rect,
  1922. numItems: this.data.fieldValue.length,
  1923. multipleSelection: this.data.multiSelect,
  1924. hidden: this.data.hidden,
  1925. actions: this.data.actions,
  1926. items: this.data.options,
  1927. page: this.data.pageIndex,
  1928. strokeColor: this.data.borderColor,
  1929. fillColor: this.data.backgroundColor,
  1930. rotation: this.rotation,
  1931. type
  1932. };
  1933. }
  1934. async _getAppearance(evaluator, task, annotationStorage) {
  1935. if (this.data.combo) {
  1936. return super._getAppearance(evaluator, task, annotationStorage);
  1937. }
  1938. if (!annotationStorage) {
  1939. return null;
  1940. }
  1941. const storageEntry = annotationStorage.get(this.data.id);
  1942. if (!storageEntry) {
  1943. return null;
  1944. }
  1945. const rotation = storageEntry.rotation;
  1946. let exportedValue = storageEntry.value;
  1947. if (rotation === undefined && exportedValue === undefined) {
  1948. return null;
  1949. }
  1950. if (exportedValue === undefined) {
  1951. exportedValue = this.data.fieldValue;
  1952. } else if (!Array.isArray(exportedValue)) {
  1953. exportedValue = [exportedValue];
  1954. }
  1955. const defaultPadding = 2;
  1956. const hPadding = defaultPadding;
  1957. let totalHeight = this.data.rect[3] - this.data.rect[1];
  1958. let totalWidth = this.data.rect[2] - this.data.rect[0];
  1959. if (rotation === 90 || rotation === 270) {
  1960. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  1961. }
  1962. const lineCount = this.data.options.length;
  1963. const valueIndices = [];
  1964. for (let i = 0; i < lineCount; i++) {
  1965. const {
  1966. exportValue
  1967. } = this.data.options[i];
  1968. if (exportedValue.includes(exportValue)) {
  1969. valueIndices.push(i);
  1970. }
  1971. }
  1972. if (!this._defaultAppearance) {
  1973. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  1974. }
  1975. const font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
  1976. let defaultAppearance;
  1977. let {
  1978. fontSize
  1979. } = this.data.defaultAppearanceData;
  1980. if (!fontSize) {
  1981. const lineHeight = (totalHeight - defaultPadding) / lineCount;
  1982. let lineWidth = -1;
  1983. let value;
  1984. for (const {
  1985. displayValue
  1986. } of this.data.options) {
  1987. const width = this._getTextWidth(displayValue, font);
  1988. if (width > lineWidth) {
  1989. lineWidth = width;
  1990. value = displayValue;
  1991. }
  1992. }
  1993. [defaultAppearance, fontSize] = this._computeFontSize(lineHeight, totalWidth - 2 * hPadding, value, font, -1);
  1994. } else {
  1995. defaultAppearance = this._defaultAppearance;
  1996. }
  1997. const lineHeight = fontSize * _util.LINE_FACTOR;
  1998. const vPadding = (lineHeight - fontSize) / 2;
  1999. const numberOfVisibleLines = Math.floor(totalHeight / lineHeight);
  2000. let firstIndex;
  2001. if (valueIndices.length === 1) {
  2002. const valuePosition = valueIndices[0];
  2003. const indexInPage = valuePosition % numberOfVisibleLines;
  2004. firstIndex = valuePosition - indexInPage;
  2005. } else {
  2006. firstIndex = valueIndices.length ? valueIndices[0] : 0;
  2007. }
  2008. const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount);
  2009. const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`];
  2010. if (valueIndices.length) {
  2011. buf.push("0.600006 0.756866 0.854904 rg");
  2012. for (const index of valueIndices) {
  2013. if (firstIndex <= index && index < end) {
  2014. buf.push(`1 ${totalHeight - (index - firstIndex + 1) * lineHeight} ${totalWidth} ${lineHeight} re f`);
  2015. }
  2016. }
  2017. }
  2018. buf.push("BT", defaultAppearance, `1 0 0 1 0 ${totalHeight} Tm`);
  2019. for (let i = firstIndex; i < end; i++) {
  2020. const {
  2021. displayValue
  2022. } = this.data.options[i];
  2023. const hpadding = i === firstIndex ? hPadding : 0;
  2024. const vpadding = i === firstIndex ? vPadding : 0;
  2025. buf.push(this._renderText(displayValue, font, fontSize, totalWidth, 0, hpadding, -lineHeight + vpadding));
  2026. }
  2027. buf.push("ET Q EMC");
  2028. return buf.join("\n");
  2029. }
  2030. }
  2031. class SignatureWidgetAnnotation extends WidgetAnnotation {
  2032. constructor(params) {
  2033. super(params);
  2034. this.data.fieldValue = null;
  2035. }
  2036. getFieldObject() {
  2037. return {
  2038. id: this.data.id,
  2039. value: null,
  2040. page: this.data.pageIndex,
  2041. type: "signature"
  2042. };
  2043. }
  2044. }
  2045. class TextAnnotation extends MarkupAnnotation {
  2046. constructor(parameters) {
  2047. const DEFAULT_ICON_SIZE = 22;
  2048. super(parameters);
  2049. const dict = parameters.dict;
  2050. this.data.annotationType = _util.AnnotationType.TEXT;
  2051. if (this.data.hasAppearance) {
  2052. this.data.name = "NoIcon";
  2053. } else {
  2054. this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
  2055. this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
  2056. this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
  2057. }
  2058. if (dict.has("State")) {
  2059. this.data.state = dict.get("State") || null;
  2060. this.data.stateModel = dict.get("StateModel") || null;
  2061. } else {
  2062. this.data.state = null;
  2063. this.data.stateModel = null;
  2064. }
  2065. }
  2066. }
  2067. class LinkAnnotation extends Annotation {
  2068. constructor(params) {
  2069. super(params);
  2070. this.data.annotationType = _util.AnnotationType.LINK;
  2071. const quadPoints = getQuadPoints(params.dict, this.rectangle);
  2072. if (quadPoints) {
  2073. this.data.quadPoints = quadPoints;
  2074. }
  2075. this.data.borderColor = this.data.borderColor || this.data.color;
  2076. _catalog.Catalog.parseDestDictionary({
  2077. destDict: params.dict,
  2078. resultObj: this.data,
  2079. docBaseUrl: params.pdfManager.docBaseUrl
  2080. });
  2081. }
  2082. }
  2083. class PopupAnnotation extends Annotation {
  2084. constructor(parameters) {
  2085. super(parameters);
  2086. this.data.annotationType = _util.AnnotationType.POPUP;
  2087. let parentItem = parameters.dict.get("Parent");
  2088. if (!parentItem) {
  2089. (0, _util.warn)("Popup annotation has a missing or invalid parent annotation.");
  2090. return;
  2091. }
  2092. const parentSubtype = parentItem.get("Subtype");
  2093. this.data.parentType = parentSubtype instanceof _primitives.Name ? parentSubtype.name : null;
  2094. const rawParent = parameters.dict.getRaw("Parent");
  2095. this.data.parentId = rawParent instanceof _primitives.Ref ? rawParent.toString() : null;
  2096. const parentRect = parentItem.getArray("Rect");
  2097. if (Array.isArray(parentRect) && parentRect.length === 4) {
  2098. this.data.parentRect = _util.Util.normalizeRect(parentRect);
  2099. } else {
  2100. this.data.parentRect = [0, 0, 0, 0];
  2101. }
  2102. const rt = parentItem.get("RT");
  2103. if ((0, _primitives.isName)(rt, _util.AnnotationReplyType.GROUP)) {
  2104. parentItem = parentItem.get("IRT");
  2105. }
  2106. if (!parentItem.has("M")) {
  2107. this.data.modificationDate = null;
  2108. } else {
  2109. this.setModificationDate(parentItem.get("M"));
  2110. this.data.modificationDate = this.modificationDate;
  2111. }
  2112. if (!parentItem.has("C")) {
  2113. this.data.color = null;
  2114. } else {
  2115. this.setColor(parentItem.getArray("C"));
  2116. this.data.color = this.color;
  2117. }
  2118. if (!this.viewable) {
  2119. const parentFlags = parentItem.get("F");
  2120. if (this._isViewable(parentFlags)) {
  2121. this.setFlags(parentFlags);
  2122. }
  2123. }
  2124. this.setTitle(parentItem.get("T"));
  2125. this.data.titleObj = this._title;
  2126. this.setContents(parentItem.get("Contents"));
  2127. this.data.contentsObj = this._contents;
  2128. if (parentItem.has("RC")) {
  2129. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
  2130. }
  2131. }
  2132. }
  2133. exports.PopupAnnotation = PopupAnnotation;
  2134. class FreeTextAnnotation extends MarkupAnnotation {
  2135. constructor(parameters) {
  2136. super(parameters);
  2137. this.data.annotationType = _util.AnnotationType.FREETEXT;
  2138. }
  2139. get hasTextContent() {
  2140. return !!this.appearance;
  2141. }
  2142. static createNewDict(annotation, xref, {
  2143. apRef,
  2144. ap
  2145. }) {
  2146. const {
  2147. color,
  2148. fontSize,
  2149. rect,
  2150. rotation,
  2151. user,
  2152. value
  2153. } = annotation;
  2154. const freetext = new _primitives.Dict(xref);
  2155. freetext.set("Type", _primitives.Name.get("Annot"));
  2156. freetext.set("Subtype", _primitives.Name.get("FreeText"));
  2157. freetext.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
  2158. freetext.set("Rect", rect);
  2159. const da = `/Helv ${fontSize} Tf ${(0, _default_appearance.getPdfColor)(color, true)}`;
  2160. freetext.set("DA", da);
  2161. freetext.set("Contents", value);
  2162. freetext.set("F", 4);
  2163. freetext.set("Border", [0, 0, 0]);
  2164. freetext.set("Rotate", rotation);
  2165. if (user) {
  2166. freetext.set("T", (0, _util.stringToUTF8String)(user));
  2167. }
  2168. const n = new _primitives.Dict(xref);
  2169. freetext.set("AP", n);
  2170. if (apRef) {
  2171. n.set("N", apRef);
  2172. } else {
  2173. n.set("N", ap);
  2174. }
  2175. return freetext;
  2176. }
  2177. static async createNewAppearanceStream(annotation, xref, params) {
  2178. const {
  2179. baseFontRef,
  2180. evaluator,
  2181. task
  2182. } = params;
  2183. const {
  2184. color,
  2185. fontSize,
  2186. rect,
  2187. rotation,
  2188. value
  2189. } = annotation;
  2190. const resources = new _primitives.Dict(xref);
  2191. const font = new _primitives.Dict(xref);
  2192. if (baseFontRef) {
  2193. font.set("Helv", baseFontRef);
  2194. } else {
  2195. const baseFont = new _primitives.Dict(xref);
  2196. baseFont.set("BaseFont", _primitives.Name.get("Helvetica"));
  2197. baseFont.set("Type", _primitives.Name.get("Font"));
  2198. baseFont.set("Subtype", _primitives.Name.get("Type1"));
  2199. baseFont.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
  2200. font.set("Helv", baseFont);
  2201. }
  2202. resources.set("Font", font);
  2203. const helv = await WidgetAnnotation._getFontData(evaluator, task, {
  2204. fontName: "Helvetica",
  2205. fontSize
  2206. }, resources);
  2207. const [x1, y1, x2, y2] = rect;
  2208. let w = x2 - x1;
  2209. let h = y2 - y1;
  2210. if (rotation % 180 !== 0) {
  2211. [w, h] = [h, w];
  2212. }
  2213. const lines = value.split("\n");
  2214. const scale = fontSize / 1000;
  2215. let totalWidth = -Infinity;
  2216. const encodedLines = [];
  2217. for (let line of lines) {
  2218. line = helv.encodeString(line).join("");
  2219. encodedLines.push(line);
  2220. let lineWidth = 0;
  2221. const glyphs = helv.charsToGlyphs(line);
  2222. for (const glyph of glyphs) {
  2223. lineWidth += glyph.width * scale;
  2224. }
  2225. totalWidth = Math.max(totalWidth, lineWidth);
  2226. }
  2227. let hscale = 1;
  2228. if (totalWidth > w) {
  2229. hscale = w / totalWidth;
  2230. }
  2231. let vscale = 1;
  2232. const lineHeight = _util.LINE_FACTOR * fontSize;
  2233. const lineDescent = _util.LINE_DESCENT_FACTOR * fontSize;
  2234. const totalHeight = lineHeight * lines.length;
  2235. if (totalHeight > h) {
  2236. vscale = h / totalHeight;
  2237. }
  2238. const fscale = Math.min(hscale, vscale);
  2239. const newFontSize = fontSize * fscale;
  2240. 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`];
  2241. const vShift = (0, _core_utils.numberToString)(lineHeight);
  2242. for (const line of encodedLines) {
  2243. buffer.push(`0 -${vShift} Td (${(0, _util.escapeString)(line)}) Tj`);
  2244. }
  2245. buffer.push("ET", "Q");
  2246. const appearance = buffer.join("\n");
  2247. const appearanceStreamDict = new _primitives.Dict(xref);
  2248. appearanceStreamDict.set("FormType", 1);
  2249. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  2250. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  2251. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  2252. appearanceStreamDict.set("Length", appearance.length);
  2253. appearanceStreamDict.set("Resources", resources);
  2254. if (rotation) {
  2255. const matrix = WidgetAnnotation._getRotationMatrix(rotation, w, h);
  2256. appearanceStreamDict.set("Matrix", matrix);
  2257. }
  2258. const ap = new _stream.StringStream(appearance);
  2259. ap.dict = appearanceStreamDict;
  2260. return ap;
  2261. }
  2262. }
  2263. class LineAnnotation extends MarkupAnnotation {
  2264. constructor(parameters) {
  2265. super(parameters);
  2266. const {
  2267. dict
  2268. } = parameters;
  2269. this.data.annotationType = _util.AnnotationType.LINE;
  2270. const lineCoordinates = dict.getArray("L");
  2271. this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates);
  2272. this.setLineEndings(dict.getArray("LE"));
  2273. this.data.lineEndings = this.lineEndings;
  2274. if (!this.appearance) {
  2275. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2276. const strokeAlpha = dict.get("CA");
  2277. let fillColor = null,
  2278. interiorColor = dict.getArray("IC");
  2279. if (interiorColor) {
  2280. interiorColor = getRgbColor(interiorColor, null);
  2281. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  2282. }
  2283. const fillAlpha = fillColor ? strokeAlpha : null;
  2284. const borderWidth = this.borderStyle.width || 1,
  2285. borderAdjust = 2 * borderWidth;
  2286. const bbox = [this.data.lineCoordinates[0] - borderAdjust, this.data.lineCoordinates[1] - borderAdjust, this.data.lineCoordinates[2] + borderAdjust, this.data.lineCoordinates[3] + borderAdjust];
  2287. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2288. this.rectangle = bbox;
  2289. }
  2290. this._setDefaultAppearance({
  2291. xref: parameters.xref,
  2292. extra: `${borderWidth} w`,
  2293. strokeColor,
  2294. fillColor,
  2295. strokeAlpha,
  2296. fillAlpha,
  2297. pointsCallback: (buffer, points) => {
  2298. buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`, `${lineCoordinates[2]} ${lineCoordinates[3]} l`, "S");
  2299. return [points[0].x - borderWidth, points[1].x + borderWidth, points[3].y - borderWidth, points[1].y + borderWidth];
  2300. }
  2301. });
  2302. }
  2303. }
  2304. }
  2305. class SquareAnnotation extends MarkupAnnotation {
  2306. constructor(parameters) {
  2307. super(parameters);
  2308. this.data.annotationType = _util.AnnotationType.SQUARE;
  2309. if (!this.appearance) {
  2310. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2311. const strokeAlpha = parameters.dict.get("CA");
  2312. let fillColor = null,
  2313. interiorColor = parameters.dict.getArray("IC");
  2314. if (interiorColor) {
  2315. interiorColor = getRgbColor(interiorColor, null);
  2316. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  2317. }
  2318. const fillAlpha = fillColor ? strokeAlpha : null;
  2319. if (this.borderStyle.width === 0 && !fillColor) {
  2320. return;
  2321. }
  2322. this._setDefaultAppearance({
  2323. xref: parameters.xref,
  2324. extra: `${this.borderStyle.width} w`,
  2325. strokeColor,
  2326. fillColor,
  2327. strokeAlpha,
  2328. fillAlpha,
  2329. pointsCallback: (buffer, points) => {
  2330. const x = points[2].x + this.borderStyle.width / 2;
  2331. const y = points[2].y + this.borderStyle.width / 2;
  2332. const width = points[3].x - points[2].x - this.borderStyle.width;
  2333. const height = points[1].y - points[3].y - this.borderStyle.width;
  2334. buffer.push(`${x} ${y} ${width} ${height} re`);
  2335. if (fillColor) {
  2336. buffer.push("B");
  2337. } else {
  2338. buffer.push("S");
  2339. }
  2340. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2341. }
  2342. });
  2343. }
  2344. }
  2345. }
  2346. class CircleAnnotation extends MarkupAnnotation {
  2347. constructor(parameters) {
  2348. super(parameters);
  2349. this.data.annotationType = _util.AnnotationType.CIRCLE;
  2350. if (!this.appearance) {
  2351. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2352. const strokeAlpha = parameters.dict.get("CA");
  2353. let fillColor = null;
  2354. let interiorColor = parameters.dict.getArray("IC");
  2355. if (interiorColor) {
  2356. interiorColor = getRgbColor(interiorColor, null);
  2357. fillColor = interiorColor ? Array.from(interiorColor).map(c => c / 255) : null;
  2358. }
  2359. const fillAlpha = fillColor ? strokeAlpha : null;
  2360. if (this.borderStyle.width === 0 && !fillColor) {
  2361. return;
  2362. }
  2363. const controlPointsDistance = 4 / 3 * Math.tan(Math.PI / (2 * 4));
  2364. this._setDefaultAppearance({
  2365. xref: parameters.xref,
  2366. extra: `${this.borderStyle.width} w`,
  2367. strokeColor,
  2368. fillColor,
  2369. strokeAlpha,
  2370. fillAlpha,
  2371. pointsCallback: (buffer, points) => {
  2372. const x0 = points[0].x + this.borderStyle.width / 2;
  2373. const y0 = points[0].y - this.borderStyle.width / 2;
  2374. const x1 = points[3].x - this.borderStyle.width / 2;
  2375. const y1 = points[3].y + this.borderStyle.width / 2;
  2376. const xMid = x0 + (x1 - x0) / 2;
  2377. const yMid = y0 + (y1 - y0) / 2;
  2378. const xOffset = (x1 - x0) / 2 * controlPointsDistance;
  2379. const yOffset = (y1 - y0) / 2 * controlPointsDistance;
  2380. 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");
  2381. if (fillColor) {
  2382. buffer.push("B");
  2383. } else {
  2384. buffer.push("S");
  2385. }
  2386. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2387. }
  2388. });
  2389. }
  2390. }
  2391. }
  2392. class PolylineAnnotation extends MarkupAnnotation {
  2393. constructor(parameters) {
  2394. super(parameters);
  2395. const {
  2396. dict
  2397. } = parameters;
  2398. this.data.annotationType = _util.AnnotationType.POLYLINE;
  2399. this.data.vertices = [];
  2400. if (!(this instanceof PolygonAnnotation)) {
  2401. this.setLineEndings(dict.getArray("LE"));
  2402. this.data.lineEndings = this.lineEndings;
  2403. }
  2404. const rawVertices = dict.getArray("Vertices");
  2405. if (!Array.isArray(rawVertices)) {
  2406. return;
  2407. }
  2408. for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
  2409. this.data.vertices.push({
  2410. x: rawVertices[i],
  2411. y: rawVertices[i + 1]
  2412. });
  2413. }
  2414. if (!this.appearance) {
  2415. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2416. const strokeAlpha = dict.get("CA");
  2417. const borderWidth = this.borderStyle.width || 1,
  2418. borderAdjust = 2 * borderWidth;
  2419. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  2420. for (const vertex of this.data.vertices) {
  2421. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  2422. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  2423. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  2424. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  2425. }
  2426. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2427. this.rectangle = bbox;
  2428. }
  2429. this._setDefaultAppearance({
  2430. xref: parameters.xref,
  2431. extra: `${borderWidth} w`,
  2432. strokeColor,
  2433. strokeAlpha,
  2434. pointsCallback: (buffer, points) => {
  2435. const vertices = this.data.vertices;
  2436. for (let i = 0, ii = vertices.length; i < ii; i++) {
  2437. buffer.push(`${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`);
  2438. }
  2439. buffer.push("S");
  2440. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2441. }
  2442. });
  2443. }
  2444. }
  2445. }
  2446. class PolygonAnnotation extends PolylineAnnotation {
  2447. constructor(parameters) {
  2448. super(parameters);
  2449. this.data.annotationType = _util.AnnotationType.POLYGON;
  2450. }
  2451. }
  2452. class CaretAnnotation extends MarkupAnnotation {
  2453. constructor(parameters) {
  2454. super(parameters);
  2455. this.data.annotationType = _util.AnnotationType.CARET;
  2456. }
  2457. }
  2458. class InkAnnotation extends MarkupAnnotation {
  2459. constructor(parameters) {
  2460. super(parameters);
  2461. this.data.annotationType = _util.AnnotationType.INK;
  2462. this.data.inkLists = [];
  2463. const rawInkLists = parameters.dict.getArray("InkList");
  2464. if (!Array.isArray(rawInkLists)) {
  2465. return;
  2466. }
  2467. const xref = parameters.xref;
  2468. for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
  2469. this.data.inkLists.push([]);
  2470. for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
  2471. this.data.inkLists[i].push({
  2472. x: xref.fetchIfRef(rawInkLists[i][j]),
  2473. y: xref.fetchIfRef(rawInkLists[i][j + 1])
  2474. });
  2475. }
  2476. }
  2477. if (!this.appearance) {
  2478. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2479. const strokeAlpha = parameters.dict.get("CA");
  2480. const borderWidth = this.borderStyle.width || 1,
  2481. borderAdjust = 2 * borderWidth;
  2482. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  2483. for (const inkLists of this.data.inkLists) {
  2484. for (const vertex of inkLists) {
  2485. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  2486. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  2487. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  2488. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  2489. }
  2490. }
  2491. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2492. this.rectangle = bbox;
  2493. }
  2494. this._setDefaultAppearance({
  2495. xref: parameters.xref,
  2496. extra: `${borderWidth} w`,
  2497. strokeColor,
  2498. strokeAlpha,
  2499. pointsCallback: (buffer, points) => {
  2500. for (const inkList of this.data.inkLists) {
  2501. for (let i = 0, ii = inkList.length; i < ii; i++) {
  2502. buffer.push(`${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`);
  2503. }
  2504. buffer.push("S");
  2505. }
  2506. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2507. }
  2508. });
  2509. }
  2510. }
  2511. static createNewDict(annotation, xref, {
  2512. apRef,
  2513. ap
  2514. }) {
  2515. const {
  2516. paths,
  2517. rect,
  2518. rotation
  2519. } = annotation;
  2520. const ink = new _primitives.Dict(xref);
  2521. ink.set("Type", _primitives.Name.get("Annot"));
  2522. ink.set("Subtype", _primitives.Name.get("Ink"));
  2523. ink.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
  2524. ink.set("Rect", rect);
  2525. ink.set("InkList", paths.map(p => p.points));
  2526. ink.set("F", 4);
  2527. ink.set("Border", [0, 0, 0]);
  2528. ink.set("Rotate", rotation);
  2529. const n = new _primitives.Dict(xref);
  2530. ink.set("AP", n);
  2531. if (apRef) {
  2532. n.set("N", apRef);
  2533. } else {
  2534. n.set("N", ap);
  2535. }
  2536. return ink;
  2537. }
  2538. static async createNewAppearanceStream(annotation, xref, params) {
  2539. const {
  2540. color,
  2541. rect,
  2542. rotation,
  2543. paths,
  2544. thickness,
  2545. opacity
  2546. } = annotation;
  2547. const [x1, y1, x2, y2] = rect;
  2548. let w = x2 - x1;
  2549. let h = y2 - y1;
  2550. if (rotation % 180 !== 0) {
  2551. [w, h] = [h, w];
  2552. }
  2553. const appearanceBuffer = [`${thickness} w 1 J 1 j`, `${(0, _default_appearance.getPdfColor)(color, false)}`];
  2554. if (opacity !== 1) {
  2555. appearanceBuffer.push("/R0 gs");
  2556. }
  2557. const buffer = [];
  2558. for (const {
  2559. bezier
  2560. } of paths) {
  2561. buffer.length = 0;
  2562. buffer.push(`${(0, _core_utils.numberToString)(bezier[0])} ${(0, _core_utils.numberToString)(bezier[1])} m`);
  2563. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  2564. const curve = bezier.slice(i, i + 6).map(_core_utils.numberToString).join(" ");
  2565. buffer.push(`${curve} c`);
  2566. }
  2567. buffer.push("S");
  2568. appearanceBuffer.push(buffer.join("\n"));
  2569. }
  2570. const appearance = appearanceBuffer.join("\n");
  2571. const appearanceStreamDict = new _primitives.Dict(xref);
  2572. appearanceStreamDict.set("FormType", 1);
  2573. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  2574. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  2575. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  2576. appearanceStreamDict.set("Length", appearance.length);
  2577. if (rotation) {
  2578. const matrix = WidgetAnnotation._getRotationMatrix(rotation, w, h);
  2579. appearanceStreamDict.set("Matrix", matrix);
  2580. }
  2581. if (opacity !== 1) {
  2582. const resources = new _primitives.Dict(xref);
  2583. const extGState = new _primitives.Dict(xref);
  2584. const r0 = new _primitives.Dict(xref);
  2585. r0.set("CA", opacity);
  2586. r0.set("Type", _primitives.Name.get("ExtGState"));
  2587. extGState.set("R0", r0);
  2588. resources.set("ExtGState", extGState);
  2589. appearanceStreamDict.set("Resources", resources);
  2590. }
  2591. const ap = new _stream.StringStream(appearance);
  2592. ap.dict = appearanceStreamDict;
  2593. return ap;
  2594. }
  2595. }
  2596. class HighlightAnnotation extends MarkupAnnotation {
  2597. constructor(parameters) {
  2598. super(parameters);
  2599. this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
  2600. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2601. if (quadPoints) {
  2602. const resources = this.appearance && this.appearance.dict.get("Resources");
  2603. if (!this.appearance || !(resources && resources.has("ExtGState"))) {
  2604. if (this.appearance) {
  2605. (0, _util.warn)("HighlightAnnotation - ignoring built-in appearance stream.");
  2606. }
  2607. const fillColor = this.color ? Array.from(this.color).map(c => c / 255) : [1, 1, 0];
  2608. const fillAlpha = parameters.dict.get("CA");
  2609. this._setDefaultAppearance({
  2610. xref: parameters.xref,
  2611. fillColor,
  2612. blendMode: "Multiply",
  2613. fillAlpha,
  2614. pointsCallback: (buffer, points) => {
  2615. 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");
  2616. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2617. }
  2618. });
  2619. }
  2620. } else {
  2621. this.data.hasPopup = false;
  2622. }
  2623. }
  2624. }
  2625. class UnderlineAnnotation extends MarkupAnnotation {
  2626. constructor(parameters) {
  2627. super(parameters);
  2628. this.data.annotationType = _util.AnnotationType.UNDERLINE;
  2629. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2630. if (quadPoints) {
  2631. if (!this.appearance) {
  2632. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2633. const strokeAlpha = parameters.dict.get("CA");
  2634. this._setDefaultAppearance({
  2635. xref: parameters.xref,
  2636. extra: "[] 0 d 1 w",
  2637. strokeColor,
  2638. strokeAlpha,
  2639. pointsCallback: (buffer, points) => {
  2640. buffer.push(`${points[2].x} ${points[2].y} m`, `${points[3].x} ${points[3].y} l`, "S");
  2641. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2642. }
  2643. });
  2644. }
  2645. } else {
  2646. this.data.hasPopup = false;
  2647. }
  2648. }
  2649. }
  2650. class SquigglyAnnotation extends MarkupAnnotation {
  2651. constructor(parameters) {
  2652. super(parameters);
  2653. this.data.annotationType = _util.AnnotationType.SQUIGGLY;
  2654. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2655. if (quadPoints) {
  2656. if (!this.appearance) {
  2657. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2658. const strokeAlpha = parameters.dict.get("CA");
  2659. this._setDefaultAppearance({
  2660. xref: parameters.xref,
  2661. extra: "[] 0 d 1 w",
  2662. strokeColor,
  2663. strokeAlpha,
  2664. pointsCallback: (buffer, points) => {
  2665. const dy = (points[0].y - points[2].y) / 6;
  2666. let shift = dy;
  2667. let x = points[2].x;
  2668. const y = points[2].y;
  2669. const xEnd = points[3].x;
  2670. buffer.push(`${x} ${y + shift} m`);
  2671. do {
  2672. x += 2;
  2673. shift = shift === 0 ? dy : 0;
  2674. buffer.push(`${x} ${y + shift} l`);
  2675. } while (x < xEnd);
  2676. buffer.push("S");
  2677. return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
  2678. }
  2679. });
  2680. }
  2681. } else {
  2682. this.data.hasPopup = false;
  2683. }
  2684. }
  2685. }
  2686. class StrikeOutAnnotation extends MarkupAnnotation {
  2687. constructor(parameters) {
  2688. super(parameters);
  2689. this.data.annotationType = _util.AnnotationType.STRIKEOUT;
  2690. const quadPoints = this.data.quadPoints = getQuadPoints(parameters.dict, null);
  2691. if (quadPoints) {
  2692. if (!this.appearance) {
  2693. const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0];
  2694. const strokeAlpha = parameters.dict.get("CA");
  2695. this._setDefaultAppearance({
  2696. xref: parameters.xref,
  2697. extra: "[] 0 d 1 w",
  2698. strokeColor,
  2699. strokeAlpha,
  2700. pointsCallback: (buffer, points) => {
  2701. 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");
  2702. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2703. }
  2704. });
  2705. }
  2706. } else {
  2707. this.data.hasPopup = false;
  2708. }
  2709. }
  2710. }
  2711. class StampAnnotation extends MarkupAnnotation {
  2712. constructor(parameters) {
  2713. super(parameters);
  2714. this.data.annotationType = _util.AnnotationType.STAMP;
  2715. }
  2716. }
  2717. class FileAttachmentAnnotation extends MarkupAnnotation {
  2718. constructor(parameters) {
  2719. super(parameters);
  2720. const file = new _file_spec.FileSpec(parameters.dict.get("FS"), parameters.xref);
  2721. this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
  2722. this.data.file = file.serializable;
  2723. }
  2724. }