2
0

annotation.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867
  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. value = value.trim();
  1253. if (value === "") {
  1254. return `/Tx BMC q ${colors}Q EMC`;
  1255. }
  1256. if (rotation === undefined) {
  1257. rotation = this.rotation;
  1258. }
  1259. let lineCount = -1;
  1260. let lines;
  1261. if (this.data.multiLine) {
  1262. lines = value.split(/\r\n?|\n/).map(line => line.normalize("NFC"));
  1263. lineCount = lines.length;
  1264. } else {
  1265. lines = [value.replace(/\r\n?|\n/, "").normalize("NFC")];
  1266. }
  1267. const defaultPadding = 1;
  1268. const defaultHPadding = 2;
  1269. let totalHeight = this.data.rect[3] - this.data.rect[1];
  1270. let totalWidth = this.data.rect[2] - this.data.rect[0];
  1271. if (rotation === 90 || rotation === 270) {
  1272. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  1273. }
  1274. if (!this._defaultAppearance) {
  1275. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  1276. }
  1277. let font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
  1278. let defaultAppearance, fontSize, lineHeight;
  1279. const encodedLines = [];
  1280. let encodingError = false;
  1281. for (const line of lines) {
  1282. const encodedString = font.encodeString(line);
  1283. if (encodedString.length > 1) {
  1284. encodingError = true;
  1285. }
  1286. encodedLines.push(encodedString.join(""));
  1287. }
  1288. if (encodingError && intent & _util.RenderingIntentFlag.SAVE) {
  1289. return {
  1290. needAppearances: true
  1291. };
  1292. }
  1293. if (encodingError && this._isOffscreenCanvasSupported) {
  1294. const fontFamily = this.data.comb ? "monospace" : "sans-serif";
  1295. const fakeUnicodeFont = new _default_appearance.FakeUnicodeFont(evaluator.xref, fontFamily);
  1296. const resources = fakeUnicodeFont.createFontResources(lines.join(""));
  1297. const newFont = resources.getRaw("Font");
  1298. if (this._fieldResources.mergedResources.has("Font")) {
  1299. const oldFont = this._fieldResources.mergedResources.get("Font");
  1300. for (const key of newFont.getKeys()) {
  1301. oldFont.set(key, newFont.getRaw(key));
  1302. }
  1303. } else {
  1304. this._fieldResources.mergedResources.set("Font", newFont);
  1305. }
  1306. const fontName = fakeUnicodeFont.fontName.name;
  1307. font = await WidgetAnnotation._getFontData(evaluator, task, {
  1308. fontName,
  1309. fontSize: 0
  1310. }, resources);
  1311. for (let i = 0, ii = encodedLines.length; i < ii; i++) {
  1312. encodedLines[i] = (0, _core_utils.stringToUTF16String)(lines[i]);
  1313. }
  1314. const savedDefaultAppearance = Object.assign(Object.create(null), this.data.defaultAppearanceData);
  1315. this.data.defaultAppearanceData.fontSize = 0;
  1316. this.data.defaultAppearanceData.fontName = fontName;
  1317. [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(totalHeight - 2 * defaultPadding, totalWidth - 2 * defaultHPadding, value, font, lineCount);
  1318. this.data.defaultAppearanceData = savedDefaultAppearance;
  1319. } else {
  1320. if (!this._isOffscreenCanvasSupported) {
  1321. (0, _util.warn)("_getAppearance: OffscreenCanvas is not supported, annotation may not render correctly.");
  1322. }
  1323. [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(totalHeight - 2 * defaultPadding, totalWidth - 2 * defaultHPadding, value, font, lineCount);
  1324. }
  1325. let descent = font.descent;
  1326. if (isNaN(descent)) {
  1327. descent = _util.BASELINE_FACTOR * lineHeight;
  1328. } else {
  1329. descent = Math.max(_util.BASELINE_FACTOR * lineHeight, Math.abs(descent) * fontSize);
  1330. }
  1331. const defaultVPadding = Math.min(Math.floor((totalHeight - fontSize) / 2), defaultPadding);
  1332. const alignment = this.data.textAlignment;
  1333. if (this.data.multiLine) {
  1334. return this._getMultilineAppearance(defaultAppearance, encodedLines, font, fontSize, totalWidth, totalHeight, alignment, defaultHPadding, defaultVPadding, descent, lineHeight, annotationStorage);
  1335. }
  1336. if (this.data.comb) {
  1337. return this._getCombAppearance(defaultAppearance, font, encodedLines[0], fontSize, totalWidth, totalHeight, defaultHPadding, defaultVPadding, descent, lineHeight, annotationStorage);
  1338. }
  1339. const bottomPadding = defaultVPadding + descent;
  1340. if (alignment === 0 || alignment > 2) {
  1341. 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";
  1342. }
  1343. const prevInfo = {
  1344. shift: 0
  1345. };
  1346. const renderedText = this._renderText(encodedLines[0], font, fontSize, totalWidth, alignment, prevInfo, defaultHPadding, bottomPadding);
  1347. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC";
  1348. }
  1349. static async _getFontData(evaluator, task, appearanceData, resources) {
  1350. const operatorList = new _operator_list.OperatorList();
  1351. const initialState = {
  1352. font: null,
  1353. clone() {
  1354. return this;
  1355. }
  1356. };
  1357. const {
  1358. fontName,
  1359. fontSize
  1360. } = appearanceData;
  1361. await evaluator.handleSetFont(resources, [fontName && _primitives.Name.get(fontName), fontSize], null, operatorList, task, initialState, null);
  1362. return initialState.font;
  1363. }
  1364. _getTextWidth(text, font) {
  1365. return font.charsToGlyphs(text).reduce((width, glyph) => width + glyph.width, 0) / 1000;
  1366. }
  1367. _computeFontSize(height, width, text, font, lineCount) {
  1368. let {
  1369. fontSize
  1370. } = this.data.defaultAppearanceData;
  1371. let lineHeight = (fontSize || 12) * _util.LINE_FACTOR,
  1372. numberOfLines = Math.round(height / lineHeight);
  1373. if (!fontSize) {
  1374. const roundWithTwoDigits = x => Math.floor(x * 100) / 100;
  1375. if (lineCount === -1) {
  1376. const textWidth = this._getTextWidth(text, font);
  1377. fontSize = roundWithTwoDigits(Math.min(height / _util.LINE_FACTOR, textWidth > width ? width / textWidth : Infinity));
  1378. numberOfLines = 1;
  1379. } else {
  1380. const lines = text.split(/\r\n?|\n/);
  1381. const cachedLines = [];
  1382. for (const line of lines) {
  1383. const encoded = font.encodeString(line).join("");
  1384. const glyphs = font.charsToGlyphs(encoded);
  1385. const positions = font.getCharPositions(encoded);
  1386. cachedLines.push({
  1387. line: encoded,
  1388. glyphs,
  1389. positions
  1390. });
  1391. }
  1392. const isTooBig = fsize => {
  1393. let totalHeight = 0;
  1394. for (const cache of cachedLines) {
  1395. const chunks = this._splitLine(null, font, fsize, width, cache);
  1396. totalHeight += chunks.length * fsize;
  1397. if (totalHeight > height) {
  1398. return true;
  1399. }
  1400. }
  1401. return false;
  1402. };
  1403. numberOfLines = Math.max(numberOfLines, lineCount);
  1404. while (true) {
  1405. lineHeight = height / numberOfLines;
  1406. fontSize = roundWithTwoDigits(lineHeight / _util.LINE_FACTOR);
  1407. if (isTooBig(fontSize)) {
  1408. numberOfLines++;
  1409. continue;
  1410. }
  1411. break;
  1412. }
  1413. }
  1414. const {
  1415. fontName,
  1416. fontColor
  1417. } = this.data.defaultAppearanceData;
  1418. this._defaultAppearance = (0, _default_appearance.createDefaultAppearance)({
  1419. fontSize,
  1420. fontName,
  1421. fontColor
  1422. });
  1423. }
  1424. return [this._defaultAppearance, fontSize, height / numberOfLines];
  1425. }
  1426. _renderText(text, font, fontSize, totalWidth, alignment, prevInfo, hPadding, vPadding) {
  1427. let shift;
  1428. if (alignment === 1) {
  1429. const width = this._getTextWidth(text, font) * fontSize;
  1430. shift = (totalWidth - width) / 2;
  1431. } else if (alignment === 2) {
  1432. const width = this._getTextWidth(text, font) * fontSize;
  1433. shift = totalWidth - width - hPadding;
  1434. } else {
  1435. shift = hPadding;
  1436. }
  1437. const shiftStr = (0, _core_utils.numberToString)(shift - prevInfo.shift);
  1438. prevInfo.shift = shift;
  1439. vPadding = (0, _core_utils.numberToString)(vPadding);
  1440. return `${shiftStr} ${vPadding} Td (${(0, _core_utils.escapeString)(text)}) Tj`;
  1441. }
  1442. _getSaveFieldResources(xref) {
  1443. const {
  1444. localResources,
  1445. appearanceResources,
  1446. acroFormResources
  1447. } = this._fieldResources;
  1448. const fontName = this.data.defaultAppearanceData && this.data.defaultAppearanceData.fontName;
  1449. if (!fontName) {
  1450. return localResources || _primitives.Dict.empty;
  1451. }
  1452. for (const resources of [localResources, appearanceResources]) {
  1453. if (resources instanceof _primitives.Dict) {
  1454. const localFont = resources.get("Font");
  1455. if (localFont instanceof _primitives.Dict && localFont.has(fontName)) {
  1456. return resources;
  1457. }
  1458. }
  1459. }
  1460. if (acroFormResources instanceof _primitives.Dict) {
  1461. const acroFormFont = acroFormResources.get("Font");
  1462. if (acroFormFont instanceof _primitives.Dict && acroFormFont.has(fontName)) {
  1463. const subFontDict = new _primitives.Dict(xref);
  1464. subFontDict.set(fontName, acroFormFont.getRaw(fontName));
  1465. const subResourcesDict = new _primitives.Dict(xref);
  1466. subResourcesDict.set("Font", subFontDict);
  1467. return _primitives.Dict.merge({
  1468. xref,
  1469. dictArray: [subResourcesDict, localResources],
  1470. mergeSubDicts: true
  1471. });
  1472. }
  1473. }
  1474. return localResources || _primitives.Dict.empty;
  1475. }
  1476. getFieldObject() {
  1477. return null;
  1478. }
  1479. }
  1480. class TextWidgetAnnotation extends WidgetAnnotation {
  1481. constructor(params) {
  1482. super(params);
  1483. this._hasText = true;
  1484. const dict = params.dict;
  1485. if (typeof this.data.fieldValue !== "string") {
  1486. this.data.fieldValue = "";
  1487. }
  1488. let alignment = (0, _core_utils.getInheritableProperty)({
  1489. dict,
  1490. key: "Q"
  1491. });
  1492. if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
  1493. alignment = null;
  1494. }
  1495. this.data.textAlignment = alignment;
  1496. let maximumLength = (0, _core_utils.getInheritableProperty)({
  1497. dict,
  1498. key: "MaxLen"
  1499. });
  1500. if (!Number.isInteger(maximumLength) || maximumLength < 0) {
  1501. maximumLength = 0;
  1502. }
  1503. this.data.maxLen = maximumLength;
  1504. this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
  1505. 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;
  1506. this.data.doNotScroll = this.hasFieldFlag(_util.AnnotationFieldFlag.DONOTSCROLL);
  1507. }
  1508. _getCombAppearance(defaultAppearance, font, text, fontSize, width, height, hPadding, vPadding, descent, lineHeight, annotationStorage) {
  1509. const combWidth = width / this.data.maxLen;
  1510. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1511. const buf = [];
  1512. const positions = font.getCharPositions(text);
  1513. for (const [start, end] of positions) {
  1514. buf.push(`(${(0, _core_utils.escapeString)(text.substring(start, end))}) Tj`);
  1515. }
  1516. const renderedComb = buf.join(` ${(0, _core_utils.numberToString)(combWidth)} 0 Td `);
  1517. 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";
  1518. }
  1519. _getMultilineAppearance(defaultAppearance, lines, font, fontSize, width, height, alignment, hPadding, vPadding, descent, lineHeight, annotationStorage) {
  1520. const buf = [];
  1521. const totalWidth = width - 2 * hPadding;
  1522. const prevInfo = {
  1523. shift: 0
  1524. };
  1525. for (let i = 0, ii = lines.length; i < ii; i++) {
  1526. const line = lines[i];
  1527. const chunks = this._splitLine(line, font, fontSize, totalWidth);
  1528. for (let j = 0, jj = chunks.length; j < jj; j++) {
  1529. const chunk = chunks[j];
  1530. const vShift = i === 0 && j === 0 ? -vPadding - (lineHeight - descent) : -lineHeight;
  1531. buf.push(this._renderText(chunk, font, fontSize, width, alignment, prevInfo, hPadding, vShift));
  1532. }
  1533. }
  1534. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1535. const renderedText = buf.join("\n");
  1536. return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 ${(0, _core_utils.numberToString)(height)} Tm ${renderedText}` + " ET Q EMC";
  1537. }
  1538. _splitLine(line, font, fontSize, width, cache = {}) {
  1539. line = cache.line || line;
  1540. const glyphs = cache.glyphs || font.charsToGlyphs(line);
  1541. if (glyphs.length <= 1) {
  1542. return [line];
  1543. }
  1544. const positions = cache.positions || font.getCharPositions(line);
  1545. const scale = fontSize / 1000;
  1546. const chunks = [];
  1547. let lastSpacePosInStringStart = -1,
  1548. lastSpacePosInStringEnd = -1,
  1549. lastSpacePos = -1,
  1550. startChunk = 0,
  1551. currentWidth = 0;
  1552. for (let i = 0, ii = glyphs.length; i < ii; i++) {
  1553. const [start, end] = positions[i];
  1554. const glyph = glyphs[i];
  1555. const glyphWidth = glyph.width * scale;
  1556. if (glyph.unicode === " ") {
  1557. if (currentWidth + glyphWidth > width) {
  1558. chunks.push(line.substring(startChunk, start));
  1559. startChunk = start;
  1560. currentWidth = glyphWidth;
  1561. lastSpacePosInStringStart = -1;
  1562. lastSpacePos = -1;
  1563. } else {
  1564. currentWidth += glyphWidth;
  1565. lastSpacePosInStringStart = start;
  1566. lastSpacePosInStringEnd = end;
  1567. lastSpacePos = i;
  1568. }
  1569. } else {
  1570. if (currentWidth + glyphWidth > width) {
  1571. if (lastSpacePosInStringStart !== -1) {
  1572. chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
  1573. startChunk = lastSpacePosInStringEnd;
  1574. i = lastSpacePos + 1;
  1575. lastSpacePosInStringStart = -1;
  1576. currentWidth = 0;
  1577. } else {
  1578. chunks.push(line.substring(startChunk, start));
  1579. startChunk = start;
  1580. currentWidth = glyphWidth;
  1581. }
  1582. } else {
  1583. currentWidth += glyphWidth;
  1584. }
  1585. }
  1586. }
  1587. if (startChunk < line.length) {
  1588. chunks.push(line.substring(startChunk, line.length));
  1589. }
  1590. return chunks;
  1591. }
  1592. getFieldObject() {
  1593. return {
  1594. id: this.data.id,
  1595. value: this.data.fieldValue,
  1596. defaultValue: this.data.defaultFieldValue || "",
  1597. multiline: this.data.multiLine,
  1598. password: this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD),
  1599. charLimit: this.data.maxLen,
  1600. comb: this.data.comb,
  1601. editable: !this.data.readOnly,
  1602. hidden: this.data.hidden,
  1603. name: this.data.fieldName,
  1604. rect: this.data.rect,
  1605. actions: this.data.actions,
  1606. page: this.data.pageIndex,
  1607. strokeColor: this.data.borderColor,
  1608. fillColor: this.data.backgroundColor,
  1609. rotation: this.rotation,
  1610. type: "text"
  1611. };
  1612. }
  1613. }
  1614. class ButtonWidgetAnnotation extends WidgetAnnotation {
  1615. constructor(params) {
  1616. super(params);
  1617. this.checkedAppearance = null;
  1618. this.uncheckedAppearance = null;
  1619. this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1620. this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1621. this.data.pushButton = this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
  1622. this.data.isTooltipOnly = false;
  1623. if (this.data.checkBox) {
  1624. this._processCheckBox(params);
  1625. } else if (this.data.radioButton) {
  1626. this._processRadioButton(params);
  1627. } else if (this.data.pushButton) {
  1628. this.data.hasOwnCanvas = true;
  1629. this._processPushButton(params);
  1630. } else {
  1631. (0, _util.warn)("Invalid field flags for button widget annotation");
  1632. }
  1633. }
  1634. async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
  1635. if (this.data.pushButton) {
  1636. return super.getOperatorList(evaluator, task, intent, false, annotationStorage);
  1637. }
  1638. let value = null;
  1639. let rotation = null;
  1640. if (annotationStorage) {
  1641. const storageEntry = annotationStorage.get(this.data.id);
  1642. value = storageEntry ? storageEntry.value : null;
  1643. rotation = storageEntry ? storageEntry.rotation : null;
  1644. }
  1645. if (value === null && this.appearance) {
  1646. return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1647. }
  1648. if (value === null || value === undefined) {
  1649. if (this.data.checkBox) {
  1650. value = this.data.fieldValue === this.data.exportValue;
  1651. } else {
  1652. value = this.data.fieldValue === this.data.buttonValue;
  1653. }
  1654. }
  1655. const appearance = value ? this.checkedAppearance : this.uncheckedAppearance;
  1656. if (appearance) {
  1657. const savedAppearance = this.appearance;
  1658. const savedMatrix = appearance.dict.getArray("Matrix") || _util.IDENTITY_MATRIX;
  1659. if (rotation) {
  1660. appearance.dict.set("Matrix", this.getRotationMatrix(annotationStorage));
  1661. }
  1662. this.appearance = appearance;
  1663. const operatorList = super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
  1664. this.appearance = savedAppearance;
  1665. appearance.dict.set("Matrix", savedMatrix);
  1666. return operatorList;
  1667. }
  1668. return {
  1669. opList: new _operator_list.OperatorList(),
  1670. separateForm: false,
  1671. separateCanvas: false
  1672. };
  1673. }
  1674. async save(evaluator, task, annotationStorage) {
  1675. if (this.data.checkBox) {
  1676. return this._saveCheckbox(evaluator, task, annotationStorage);
  1677. }
  1678. if (this.data.radioButton) {
  1679. return this._saveRadioButton(evaluator, task, annotationStorage);
  1680. }
  1681. return null;
  1682. }
  1683. async _saveCheckbox(evaluator, task, annotationStorage) {
  1684. if (!annotationStorage) {
  1685. return null;
  1686. }
  1687. const storageEntry = annotationStorage.get(this.data.id);
  1688. let rotation = storageEntry && storageEntry.rotation;
  1689. let value = storageEntry && storageEntry.value;
  1690. if (rotation === undefined) {
  1691. if (value === undefined) {
  1692. return null;
  1693. }
  1694. const defaultValue = this.data.fieldValue === this.data.exportValue;
  1695. if (defaultValue === value) {
  1696. return null;
  1697. }
  1698. }
  1699. const dict = evaluator.xref.fetchIfRef(this.ref);
  1700. if (!(dict instanceof _primitives.Dict)) {
  1701. return null;
  1702. }
  1703. if (rotation === undefined) {
  1704. rotation = this.rotation;
  1705. }
  1706. if (value === undefined) {
  1707. value = this.data.fieldValue === this.data.exportValue;
  1708. }
  1709. const xfa = {
  1710. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1711. value: value ? this.data.exportValue : ""
  1712. };
  1713. const name = _primitives.Name.get(value ? this.data.exportValue : "Off");
  1714. dict.set("V", name);
  1715. dict.set("AS", name);
  1716. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1717. const maybeMK = this._getMKDict(rotation);
  1718. if (maybeMK) {
  1719. dict.set("MK", maybeMK);
  1720. }
  1721. const encrypt = evaluator.xref.encrypt;
  1722. let originalTransform = null;
  1723. if (encrypt) {
  1724. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1725. }
  1726. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1727. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1728. buffer.push("\nendobj\n");
  1729. return [{
  1730. ref: this.ref,
  1731. data: buffer.join(""),
  1732. xfa
  1733. }];
  1734. }
  1735. async _saveRadioButton(evaluator, task, annotationStorage) {
  1736. if (!annotationStorage) {
  1737. return null;
  1738. }
  1739. const storageEntry = annotationStorage.get(this.data.id);
  1740. let rotation = storageEntry && storageEntry.rotation;
  1741. let value = storageEntry && storageEntry.value;
  1742. if (rotation === undefined) {
  1743. if (value === undefined) {
  1744. return null;
  1745. }
  1746. const defaultValue = this.data.fieldValue === this.data.buttonValue;
  1747. if (defaultValue === value) {
  1748. return null;
  1749. }
  1750. }
  1751. const dict = evaluator.xref.fetchIfRef(this.ref);
  1752. if (!(dict instanceof _primitives.Dict)) {
  1753. return null;
  1754. }
  1755. if (value === undefined) {
  1756. value = this.data.fieldValue === this.data.buttonValue;
  1757. }
  1758. if (rotation === undefined) {
  1759. rotation = this.rotation;
  1760. }
  1761. const xfa = {
  1762. path: (0, _util.stringToPDFString)(dict.get("T") || ""),
  1763. value: value ? this.data.buttonValue : ""
  1764. };
  1765. const name = _primitives.Name.get(value ? this.data.buttonValue : "Off");
  1766. let parentBuffer = null;
  1767. const encrypt = evaluator.xref.encrypt;
  1768. if (value) {
  1769. if (this.parent instanceof _primitives.Ref) {
  1770. const parent = evaluator.xref.fetch(this.parent);
  1771. let parentTransform = null;
  1772. if (encrypt) {
  1773. parentTransform = encrypt.createCipherTransform(this.parent.num, this.parent.gen);
  1774. }
  1775. parent.set("V", name);
  1776. parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
  1777. (0, _writer.writeDict)(parent, parentBuffer, parentTransform);
  1778. parentBuffer.push("\nendobj\n");
  1779. } else if (this.parent instanceof _primitives.Dict) {
  1780. this.parent.set("V", name);
  1781. }
  1782. }
  1783. dict.set("AS", name);
  1784. dict.set("M", `D:${(0, _util.getModificationDate)()}`);
  1785. const maybeMK = this._getMKDict(rotation);
  1786. if (maybeMK) {
  1787. dict.set("MK", maybeMK);
  1788. }
  1789. let originalTransform = null;
  1790. if (encrypt) {
  1791. originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
  1792. }
  1793. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  1794. (0, _writer.writeDict)(dict, buffer, originalTransform);
  1795. buffer.push("\nendobj\n");
  1796. const newRefs = [{
  1797. ref: this.ref,
  1798. data: buffer.join(""),
  1799. xfa
  1800. }];
  1801. if (parentBuffer !== null) {
  1802. newRefs.push({
  1803. ref: this.parent,
  1804. data: parentBuffer.join(""),
  1805. xfa: null
  1806. });
  1807. }
  1808. return newRefs;
  1809. }
  1810. _getDefaultCheckedAppearance(params, type) {
  1811. const width = this.data.rect[2] - this.data.rect[0];
  1812. const height = this.data.rect[3] - this.data.rect[1];
  1813. const bbox = [0, 0, width, height];
  1814. const FONT_RATIO = 0.8;
  1815. const fontSize = Math.min(width, height) * FONT_RATIO;
  1816. let metrics, char;
  1817. if (type === "check") {
  1818. metrics = {
  1819. width: 0.755 * fontSize,
  1820. height: 0.705 * fontSize
  1821. };
  1822. char = "\x33";
  1823. } else if (type === "disc") {
  1824. metrics = {
  1825. width: 0.791 * fontSize,
  1826. height: 0.705 * fontSize
  1827. };
  1828. char = "\x6C";
  1829. } else {
  1830. (0, _util.unreachable)(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
  1831. }
  1832. const xShift = (0, _core_utils.numberToString)((width - metrics.width) / 2);
  1833. const yShift = (0, _core_utils.numberToString)((height - metrics.height) / 2);
  1834. const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
  1835. const appearanceStreamDict = new _primitives.Dict(params.xref);
  1836. appearanceStreamDict.set("FormType", 1);
  1837. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  1838. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  1839. appearanceStreamDict.set("BBox", bbox);
  1840. appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
  1841. appearanceStreamDict.set("Length", appearance.length);
  1842. const resources = new _primitives.Dict(params.xref);
  1843. const font = new _primitives.Dict(params.xref);
  1844. font.set("PdfJsZaDb", this.fallbackFontDict);
  1845. resources.set("Font", font);
  1846. appearanceStreamDict.set("Resources", resources);
  1847. this.checkedAppearance = new _stream.StringStream(appearance);
  1848. this.checkedAppearance.dict = appearanceStreamDict;
  1849. this._streams.push(this.checkedAppearance);
  1850. }
  1851. _processCheckBox(params) {
  1852. const customAppearance = params.dict.get("AP");
  1853. if (!(customAppearance instanceof _primitives.Dict)) {
  1854. return;
  1855. }
  1856. const normalAppearance = customAppearance.get("N");
  1857. if (!(normalAppearance instanceof _primitives.Dict)) {
  1858. return;
  1859. }
  1860. const asValue = this._decodeFormValue(params.dict.get("AS"));
  1861. if (typeof asValue === "string") {
  1862. this.data.fieldValue = asValue;
  1863. }
  1864. const yes = this.data.fieldValue !== null && this.data.fieldValue !== "Off" ? this.data.fieldValue : "Yes";
  1865. const exportValues = normalAppearance.getKeys();
  1866. if (exportValues.length === 0) {
  1867. exportValues.push("Off", yes);
  1868. } else if (exportValues.length === 1) {
  1869. if (exportValues[0] === "Off") {
  1870. exportValues.push(yes);
  1871. } else {
  1872. exportValues.unshift("Off");
  1873. }
  1874. } else if (exportValues.includes(yes)) {
  1875. exportValues.length = 0;
  1876. exportValues.push("Off", yes);
  1877. } else {
  1878. const otherYes = exportValues.find(v => v !== "Off");
  1879. exportValues.length = 0;
  1880. exportValues.push("Off", otherYes);
  1881. }
  1882. if (!exportValues.includes(this.data.fieldValue)) {
  1883. this.data.fieldValue = "Off";
  1884. }
  1885. this.data.exportValue = exportValues[1];
  1886. this.checkedAppearance = normalAppearance.get(this.data.exportValue) || null;
  1887. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1888. if (this.checkedAppearance) {
  1889. this._streams.push(this.checkedAppearance);
  1890. } else {
  1891. this._getDefaultCheckedAppearance(params, "check");
  1892. }
  1893. if (this.uncheckedAppearance) {
  1894. this._streams.push(this.uncheckedAppearance);
  1895. }
  1896. this._fallbackFontDict = this.fallbackFontDict;
  1897. }
  1898. _processRadioButton(params) {
  1899. this.data.fieldValue = this.data.buttonValue = null;
  1900. const fieldParent = params.dict.get("Parent");
  1901. if (fieldParent instanceof _primitives.Dict) {
  1902. this.parent = params.dict.getRaw("Parent");
  1903. const fieldParentValue = fieldParent.get("V");
  1904. if (fieldParentValue instanceof _primitives.Name) {
  1905. this.data.fieldValue = this._decodeFormValue(fieldParentValue);
  1906. }
  1907. }
  1908. const appearanceStates = params.dict.get("AP");
  1909. if (!(appearanceStates instanceof _primitives.Dict)) {
  1910. return;
  1911. }
  1912. const normalAppearance = appearanceStates.get("N");
  1913. if (!(normalAppearance instanceof _primitives.Dict)) {
  1914. return;
  1915. }
  1916. for (const key of normalAppearance.getKeys()) {
  1917. if (key !== "Off") {
  1918. this.data.buttonValue = this._decodeFormValue(key);
  1919. break;
  1920. }
  1921. }
  1922. this.checkedAppearance = normalAppearance.get(this.data.buttonValue) || null;
  1923. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  1924. if (this.checkedAppearance) {
  1925. this._streams.push(this.checkedAppearance);
  1926. } else {
  1927. this._getDefaultCheckedAppearance(params, "disc");
  1928. }
  1929. if (this.uncheckedAppearance) {
  1930. this._streams.push(this.uncheckedAppearance);
  1931. }
  1932. this._fallbackFontDict = this.fallbackFontDict;
  1933. }
  1934. _processPushButton(params) {
  1935. if (!params.dict.has("A") && !params.dict.has("AA") && !this.data.alternativeText) {
  1936. (0, _util.warn)("Push buttons without action dictionaries are not supported");
  1937. return;
  1938. }
  1939. this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
  1940. _catalog.Catalog.parseDestDictionary({
  1941. destDict: params.dict,
  1942. resultObj: this.data,
  1943. docBaseUrl: params.pdfManager.docBaseUrl,
  1944. docAttachments: params.attachments
  1945. });
  1946. }
  1947. getFieldObject() {
  1948. let type = "button";
  1949. let exportValues;
  1950. if (this.data.checkBox) {
  1951. type = "checkbox";
  1952. exportValues = this.data.exportValue;
  1953. } else if (this.data.radioButton) {
  1954. type = "radiobutton";
  1955. exportValues = this.data.buttonValue;
  1956. }
  1957. return {
  1958. id: this.data.id,
  1959. value: this.data.fieldValue || "Off",
  1960. defaultValue: this.data.defaultFieldValue,
  1961. exportValues,
  1962. editable: !this.data.readOnly,
  1963. name: this.data.fieldName,
  1964. rect: this.data.rect,
  1965. hidden: this.data.hidden,
  1966. actions: this.data.actions,
  1967. page: this.data.pageIndex,
  1968. strokeColor: this.data.borderColor,
  1969. fillColor: this.data.backgroundColor,
  1970. rotation: this.rotation,
  1971. type
  1972. };
  1973. }
  1974. get fallbackFontDict() {
  1975. const dict = new _primitives.Dict();
  1976. dict.set("BaseFont", _primitives.Name.get("ZapfDingbats"));
  1977. dict.set("Type", _primitives.Name.get("FallbackType"));
  1978. dict.set("Subtype", _primitives.Name.get("FallbackType"));
  1979. dict.set("Encoding", _primitives.Name.get("ZapfDingbatsEncoding"));
  1980. return (0, _util.shadow)(this, "fallbackFontDict", dict);
  1981. }
  1982. }
  1983. class ChoiceWidgetAnnotation extends WidgetAnnotation {
  1984. constructor(params) {
  1985. super(params);
  1986. const {
  1987. dict,
  1988. xref
  1989. } = params;
  1990. this.data.options = [];
  1991. const options = (0, _core_utils.getInheritableProperty)({
  1992. dict,
  1993. key: "Opt"
  1994. });
  1995. if (Array.isArray(options)) {
  1996. for (let i = 0, ii = options.length; i < ii; i++) {
  1997. const option = xref.fetchIfRef(options[i]);
  1998. const isOptionArray = Array.isArray(option);
  1999. this.data.options[i] = {
  2000. exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
  2001. displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
  2002. };
  2003. }
  2004. }
  2005. if (typeof this.data.fieldValue === "string") {
  2006. this.data.fieldValue = [this.data.fieldValue];
  2007. } else if (!this.data.fieldValue) {
  2008. this.data.fieldValue = [];
  2009. }
  2010. this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
  2011. this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
  2012. this._hasText = true;
  2013. }
  2014. getFieldObject() {
  2015. const type = this.data.combo ? "combobox" : "listbox";
  2016. const value = this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
  2017. return {
  2018. id: this.data.id,
  2019. value,
  2020. defaultValue: this.data.defaultFieldValue,
  2021. editable: !this.data.readOnly,
  2022. name: this.data.fieldName,
  2023. rect: this.data.rect,
  2024. numItems: this.data.fieldValue.length,
  2025. multipleSelection: this.data.multiSelect,
  2026. hidden: this.data.hidden,
  2027. actions: this.data.actions,
  2028. items: this.data.options,
  2029. page: this.data.pageIndex,
  2030. strokeColor: this.data.borderColor,
  2031. fillColor: this.data.backgroundColor,
  2032. rotation: this.rotation,
  2033. type
  2034. };
  2035. }
  2036. async _getAppearance(evaluator, task, intent, annotationStorage) {
  2037. if (this.data.combo) {
  2038. return super._getAppearance(evaluator, task, intent, annotationStorage);
  2039. }
  2040. let exportedValue, rotation;
  2041. const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
  2042. if (storageEntry) {
  2043. rotation = storageEntry.rotation;
  2044. exportedValue = storageEntry.value;
  2045. }
  2046. if (rotation === undefined && exportedValue === undefined && !this._needAppearances) {
  2047. return null;
  2048. }
  2049. if (exportedValue === undefined) {
  2050. exportedValue = this.data.fieldValue;
  2051. } else if (!Array.isArray(exportedValue)) {
  2052. exportedValue = [exportedValue];
  2053. }
  2054. const defaultPadding = 1;
  2055. const defaultHPadding = 2;
  2056. let totalHeight = this.data.rect[3] - this.data.rect[1];
  2057. let totalWidth = this.data.rect[2] - this.data.rect[0];
  2058. if (rotation === 90 || rotation === 270) {
  2059. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  2060. }
  2061. const lineCount = this.data.options.length;
  2062. const valueIndices = [];
  2063. for (let i = 0; i < lineCount; i++) {
  2064. const {
  2065. exportValue
  2066. } = this.data.options[i];
  2067. if (exportedValue.includes(exportValue)) {
  2068. valueIndices.push(i);
  2069. }
  2070. }
  2071. if (!this._defaultAppearance) {
  2072. this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
  2073. }
  2074. const font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
  2075. let defaultAppearance;
  2076. let {
  2077. fontSize
  2078. } = this.data.defaultAppearanceData;
  2079. if (!fontSize) {
  2080. const lineHeight = (totalHeight - defaultPadding) / lineCount;
  2081. let lineWidth = -1;
  2082. let value;
  2083. for (const {
  2084. displayValue
  2085. } of this.data.options) {
  2086. const width = this._getTextWidth(displayValue, font);
  2087. if (width > lineWidth) {
  2088. lineWidth = width;
  2089. value = displayValue;
  2090. }
  2091. }
  2092. [defaultAppearance, fontSize] = this._computeFontSize(lineHeight, totalWidth - 2 * defaultHPadding, value, font, -1);
  2093. } else {
  2094. defaultAppearance = this._defaultAppearance;
  2095. }
  2096. const lineHeight = fontSize * _util.LINE_FACTOR;
  2097. const vPadding = (lineHeight - fontSize) / 2;
  2098. const numberOfVisibleLines = Math.floor(totalHeight / lineHeight);
  2099. let firstIndex;
  2100. if (valueIndices.length === 1) {
  2101. const valuePosition = valueIndices[0];
  2102. const indexInPage = valuePosition % numberOfVisibleLines;
  2103. firstIndex = valuePosition - indexInPage;
  2104. } else {
  2105. firstIndex = valueIndices.length ? valueIndices[0] : 0;
  2106. }
  2107. const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount);
  2108. const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`];
  2109. if (valueIndices.length) {
  2110. buf.push("0.600006 0.756866 0.854904 rg");
  2111. for (const index of valueIndices) {
  2112. if (firstIndex <= index && index < end) {
  2113. buf.push(`1 ${totalHeight - (index - firstIndex + 1) * lineHeight} ${totalWidth} ${lineHeight} re f`);
  2114. }
  2115. }
  2116. }
  2117. buf.push("BT", defaultAppearance, `1 0 0 1 0 ${totalHeight} Tm`);
  2118. const prevInfo = {
  2119. shift: 0
  2120. };
  2121. for (let i = firstIndex; i < end; i++) {
  2122. const {
  2123. displayValue
  2124. } = this.data.options[i];
  2125. const vpadding = i === firstIndex ? vPadding : 0;
  2126. buf.push(this._renderText(displayValue, font, fontSize, totalWidth, 0, prevInfo, defaultHPadding, -lineHeight + vpadding));
  2127. }
  2128. buf.push("ET Q EMC");
  2129. return buf.join("\n");
  2130. }
  2131. }
  2132. class SignatureWidgetAnnotation extends WidgetAnnotation {
  2133. constructor(params) {
  2134. super(params);
  2135. this.data.fieldValue = null;
  2136. }
  2137. getFieldObject() {
  2138. return {
  2139. id: this.data.id,
  2140. value: null,
  2141. page: this.data.pageIndex,
  2142. type: "signature"
  2143. };
  2144. }
  2145. }
  2146. class TextAnnotation extends MarkupAnnotation {
  2147. constructor(params) {
  2148. const DEFAULT_ICON_SIZE = 22;
  2149. super(params);
  2150. const {
  2151. dict
  2152. } = params;
  2153. this.data.annotationType = _util.AnnotationType.TEXT;
  2154. if (this.data.hasAppearance) {
  2155. this.data.name = "NoIcon";
  2156. } else {
  2157. this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
  2158. this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
  2159. this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
  2160. }
  2161. if (dict.has("State")) {
  2162. this.data.state = dict.get("State") || null;
  2163. this.data.stateModel = dict.get("StateModel") || null;
  2164. } else {
  2165. this.data.state = null;
  2166. this.data.stateModel = null;
  2167. }
  2168. }
  2169. }
  2170. class LinkAnnotation extends Annotation {
  2171. constructor(params) {
  2172. super(params);
  2173. this.data.annotationType = _util.AnnotationType.LINK;
  2174. const quadPoints = getQuadPoints(params.dict, this.rectangle);
  2175. if (quadPoints) {
  2176. this.data.quadPoints = quadPoints;
  2177. }
  2178. this.data.borderColor = this.data.borderColor || this.data.color;
  2179. _catalog.Catalog.parseDestDictionary({
  2180. destDict: params.dict,
  2181. resultObj: this.data,
  2182. docBaseUrl: params.pdfManager.docBaseUrl,
  2183. docAttachments: params.attachments
  2184. });
  2185. }
  2186. }
  2187. class PopupAnnotation extends Annotation {
  2188. constructor(params) {
  2189. super(params);
  2190. const {
  2191. dict
  2192. } = params;
  2193. this.data.annotationType = _util.AnnotationType.POPUP;
  2194. let parentItem = dict.get("Parent");
  2195. if (!parentItem) {
  2196. (0, _util.warn)("Popup annotation has a missing or invalid parent annotation.");
  2197. return;
  2198. }
  2199. const parentSubtype = parentItem.get("Subtype");
  2200. this.data.parentType = parentSubtype instanceof _primitives.Name ? parentSubtype.name : null;
  2201. const rawParent = dict.getRaw("Parent");
  2202. this.data.parentId = rawParent instanceof _primitives.Ref ? rawParent.toString() : null;
  2203. const parentRect = parentItem.getArray("Rect");
  2204. if (Array.isArray(parentRect) && parentRect.length === 4) {
  2205. this.data.parentRect = _util.Util.normalizeRect(parentRect);
  2206. } else {
  2207. this.data.parentRect = [0, 0, 0, 0];
  2208. }
  2209. const rt = parentItem.get("RT");
  2210. if ((0, _primitives.isName)(rt, _util.AnnotationReplyType.GROUP)) {
  2211. parentItem = parentItem.get("IRT");
  2212. }
  2213. if (!parentItem.has("M")) {
  2214. this.data.modificationDate = null;
  2215. } else {
  2216. this.setModificationDate(parentItem.get("M"));
  2217. this.data.modificationDate = this.modificationDate;
  2218. }
  2219. if (!parentItem.has("C")) {
  2220. this.data.color = null;
  2221. } else {
  2222. this.setColor(parentItem.getArray("C"));
  2223. this.data.color = this.color;
  2224. }
  2225. if (!this.viewable) {
  2226. const parentFlags = parentItem.get("F");
  2227. if (this._isViewable(parentFlags)) {
  2228. this.setFlags(parentFlags);
  2229. }
  2230. }
  2231. this.setTitle(parentItem.get("T"));
  2232. this.data.titleObj = this._title;
  2233. this.setContents(parentItem.get("Contents"));
  2234. this.data.contentsObj = this._contents;
  2235. if (parentItem.has("RC")) {
  2236. this.data.richText = _factory.XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
  2237. }
  2238. }
  2239. }
  2240. exports.PopupAnnotation = PopupAnnotation;
  2241. class FreeTextAnnotation extends MarkupAnnotation {
  2242. constructor(params) {
  2243. super(params);
  2244. const {
  2245. xref
  2246. } = params;
  2247. this.data.annotationType = _util.AnnotationType.FREETEXT;
  2248. this.setDefaultAppearance(params);
  2249. if (!this.appearance && this._isOffscreenCanvasSupported) {
  2250. const fakeUnicodeFont = new _default_appearance.FakeUnicodeFont(xref, "sans-serif");
  2251. const fontData = this.data.defaultAppearanceData;
  2252. this.appearance = fakeUnicodeFont.createAppearance(this._contents.str, this.rectangle, this.rotation, fontData.fontSize || 10, fontData.fontColor);
  2253. this._streams.push(this.appearance, _default_appearance.FakeUnicodeFont.toUnicodeStream);
  2254. } else if (!this._isOffscreenCanvasSupported) {
  2255. (0, _util.warn)("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.");
  2256. }
  2257. }
  2258. get hasTextContent() {
  2259. return !!this.appearance;
  2260. }
  2261. static createNewDict(annotation, xref, {
  2262. apRef,
  2263. ap
  2264. }) {
  2265. const {
  2266. color,
  2267. fontSize,
  2268. rect,
  2269. rotation,
  2270. user,
  2271. value
  2272. } = annotation;
  2273. const freetext = new _primitives.Dict(xref);
  2274. freetext.set("Type", _primitives.Name.get("Annot"));
  2275. freetext.set("Subtype", _primitives.Name.get("FreeText"));
  2276. freetext.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
  2277. freetext.set("Rect", rect);
  2278. const da = `/Helv ${fontSize} Tf ${(0, _default_appearance.getPdfColor)(color, true)}`;
  2279. freetext.set("DA", da);
  2280. freetext.set("Contents", (0, _core_utils.isAscii)(value) ? value : (0, _core_utils.stringToUTF16String)(value, true));
  2281. freetext.set("F", 4);
  2282. freetext.set("Border", [0, 0, 0]);
  2283. freetext.set("Rotate", rotation);
  2284. if (user) {
  2285. freetext.set("T", (0, _core_utils.isAscii)(user) ? user : (0, _core_utils.stringToUTF16String)(user, true));
  2286. }
  2287. if (apRef || ap) {
  2288. const n = new _primitives.Dict(xref);
  2289. freetext.set("AP", n);
  2290. if (apRef) {
  2291. n.set("N", apRef);
  2292. } else {
  2293. n.set("N", ap);
  2294. }
  2295. }
  2296. return freetext;
  2297. }
  2298. static async createNewAppearanceStream(annotation, xref, params) {
  2299. const {
  2300. baseFontRef,
  2301. evaluator,
  2302. task
  2303. } = params;
  2304. const {
  2305. color,
  2306. fontSize,
  2307. rect,
  2308. rotation,
  2309. value
  2310. } = annotation;
  2311. const resources = new _primitives.Dict(xref);
  2312. const font = new _primitives.Dict(xref);
  2313. if (baseFontRef) {
  2314. font.set("Helv", baseFontRef);
  2315. } else {
  2316. const baseFont = new _primitives.Dict(xref);
  2317. baseFont.set("BaseFont", _primitives.Name.get("Helvetica"));
  2318. baseFont.set("Type", _primitives.Name.get("Font"));
  2319. baseFont.set("Subtype", _primitives.Name.get("Type1"));
  2320. baseFont.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
  2321. font.set("Helv", baseFont);
  2322. }
  2323. resources.set("Font", font);
  2324. const helv = await WidgetAnnotation._getFontData(evaluator, task, {
  2325. fontName: "Helvetica",
  2326. fontSize
  2327. }, resources);
  2328. const [x1, y1, x2, y2] = rect;
  2329. let w = x2 - x1;
  2330. let h = y2 - y1;
  2331. if (rotation % 180 !== 0) {
  2332. [w, h] = [h, w];
  2333. }
  2334. const lines = value.split("\n");
  2335. const scale = fontSize / 1000;
  2336. let totalWidth = -Infinity;
  2337. const encodedLines = [];
  2338. for (let line of lines) {
  2339. const encoded = helv.encodeString(line);
  2340. if (encoded.length > 1) {
  2341. return null;
  2342. }
  2343. line = encoded.join("");
  2344. encodedLines.push(line);
  2345. let lineWidth = 0;
  2346. const glyphs = helv.charsToGlyphs(line);
  2347. for (const glyph of glyphs) {
  2348. lineWidth += glyph.width * scale;
  2349. }
  2350. totalWidth = Math.max(totalWidth, lineWidth);
  2351. }
  2352. let hscale = 1;
  2353. if (totalWidth > w) {
  2354. hscale = w / totalWidth;
  2355. }
  2356. let vscale = 1;
  2357. const lineHeight = _util.LINE_FACTOR * fontSize;
  2358. const lineDescent = _util.LINE_DESCENT_FACTOR * fontSize;
  2359. const totalHeight = lineHeight * lines.length;
  2360. if (totalHeight > h) {
  2361. vscale = h / totalHeight;
  2362. }
  2363. const fscale = Math.min(hscale, vscale);
  2364. const newFontSize = fontSize * fscale;
  2365. 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`];
  2366. const vShift = (0, _core_utils.numberToString)(lineHeight);
  2367. for (const line of encodedLines) {
  2368. buffer.push(`0 -${vShift} Td (${(0, _core_utils.escapeString)(line)}) Tj`);
  2369. }
  2370. buffer.push("ET", "Q");
  2371. const appearance = buffer.join("\n");
  2372. const appearanceStreamDict = new _primitives.Dict(xref);
  2373. appearanceStreamDict.set("FormType", 1);
  2374. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  2375. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  2376. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  2377. appearanceStreamDict.set("Length", appearance.length);
  2378. appearanceStreamDict.set("Resources", resources);
  2379. if (rotation) {
  2380. const matrix = (0, _core_utils.getRotationMatrix)(rotation, w, h);
  2381. appearanceStreamDict.set("Matrix", matrix);
  2382. }
  2383. const ap = new _stream.StringStream(appearance);
  2384. ap.dict = appearanceStreamDict;
  2385. return ap;
  2386. }
  2387. }
  2388. class LineAnnotation extends MarkupAnnotation {
  2389. constructor(params) {
  2390. super(params);
  2391. const {
  2392. dict,
  2393. xref
  2394. } = params;
  2395. this.data.annotationType = _util.AnnotationType.LINE;
  2396. const lineCoordinates = dict.getArray("L");
  2397. this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates);
  2398. this.setLineEndings(dict.getArray("LE"));
  2399. this.data.lineEndings = this.lineEndings;
  2400. if (!this.appearance) {
  2401. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2402. const strokeAlpha = dict.get("CA");
  2403. const interiorColor = getRgbColor(dict.getArray("IC"), null);
  2404. const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
  2405. const fillAlpha = fillColor ? strokeAlpha : null;
  2406. const borderWidth = this.borderStyle.width || 1,
  2407. borderAdjust = 2 * borderWidth;
  2408. const bbox = [this.data.lineCoordinates[0] - borderAdjust, this.data.lineCoordinates[1] - borderAdjust, this.data.lineCoordinates[2] + borderAdjust, this.data.lineCoordinates[3] + borderAdjust];
  2409. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2410. this.rectangle = bbox;
  2411. }
  2412. this._setDefaultAppearance({
  2413. xref,
  2414. extra: `${borderWidth} w`,
  2415. strokeColor,
  2416. fillColor,
  2417. strokeAlpha,
  2418. fillAlpha,
  2419. pointsCallback: (buffer, points) => {
  2420. buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`, `${lineCoordinates[2]} ${lineCoordinates[3]} l`, "S");
  2421. return [points[0].x - borderWidth, points[1].x + borderWidth, points[3].y - borderWidth, points[1].y + borderWidth];
  2422. }
  2423. });
  2424. }
  2425. }
  2426. }
  2427. class SquareAnnotation extends MarkupAnnotation {
  2428. constructor(params) {
  2429. super(params);
  2430. const {
  2431. dict,
  2432. xref
  2433. } = params;
  2434. this.data.annotationType = _util.AnnotationType.SQUARE;
  2435. if (!this.appearance) {
  2436. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2437. const strokeAlpha = dict.get("CA");
  2438. const interiorColor = getRgbColor(dict.getArray("IC"), null);
  2439. const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
  2440. const fillAlpha = fillColor ? strokeAlpha : null;
  2441. if (this.borderStyle.width === 0 && !fillColor) {
  2442. return;
  2443. }
  2444. this._setDefaultAppearance({
  2445. xref,
  2446. extra: `${this.borderStyle.width} w`,
  2447. strokeColor,
  2448. fillColor,
  2449. strokeAlpha,
  2450. fillAlpha,
  2451. pointsCallback: (buffer, points) => {
  2452. const x = points[2].x + this.borderStyle.width / 2;
  2453. const y = points[2].y + this.borderStyle.width / 2;
  2454. const width = points[3].x - points[2].x - this.borderStyle.width;
  2455. const height = points[1].y - points[3].y - this.borderStyle.width;
  2456. buffer.push(`${x} ${y} ${width} ${height} re`);
  2457. if (fillColor) {
  2458. buffer.push("B");
  2459. } else {
  2460. buffer.push("S");
  2461. }
  2462. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2463. }
  2464. });
  2465. }
  2466. }
  2467. }
  2468. class CircleAnnotation extends MarkupAnnotation {
  2469. constructor(params) {
  2470. super(params);
  2471. const {
  2472. dict,
  2473. xref
  2474. } = params;
  2475. this.data.annotationType = _util.AnnotationType.CIRCLE;
  2476. if (!this.appearance) {
  2477. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2478. const strokeAlpha = dict.get("CA");
  2479. const interiorColor = getRgbColor(dict.getArray("IC"), null);
  2480. const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
  2481. const fillAlpha = fillColor ? strokeAlpha : null;
  2482. if (this.borderStyle.width === 0 && !fillColor) {
  2483. return;
  2484. }
  2485. const controlPointsDistance = 4 / 3 * Math.tan(Math.PI / (2 * 4));
  2486. this._setDefaultAppearance({
  2487. xref,
  2488. extra: `${this.borderStyle.width} w`,
  2489. strokeColor,
  2490. fillColor,
  2491. strokeAlpha,
  2492. fillAlpha,
  2493. pointsCallback: (buffer, points) => {
  2494. const x0 = points[0].x + this.borderStyle.width / 2;
  2495. const y0 = points[0].y - this.borderStyle.width / 2;
  2496. const x1 = points[3].x - this.borderStyle.width / 2;
  2497. const y1 = points[3].y + this.borderStyle.width / 2;
  2498. const xMid = x0 + (x1 - x0) / 2;
  2499. const yMid = y0 + (y1 - y0) / 2;
  2500. const xOffset = (x1 - x0) / 2 * controlPointsDistance;
  2501. const yOffset = (y1 - y0) / 2 * controlPointsDistance;
  2502. 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");
  2503. if (fillColor) {
  2504. buffer.push("B");
  2505. } else {
  2506. buffer.push("S");
  2507. }
  2508. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2509. }
  2510. });
  2511. }
  2512. }
  2513. }
  2514. class PolylineAnnotation extends MarkupAnnotation {
  2515. constructor(params) {
  2516. super(params);
  2517. const {
  2518. dict,
  2519. xref
  2520. } = params;
  2521. this.data.annotationType = _util.AnnotationType.POLYLINE;
  2522. this.data.vertices = [];
  2523. if (!(this instanceof PolygonAnnotation)) {
  2524. this.setLineEndings(dict.getArray("LE"));
  2525. this.data.lineEndings = this.lineEndings;
  2526. }
  2527. const rawVertices = dict.getArray("Vertices");
  2528. if (!Array.isArray(rawVertices)) {
  2529. return;
  2530. }
  2531. for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
  2532. this.data.vertices.push({
  2533. x: rawVertices[i],
  2534. y: rawVertices[i + 1]
  2535. });
  2536. }
  2537. if (!this.appearance) {
  2538. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2539. const strokeAlpha = dict.get("CA");
  2540. const borderWidth = this.borderStyle.width || 1,
  2541. borderAdjust = 2 * borderWidth;
  2542. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  2543. for (const vertex of this.data.vertices) {
  2544. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  2545. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  2546. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  2547. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  2548. }
  2549. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2550. this.rectangle = bbox;
  2551. }
  2552. this._setDefaultAppearance({
  2553. xref,
  2554. extra: `${borderWidth} w`,
  2555. strokeColor,
  2556. strokeAlpha,
  2557. pointsCallback: (buffer, points) => {
  2558. const vertices = this.data.vertices;
  2559. for (let i = 0, ii = vertices.length; i < ii; i++) {
  2560. buffer.push(`${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`);
  2561. }
  2562. buffer.push("S");
  2563. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2564. }
  2565. });
  2566. }
  2567. }
  2568. }
  2569. class PolygonAnnotation extends PolylineAnnotation {
  2570. constructor(params) {
  2571. super(params);
  2572. this.data.annotationType = _util.AnnotationType.POLYGON;
  2573. }
  2574. }
  2575. class CaretAnnotation extends MarkupAnnotation {
  2576. constructor(params) {
  2577. super(params);
  2578. this.data.annotationType = _util.AnnotationType.CARET;
  2579. }
  2580. }
  2581. class InkAnnotation extends MarkupAnnotation {
  2582. constructor(params) {
  2583. super(params);
  2584. const {
  2585. dict,
  2586. xref
  2587. } = params;
  2588. this.data.annotationType = _util.AnnotationType.INK;
  2589. this.data.inkLists = [];
  2590. const rawInkLists = dict.getArray("InkList");
  2591. if (!Array.isArray(rawInkLists)) {
  2592. return;
  2593. }
  2594. for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
  2595. this.data.inkLists.push([]);
  2596. for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
  2597. this.data.inkLists[i].push({
  2598. x: xref.fetchIfRef(rawInkLists[i][j]),
  2599. y: xref.fetchIfRef(rawInkLists[i][j + 1])
  2600. });
  2601. }
  2602. }
  2603. if (!this.appearance) {
  2604. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2605. const strokeAlpha = dict.get("CA");
  2606. const borderWidth = this.borderStyle.width || 1,
  2607. borderAdjust = 2 * borderWidth;
  2608. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  2609. for (const inkLists of this.data.inkLists) {
  2610. for (const vertex of inkLists) {
  2611. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  2612. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  2613. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  2614. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  2615. }
  2616. }
  2617. if (!_util.Util.intersect(this.rectangle, bbox)) {
  2618. this.rectangle = bbox;
  2619. }
  2620. this._setDefaultAppearance({
  2621. xref,
  2622. extra: `${borderWidth} w`,
  2623. strokeColor,
  2624. strokeAlpha,
  2625. pointsCallback: (buffer, points) => {
  2626. for (const inkList of this.data.inkLists) {
  2627. for (let i = 0, ii = inkList.length; i < ii; i++) {
  2628. buffer.push(`${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`);
  2629. }
  2630. buffer.push("S");
  2631. }
  2632. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2633. }
  2634. });
  2635. }
  2636. }
  2637. static createNewDict(annotation, xref, {
  2638. apRef,
  2639. ap
  2640. }) {
  2641. const {
  2642. paths,
  2643. rect,
  2644. rotation
  2645. } = annotation;
  2646. const ink = new _primitives.Dict(xref);
  2647. ink.set("Type", _primitives.Name.get("Annot"));
  2648. ink.set("Subtype", _primitives.Name.get("Ink"));
  2649. ink.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
  2650. ink.set("Rect", rect);
  2651. ink.set("InkList", paths.map(p => p.points));
  2652. ink.set("F", 4);
  2653. ink.set("Border", [0, 0, 0]);
  2654. ink.set("Rotate", rotation);
  2655. const n = new _primitives.Dict(xref);
  2656. ink.set("AP", n);
  2657. if (apRef) {
  2658. n.set("N", apRef);
  2659. } else {
  2660. n.set("N", ap);
  2661. }
  2662. return ink;
  2663. }
  2664. static async createNewAppearanceStream(annotation, xref, params) {
  2665. const {
  2666. color,
  2667. rect,
  2668. rotation,
  2669. paths,
  2670. thickness,
  2671. opacity
  2672. } = annotation;
  2673. const [x1, y1, x2, y2] = rect;
  2674. let w = x2 - x1;
  2675. let h = y2 - y1;
  2676. if (rotation % 180 !== 0) {
  2677. [w, h] = [h, w];
  2678. }
  2679. const appearanceBuffer = [`${thickness} w 1 J 1 j`, `${(0, _default_appearance.getPdfColor)(color, false)}`];
  2680. if (opacity !== 1) {
  2681. appearanceBuffer.push("/R0 gs");
  2682. }
  2683. const buffer = [];
  2684. for (const {
  2685. bezier
  2686. } of paths) {
  2687. buffer.length = 0;
  2688. buffer.push(`${(0, _core_utils.numberToString)(bezier[0])} ${(0, _core_utils.numberToString)(bezier[1])} m`);
  2689. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  2690. const curve = bezier.slice(i, i + 6).map(_core_utils.numberToString).join(" ");
  2691. buffer.push(`${curve} c`);
  2692. }
  2693. buffer.push("S");
  2694. appearanceBuffer.push(buffer.join("\n"));
  2695. }
  2696. const appearance = appearanceBuffer.join("\n");
  2697. const appearanceStreamDict = new _primitives.Dict(xref);
  2698. appearanceStreamDict.set("FormType", 1);
  2699. appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
  2700. appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
  2701. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  2702. appearanceStreamDict.set("Length", appearance.length);
  2703. if (rotation) {
  2704. const matrix = (0, _core_utils.getRotationMatrix)(rotation, w, h);
  2705. appearanceStreamDict.set("Matrix", matrix);
  2706. }
  2707. if (opacity !== 1) {
  2708. const resources = new _primitives.Dict(xref);
  2709. const extGState = new _primitives.Dict(xref);
  2710. const r0 = new _primitives.Dict(xref);
  2711. r0.set("CA", opacity);
  2712. r0.set("Type", _primitives.Name.get("ExtGState"));
  2713. extGState.set("R0", r0);
  2714. resources.set("ExtGState", extGState);
  2715. appearanceStreamDict.set("Resources", resources);
  2716. }
  2717. const ap = new _stream.StringStream(appearance);
  2718. ap.dict = appearanceStreamDict;
  2719. return ap;
  2720. }
  2721. }
  2722. class HighlightAnnotation extends MarkupAnnotation {
  2723. constructor(params) {
  2724. super(params);
  2725. const {
  2726. dict,
  2727. xref
  2728. } = params;
  2729. this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
  2730. const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
  2731. if (quadPoints) {
  2732. const resources = this.appearance && this.appearance.dict.get("Resources");
  2733. if (!this.appearance || !(resources && resources.has("ExtGState"))) {
  2734. if (this.appearance) {
  2735. (0, _util.warn)("HighlightAnnotation - ignoring built-in appearance stream.");
  2736. }
  2737. const fillColor = this.color ? getPdfColorArray(this.color) : [1, 1, 0];
  2738. const fillAlpha = dict.get("CA");
  2739. this._setDefaultAppearance({
  2740. xref,
  2741. fillColor,
  2742. blendMode: "Multiply",
  2743. fillAlpha,
  2744. pointsCallback: (buffer, points) => {
  2745. 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");
  2746. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2747. }
  2748. });
  2749. }
  2750. } else {
  2751. this.data.hasPopup = false;
  2752. }
  2753. }
  2754. }
  2755. class UnderlineAnnotation extends MarkupAnnotation {
  2756. constructor(params) {
  2757. super(params);
  2758. const {
  2759. dict,
  2760. xref
  2761. } = params;
  2762. this.data.annotationType = _util.AnnotationType.UNDERLINE;
  2763. const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
  2764. if (quadPoints) {
  2765. if (!this.appearance) {
  2766. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2767. const strokeAlpha = dict.get("CA");
  2768. this._setDefaultAppearance({
  2769. xref,
  2770. extra: "[] 0 d 1 w",
  2771. strokeColor,
  2772. strokeAlpha,
  2773. pointsCallback: (buffer, points) => {
  2774. buffer.push(`${points[2].x} ${points[2].y} m`, `${points[3].x} ${points[3].y} l`, "S");
  2775. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2776. }
  2777. });
  2778. }
  2779. } else {
  2780. this.data.hasPopup = false;
  2781. }
  2782. }
  2783. }
  2784. class SquigglyAnnotation extends MarkupAnnotation {
  2785. constructor(params) {
  2786. super(params);
  2787. const {
  2788. dict,
  2789. xref
  2790. } = params;
  2791. this.data.annotationType = _util.AnnotationType.SQUIGGLY;
  2792. const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
  2793. if (quadPoints) {
  2794. if (!this.appearance) {
  2795. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2796. const strokeAlpha = dict.get("CA");
  2797. this._setDefaultAppearance({
  2798. xref,
  2799. extra: "[] 0 d 1 w",
  2800. strokeColor,
  2801. strokeAlpha,
  2802. pointsCallback: (buffer, points) => {
  2803. const dy = (points[0].y - points[2].y) / 6;
  2804. let shift = dy;
  2805. let x = points[2].x;
  2806. const y = points[2].y;
  2807. const xEnd = points[3].x;
  2808. buffer.push(`${x} ${y + shift} m`);
  2809. do {
  2810. x += 2;
  2811. shift = shift === 0 ? dy : 0;
  2812. buffer.push(`${x} ${y + shift} l`);
  2813. } while (x < xEnd);
  2814. buffer.push("S");
  2815. return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
  2816. }
  2817. });
  2818. }
  2819. } else {
  2820. this.data.hasPopup = false;
  2821. }
  2822. }
  2823. }
  2824. class StrikeOutAnnotation extends MarkupAnnotation {
  2825. constructor(params) {
  2826. super(params);
  2827. const {
  2828. dict,
  2829. xref
  2830. } = params;
  2831. this.data.annotationType = _util.AnnotationType.STRIKEOUT;
  2832. const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
  2833. if (quadPoints) {
  2834. if (!this.appearance) {
  2835. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  2836. const strokeAlpha = dict.get("CA");
  2837. this._setDefaultAppearance({
  2838. xref,
  2839. extra: "[] 0 d 1 w",
  2840. strokeColor,
  2841. strokeAlpha,
  2842. pointsCallback: (buffer, points) => {
  2843. 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");
  2844. return [points[0].x, points[1].x, points[3].y, points[1].y];
  2845. }
  2846. });
  2847. }
  2848. } else {
  2849. this.data.hasPopup = false;
  2850. }
  2851. }
  2852. }
  2853. class StampAnnotation extends MarkupAnnotation {
  2854. constructor(params) {
  2855. super(params);
  2856. this.data.annotationType = _util.AnnotationType.STAMP;
  2857. }
  2858. }
  2859. class FileAttachmentAnnotation extends MarkupAnnotation {
  2860. constructor(params) {
  2861. super(params);
  2862. const file = new _file_spec.FileSpec(params.dict.get("FS"), params.xref);
  2863. this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
  2864. this.data.file = file.serializable;
  2865. }
  2866. }