2
0

annotation.js 100 KB

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