annotation.js 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import {
  16. AnnotationActionEventType,
  17. AnnotationBorderStyleType,
  18. AnnotationEditorType,
  19. AnnotationFieldFlag,
  20. AnnotationFlag,
  21. AnnotationReplyType,
  22. AnnotationType,
  23. assert,
  24. BASELINE_FACTOR,
  25. FeatureTest,
  26. getModificationDate,
  27. IDENTITY_MATRIX,
  28. LINE_DESCENT_FACTOR,
  29. LINE_FACTOR,
  30. OPS,
  31. RenderingIntentFlag,
  32. shadow,
  33. stringToPDFString,
  34. unreachable,
  35. Util,
  36. warn,
  37. } from "../shared/util.js";
  38. import {
  39. collectActions,
  40. escapeString,
  41. getInheritableProperty,
  42. getRotationMatrix,
  43. isAscii,
  44. numberToString,
  45. stringToUTF16String,
  46. } from "./core_utils.js";
  47. import {
  48. createDefaultAppearance,
  49. FakeUnicodeFont,
  50. getPdfColor,
  51. parseDefaultAppearance,
  52. } from "./default_appearance.js";
  53. import { Dict, isName, Name, Ref, RefSet } from "./primitives.js";
  54. import { writeDict, writeObject } from "./writer.js";
  55. import { BaseStream } from "./base_stream.js";
  56. import { bidi } from "./bidi.js";
  57. import { Catalog } from "./catalog.js";
  58. import { ColorSpace } from "./colorspace.js";
  59. import { FileSpec } from "./file_spec.js";
  60. import { ObjectLoader } from "./object_loader.js";
  61. import { OperatorList } from "./operator_list.js";
  62. import { StringStream } from "./stream.js";
  63. import { XFAFactory } from "./xfa/factory.js";
  64. class AnnotationFactory {
  65. /**
  66. * Create an `Annotation` object of the correct type for the given reference
  67. * to an annotation dictionary. This yields a promise that is resolved when
  68. * the `Annotation` object is constructed.
  69. *
  70. * @param {XRef} xref
  71. * @param {Object} ref
  72. * @param {PDFManager} pdfManager
  73. * @param {Object} idFactory
  74. * @param {boolean} collectFields
  75. * @returns {Promise} A promise that is resolved with an {Annotation}
  76. * instance.
  77. */
  78. static create(xref, ref, pdfManager, idFactory, collectFields) {
  79. return Promise.all([
  80. pdfManager.ensureCatalog("acroForm"),
  81. // Only necessary to prevent the `pdfManager.docBaseUrl`-getter, used
  82. // with certain Annotations, from throwing and thus breaking parsing:
  83. pdfManager.ensureCatalog("baseUrl"),
  84. // Only necessary in the `Catalog.parseDestDictionary`-method,
  85. // when parsing "GoToE" actions:
  86. pdfManager.ensureCatalog("attachments"),
  87. pdfManager.ensureDoc("xfaDatasets"),
  88. collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1,
  89. ]).then(([acroForm, baseUrl, attachments, xfaDatasets, pageIndex]) =>
  90. pdfManager.ensure(this, "_create", [
  91. xref,
  92. ref,
  93. pdfManager,
  94. idFactory,
  95. acroForm,
  96. attachments,
  97. xfaDatasets,
  98. collectFields,
  99. pageIndex,
  100. ])
  101. );
  102. }
  103. /**
  104. * @private
  105. */
  106. static _create(
  107. xref,
  108. ref,
  109. pdfManager,
  110. idFactory,
  111. acroForm,
  112. attachments = null,
  113. xfaDatasets,
  114. collectFields,
  115. pageIndex = -1
  116. ) {
  117. const dict = xref.fetchIfRef(ref);
  118. if (!(dict instanceof Dict)) {
  119. return undefined;
  120. }
  121. const id =
  122. ref instanceof Ref ? ref.toString() : `annot_${idFactory.createObjId()}`;
  123. // Determine the annotation's subtype.
  124. let subtype = dict.get("Subtype");
  125. subtype = subtype instanceof Name ? subtype.name : null;
  126. const acroFormDict = acroForm instanceof Dict ? acroForm : Dict.empty;
  127. // Return the right annotation object based on the subtype and field type.
  128. const parameters = {
  129. xref,
  130. ref,
  131. dict,
  132. subtype,
  133. id,
  134. pdfManager,
  135. acroForm: acroFormDict,
  136. attachments,
  137. xfaDatasets,
  138. collectFields,
  139. needAppearances:
  140. !collectFields && acroFormDict.get("NeedAppearances") === true,
  141. pageIndex,
  142. isOffscreenCanvasSupported:
  143. FeatureTest.isOffscreenCanvasSupported &&
  144. pdfManager.evaluatorOptions.isOffscreenCanvasSupported,
  145. };
  146. switch (subtype) {
  147. case "Link":
  148. return new LinkAnnotation(parameters);
  149. case "Text":
  150. return new TextAnnotation(parameters);
  151. case "Widget":
  152. let fieldType = getInheritableProperty({ dict, key: "FT" });
  153. fieldType = fieldType instanceof Name ? fieldType.name : null;
  154. switch (fieldType) {
  155. case "Tx":
  156. return new TextWidgetAnnotation(parameters);
  157. case "Btn":
  158. return new ButtonWidgetAnnotation(parameters);
  159. case "Ch":
  160. return new ChoiceWidgetAnnotation(parameters);
  161. case "Sig":
  162. return new SignatureWidgetAnnotation(parameters);
  163. }
  164. warn(
  165. `Unimplemented widget field type "${fieldType}", ` +
  166. "falling back to base field type."
  167. );
  168. return new WidgetAnnotation(parameters);
  169. case "Popup":
  170. return new PopupAnnotation(parameters);
  171. case "FreeText":
  172. return new FreeTextAnnotation(parameters);
  173. case "Line":
  174. return new LineAnnotation(parameters);
  175. case "Square":
  176. return new SquareAnnotation(parameters);
  177. case "Circle":
  178. return new CircleAnnotation(parameters);
  179. case "PolyLine":
  180. return new PolylineAnnotation(parameters);
  181. case "Polygon":
  182. return new PolygonAnnotation(parameters);
  183. case "Caret":
  184. return new CaretAnnotation(parameters);
  185. case "Ink":
  186. return new InkAnnotation(parameters);
  187. case "Highlight":
  188. return new HighlightAnnotation(parameters);
  189. case "Underline":
  190. return new UnderlineAnnotation(parameters);
  191. case "Squiggly":
  192. return new SquigglyAnnotation(parameters);
  193. case "StrikeOut":
  194. return new StrikeOutAnnotation(parameters);
  195. case "Stamp":
  196. return new StampAnnotation(parameters);
  197. case "FileAttachment":
  198. return new FileAttachmentAnnotation(parameters);
  199. default:
  200. if (!collectFields) {
  201. if (!subtype) {
  202. warn("Annotation is missing the required /Subtype.");
  203. } else {
  204. warn(
  205. `Unimplemented annotation type "${subtype}", ` +
  206. "falling back to base annotation."
  207. );
  208. }
  209. }
  210. return new Annotation(parameters);
  211. }
  212. }
  213. static async _getPageIndex(xref, ref, pdfManager) {
  214. try {
  215. const annotDict = await xref.fetchIfRefAsync(ref);
  216. if (!(annotDict instanceof Dict)) {
  217. return -1;
  218. }
  219. const pageRef = annotDict.getRaw("P");
  220. if (!(pageRef instanceof Ref)) {
  221. return -1;
  222. }
  223. const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [
  224. pageRef,
  225. ]);
  226. return pageIndex;
  227. } catch (ex) {
  228. warn(`_getPageIndex: "${ex}".`);
  229. return -1;
  230. }
  231. }
  232. static async saveNewAnnotations(evaluator, task, annotations) {
  233. const xref = evaluator.xref;
  234. let baseFontRef;
  235. const dependencies = [];
  236. const promises = [];
  237. for (const annotation of annotations) {
  238. switch (annotation.annotationType) {
  239. case AnnotationEditorType.FREETEXT:
  240. if (!baseFontRef) {
  241. const baseFont = new Dict(xref);
  242. baseFont.set("BaseFont", Name.get("Helvetica"));
  243. baseFont.set("Type", Name.get("Font"));
  244. baseFont.set("Subtype", Name.get("Type1"));
  245. baseFont.set("Encoding", Name.get("WinAnsiEncoding"));
  246. const buffer = [];
  247. baseFontRef = xref.getNewTemporaryRef();
  248. writeObject(baseFontRef, baseFont, buffer, null);
  249. dependencies.push({ ref: baseFontRef, data: buffer.join("") });
  250. }
  251. promises.push(
  252. FreeTextAnnotation.createNewAnnotation(
  253. xref,
  254. annotation,
  255. dependencies,
  256. { evaluator, task, baseFontRef }
  257. )
  258. );
  259. break;
  260. case AnnotationEditorType.INK:
  261. promises.push(
  262. InkAnnotation.createNewAnnotation(xref, annotation, dependencies)
  263. );
  264. }
  265. }
  266. return {
  267. annotations: await Promise.all(promises),
  268. dependencies,
  269. };
  270. }
  271. static async printNewAnnotations(evaluator, task, annotations) {
  272. if (!annotations) {
  273. return null;
  274. }
  275. const xref = evaluator.xref;
  276. const promises = [];
  277. const isOffscreenCanvasSupported =
  278. FeatureTest.isOffscreenCanvasSupported &&
  279. evaluator.options.isOffscreenCanvasSupported;
  280. for (const annotation of annotations) {
  281. switch (annotation.annotationType) {
  282. case AnnotationEditorType.FREETEXT:
  283. promises.push(
  284. FreeTextAnnotation.createNewPrintAnnotation(xref, annotation, {
  285. evaluator,
  286. task,
  287. isOffscreenCanvasSupported,
  288. })
  289. );
  290. break;
  291. case AnnotationEditorType.INK:
  292. promises.push(
  293. InkAnnotation.createNewPrintAnnotation(xref, annotation, {
  294. isOffscreenCanvasSupported,
  295. })
  296. );
  297. break;
  298. }
  299. }
  300. return Promise.all(promises);
  301. }
  302. }
  303. function getRgbColor(color, defaultColor = new Uint8ClampedArray(3)) {
  304. if (!Array.isArray(color)) {
  305. return defaultColor;
  306. }
  307. const rgbColor = defaultColor || new Uint8ClampedArray(3);
  308. switch (color.length) {
  309. case 0: // Transparent, which we indicate with a null value
  310. return null;
  311. case 1: // Convert grayscale to RGB
  312. ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
  313. return rgbColor;
  314. case 3: // Convert RGB percentages to RGB
  315. ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
  316. return rgbColor;
  317. case 4: // Convert CMYK to RGB
  318. ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
  319. return rgbColor;
  320. default:
  321. return defaultColor;
  322. }
  323. }
  324. function getPdfColorArray(color) {
  325. return Array.from(color, c => c / 255);
  326. }
  327. function getQuadPoints(dict, rect) {
  328. // The region is described as a number of quadrilaterals.
  329. // Each quadrilateral must consist of eight coordinates.
  330. const quadPoints = dict.getArray("QuadPoints");
  331. if (
  332. !Array.isArray(quadPoints) ||
  333. quadPoints.length === 0 ||
  334. quadPoints.length % 8 > 0
  335. ) {
  336. return null;
  337. }
  338. const quadPointsLists = [];
  339. for (let i = 0, ii = quadPoints.length / 8; i < ii; i++) {
  340. // Each series of eight numbers represents the coordinates for one
  341. // quadrilateral in the order [x1, y1, x2, y2, x3, y3, x4, y4].
  342. // Convert this to an array of objects with x and y coordinates.
  343. let minX = Infinity,
  344. maxX = -Infinity,
  345. minY = Infinity,
  346. maxY = -Infinity;
  347. for (let j = i * 8, jj = i * 8 + 8; j < jj; j += 2) {
  348. const x = quadPoints[j];
  349. const y = quadPoints[j + 1];
  350. minX = Math.min(x, minX);
  351. maxX = Math.max(x, maxX);
  352. minY = Math.min(y, minY);
  353. maxY = Math.max(y, maxY);
  354. }
  355. // The quadpoints should be ignored if any coordinate in the array
  356. // lies outside the region specified by the rectangle. The rectangle
  357. // can be `null` for markup annotations since their rectangle may be
  358. // incorrect (fixes bug 1538111).
  359. if (
  360. rect !== null &&
  361. (minX < rect[0] || maxX > rect[2] || minY < rect[1] || maxY > rect[3])
  362. ) {
  363. return null;
  364. }
  365. // The PDF specification states in section 12.5.6.10 (figure 64) that the
  366. // order of the quadpoints should be bottom left, bottom right, top right
  367. // and top left. However, in practice PDF files use a different order,
  368. // namely bottom left, bottom right, top left and top right (this is also
  369. // mentioned on https://github.com/highkite/pdfAnnotate#QuadPoints), so
  370. // this is the actual order we should work with. However, the situation is
  371. // even worse since Adobe's own applications and other applications violate
  372. // the specification and create annotations with other orders, namely top
  373. // left, top right, bottom left and bottom right or even top left,
  374. // top right, bottom right and bottom left. To avoid inconsistency and
  375. // broken rendering, we normalize all lists to put the quadpoints in the
  376. // same standard order (see https://stackoverflow.com/a/10729881).
  377. quadPointsLists.push([
  378. { x: minX, y: maxY },
  379. { x: maxX, y: maxY },
  380. { x: minX, y: minY },
  381. { x: maxX, y: minY },
  382. ]);
  383. }
  384. return quadPointsLists;
  385. }
  386. function getTransformMatrix(rect, bbox, matrix) {
  387. // 12.5.5: Algorithm: Appearance streams
  388. const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox(
  389. bbox,
  390. matrix
  391. );
  392. if (minX === maxX || minY === maxY) {
  393. // From real-life file, bbox was [0, 0, 0, 0]. In this case,
  394. // just apply the transform for rect
  395. return [1, 0, 0, 1, rect[0], rect[1]];
  396. }
  397. const xRatio = (rect[2] - rect[0]) / (maxX - minX);
  398. const yRatio = (rect[3] - rect[1]) / (maxY - minY);
  399. return [
  400. xRatio,
  401. 0,
  402. 0,
  403. yRatio,
  404. rect[0] - minX * xRatio,
  405. rect[1] - minY * yRatio,
  406. ];
  407. }
  408. class Annotation {
  409. constructor(params) {
  410. const { dict, xref } = params;
  411. this.setTitle(dict.get("T"));
  412. this.setContents(dict.get("Contents"));
  413. this.setModificationDate(dict.get("M"));
  414. this.setFlags(dict.get("F"));
  415. this.setRectangle(dict.getArray("Rect"));
  416. this.setColor(dict.getArray("C"));
  417. this.setBorderStyle(dict);
  418. this.setAppearance(dict);
  419. this.setOptionalContent(dict);
  420. const MK = dict.get("MK");
  421. this.setBorderAndBackgroundColors(MK);
  422. this.setRotation(MK);
  423. this._streams = [];
  424. if (this.appearance) {
  425. this._streams.push(this.appearance);
  426. }
  427. // Expose public properties using a data object.
  428. this.data = {
  429. annotationFlags: this.flags,
  430. borderStyle: this.borderStyle,
  431. color: this.color,
  432. backgroundColor: this.backgroundColor,
  433. borderColor: this.borderColor,
  434. rotation: this.rotation,
  435. contentsObj: this._contents,
  436. hasAppearance: !!this.appearance,
  437. id: params.id,
  438. modificationDate: this.modificationDate,
  439. rect: this.rectangle,
  440. subtype: params.subtype,
  441. hasOwnCanvas: false,
  442. };
  443. if (params.collectFields) {
  444. // Fields can act as container for other fields and have
  445. // some actions even if no Annotation inherit from them.
  446. // Those fields can be referenced by CO (calculation order).
  447. const kids = dict.get("Kids");
  448. if (Array.isArray(kids)) {
  449. const kidIds = [];
  450. for (const kid of kids) {
  451. if (kid instanceof Ref) {
  452. kidIds.push(kid.toString());
  453. }
  454. }
  455. if (kidIds.length !== 0) {
  456. this.data.kidIds = kidIds;
  457. }
  458. }
  459. this.data.actions = collectActions(xref, dict, AnnotationActionEventType);
  460. this.data.fieldName = this._constructFieldName(dict);
  461. this.data.pageIndex = params.pageIndex;
  462. }
  463. this._isOffscreenCanvasSupported = params.isOffscreenCanvasSupported;
  464. this._fallbackFontDict = null;
  465. this._needAppearances = false;
  466. }
  467. /**
  468. * @private
  469. */
  470. _hasFlag(flags, flag) {
  471. return !!(flags & flag);
  472. }
  473. /**
  474. * @private
  475. */
  476. _isViewable(flags) {
  477. return (
  478. !this._hasFlag(flags, AnnotationFlag.INVISIBLE) &&
  479. !this._hasFlag(flags, AnnotationFlag.NOVIEW)
  480. );
  481. }
  482. /**
  483. * @private
  484. */
  485. _isPrintable(flags) {
  486. return (
  487. this._hasFlag(flags, AnnotationFlag.PRINT) &&
  488. !this._hasFlag(flags, AnnotationFlag.INVISIBLE)
  489. );
  490. }
  491. /**
  492. * Check if the annotation must be displayed by taking into account
  493. * the value found in the annotationStorage which may have been set
  494. * through JS.
  495. *
  496. * @public
  497. * @memberof Annotation
  498. * @param {AnnotationStorage} [annotationStorage] - Storage for annotation
  499. */
  500. mustBeViewed(annotationStorage) {
  501. const storageEntry =
  502. annotationStorage && annotationStorage.get(this.data.id);
  503. if (storageEntry && storageEntry.hidden !== undefined) {
  504. return !storageEntry.hidden;
  505. }
  506. return this.viewable && !this._hasFlag(this.flags, AnnotationFlag.HIDDEN);
  507. }
  508. /**
  509. * Check if the annotation must be printed by taking into account
  510. * the value found in the annotationStorage which may have been set
  511. * through JS.
  512. *
  513. * @public
  514. * @memberof Annotation
  515. * @param {AnnotationStorage} [annotationStorage] - Storage for annotation
  516. */
  517. mustBePrinted(annotationStorage) {
  518. const storageEntry =
  519. annotationStorage && annotationStorage.get(this.data.id);
  520. if (storageEntry && storageEntry.print !== undefined) {
  521. return storageEntry.print;
  522. }
  523. return this.printable;
  524. }
  525. /**
  526. * @type {boolean}
  527. */
  528. get viewable() {
  529. if (this.data.quadPoints === null) {
  530. return false;
  531. }
  532. if (this.flags === 0) {
  533. return true;
  534. }
  535. return this._isViewable(this.flags);
  536. }
  537. /**
  538. * @type {boolean}
  539. */
  540. get printable() {
  541. if (this.data.quadPoints === null) {
  542. return false;
  543. }
  544. if (this.flags === 0) {
  545. return false;
  546. }
  547. return this._isPrintable(this.flags);
  548. }
  549. /**
  550. * @private
  551. */
  552. _parseStringHelper(data) {
  553. const str = typeof data === "string" ? stringToPDFString(data) : "";
  554. const dir = str && bidi(str).dir === "rtl" ? "rtl" : "ltr";
  555. return { str, dir };
  556. }
  557. setDefaultAppearance(params) {
  558. const defaultAppearance =
  559. getInheritableProperty({ dict: params.dict, key: "DA" }) ||
  560. params.acroForm.get("DA");
  561. this._defaultAppearance =
  562. typeof defaultAppearance === "string" ? defaultAppearance : "";
  563. this.data.defaultAppearanceData = parseDefaultAppearance(
  564. this._defaultAppearance
  565. );
  566. }
  567. /**
  568. * Set the title.
  569. *
  570. * @param {string} title - The title of the annotation, used e.g. with
  571. * PopupAnnotations.
  572. */
  573. setTitle(title) {
  574. this._title = this._parseStringHelper(title);
  575. }
  576. /**
  577. * Set the contents.
  578. *
  579. * @param {string} contents - Text to display for the annotation or, if the
  580. * type of annotation does not display text, a
  581. * description of the annotation's contents
  582. */
  583. setContents(contents) {
  584. this._contents = this._parseStringHelper(contents);
  585. }
  586. /**
  587. * Set the modification date.
  588. *
  589. * @public
  590. * @memberof Annotation
  591. * @param {string} modificationDate - PDF date string that indicates when the
  592. * annotation was last modified
  593. */
  594. setModificationDate(modificationDate) {
  595. this.modificationDate =
  596. typeof modificationDate === "string" ? modificationDate : null;
  597. }
  598. /**
  599. * Set the flags.
  600. *
  601. * @public
  602. * @memberof Annotation
  603. * @param {number} flags - Unsigned 32-bit integer specifying annotation
  604. * characteristics
  605. * @see {@link shared/util.js}
  606. */
  607. setFlags(flags) {
  608. this.flags = Number.isInteger(flags) && flags > 0 ? flags : 0;
  609. }
  610. /**
  611. * Check if a provided flag is set.
  612. *
  613. * @public
  614. * @memberof Annotation
  615. * @param {number} flag - Hexadecimal representation for an annotation
  616. * characteristic
  617. * @returns {boolean}
  618. * @see {@link shared/util.js}
  619. */
  620. hasFlag(flag) {
  621. return this._hasFlag(this.flags, flag);
  622. }
  623. /**
  624. * Set the rectangle.
  625. *
  626. * @public
  627. * @memberof Annotation
  628. * @param {Array} rectangle - The rectangle array with exactly four entries
  629. */
  630. setRectangle(rectangle) {
  631. if (Array.isArray(rectangle) && rectangle.length === 4) {
  632. this.rectangle = Util.normalizeRect(rectangle);
  633. } else {
  634. this.rectangle = [0, 0, 0, 0];
  635. }
  636. }
  637. /**
  638. * Set the color and take care of color space conversion.
  639. * The default value is black, in RGB color space.
  640. *
  641. * @public
  642. * @memberof Annotation
  643. * @param {Array} color - The color array containing either 0
  644. * (transparent), 1 (grayscale), 3 (RGB) or
  645. * 4 (CMYK) elements
  646. */
  647. setColor(color) {
  648. this.color = getRgbColor(color);
  649. }
  650. /**
  651. * Set the line endings; should only be used with specific annotation types.
  652. * @param {Array} lineEndings - The line endings array.
  653. */
  654. setLineEndings(lineEndings) {
  655. this.lineEndings = ["None", "None"]; // The default values.
  656. if (Array.isArray(lineEndings) && lineEndings.length === 2) {
  657. for (let i = 0; i < 2; i++) {
  658. const obj = lineEndings[i];
  659. if (obj instanceof Name) {
  660. switch (obj.name) {
  661. case "None":
  662. continue;
  663. case "Square":
  664. case "Circle":
  665. case "Diamond":
  666. case "OpenArrow":
  667. case "ClosedArrow":
  668. case "Butt":
  669. case "ROpenArrow":
  670. case "RClosedArrow":
  671. case "Slash":
  672. this.lineEndings[i] = obj.name;
  673. continue;
  674. }
  675. }
  676. warn(`Ignoring invalid lineEnding: ${obj}`);
  677. }
  678. }
  679. }
  680. setRotation(mk) {
  681. this.rotation = 0;
  682. if (mk instanceof Dict) {
  683. let angle = mk.get("R") || 0;
  684. if (Number.isInteger(angle) && angle !== 0) {
  685. angle %= 360;
  686. if (angle < 0) {
  687. angle += 360;
  688. }
  689. if (angle % 90 === 0) {
  690. this.rotation = angle;
  691. }
  692. }
  693. }
  694. }
  695. /**
  696. * Set the color for background and border if any.
  697. * The default values are transparent.
  698. *
  699. * @public
  700. * @memberof Annotation
  701. * @param {Dict} mk - The MK dictionary
  702. */
  703. setBorderAndBackgroundColors(mk) {
  704. if (mk instanceof Dict) {
  705. this.borderColor = getRgbColor(mk.getArray("BC"), null);
  706. this.backgroundColor = getRgbColor(mk.getArray("BG"), null);
  707. } else {
  708. this.borderColor = this.backgroundColor = null;
  709. }
  710. }
  711. /**
  712. * Set the border style (as AnnotationBorderStyle object).
  713. *
  714. * @public
  715. * @memberof Annotation
  716. * @param {Dict} borderStyle - The border style dictionary
  717. */
  718. setBorderStyle(borderStyle) {
  719. if (
  720. typeof PDFJSDev === "undefined" ||
  721. PDFJSDev.test("!PRODUCTION || TESTING")
  722. ) {
  723. assert(this.rectangle, "setRectangle must have been called previously.");
  724. }
  725. this.borderStyle = new AnnotationBorderStyle();
  726. if (!(borderStyle instanceof Dict)) {
  727. return;
  728. }
  729. if (borderStyle.has("BS")) {
  730. const dict = borderStyle.get("BS");
  731. const dictType = dict.get("Type");
  732. if (!dictType || isName(dictType, "Border")) {
  733. this.borderStyle.setWidth(dict.get("W"), this.rectangle);
  734. this.borderStyle.setStyle(dict.get("S"));
  735. this.borderStyle.setDashArray(dict.getArray("D"));
  736. }
  737. } else if (borderStyle.has("Border")) {
  738. const array = borderStyle.getArray("Border");
  739. if (Array.isArray(array) && array.length >= 3) {
  740. this.borderStyle.setHorizontalCornerRadius(array[0]);
  741. this.borderStyle.setVerticalCornerRadius(array[1]);
  742. this.borderStyle.setWidth(array[2], this.rectangle);
  743. if (array.length === 4) {
  744. // Dash array available
  745. this.borderStyle.setDashArray(array[3], /* forceStyle = */ true);
  746. }
  747. }
  748. } else {
  749. // There are no border entries in the dictionary. According to the
  750. // specification, we should draw a solid border of width 1 in that
  751. // case, but Adobe Reader did not implement that part of the
  752. // specification and instead draws no border at all, so we do the same.
  753. // See also https://github.com/mozilla/pdf.js/issues/6179.
  754. this.borderStyle.setWidth(0);
  755. }
  756. }
  757. /**
  758. * Set the (normal) appearance.
  759. *
  760. * @public
  761. * @memberof Annotation
  762. * @param {Dict} dict - The annotation's data dictionary
  763. */
  764. setAppearance(dict) {
  765. this.appearance = null;
  766. const appearanceStates = dict.get("AP");
  767. if (!(appearanceStates instanceof Dict)) {
  768. return;
  769. }
  770. // In case the normal appearance is a stream, then it is used directly.
  771. const normalAppearanceState = appearanceStates.get("N");
  772. if (normalAppearanceState instanceof BaseStream) {
  773. this.appearance = normalAppearanceState;
  774. return;
  775. }
  776. if (!(normalAppearanceState instanceof Dict)) {
  777. return;
  778. }
  779. // In case the normal appearance is a dictionary, the `AS` entry provides
  780. // the key of the stream in this dictionary.
  781. const as = dict.get("AS");
  782. if (!(as instanceof Name) || !normalAppearanceState.has(as.name)) {
  783. return;
  784. }
  785. this.appearance = normalAppearanceState.get(as.name);
  786. }
  787. setOptionalContent(dict) {
  788. this.oc = null;
  789. const oc = dict.get("OC");
  790. if (oc instanceof Name) {
  791. warn("setOptionalContent: Support for /Name-entry is not implemented.");
  792. } else if (oc instanceof Dict) {
  793. this.oc = oc;
  794. }
  795. }
  796. loadResources(keys, appearance) {
  797. return appearance.dict.getAsync("Resources").then(resources => {
  798. if (!resources) {
  799. return undefined;
  800. }
  801. const objectLoader = new ObjectLoader(resources, keys, resources.xref);
  802. return objectLoader.load().then(function () {
  803. return resources;
  804. });
  805. });
  806. }
  807. async getOperatorList(
  808. evaluator,
  809. task,
  810. intent,
  811. renderForms,
  812. annotationStorage
  813. ) {
  814. const data = this.data;
  815. let appearance = this.appearance;
  816. const isUsingOwnCanvas = !!(
  817. this.data.hasOwnCanvas && intent & RenderingIntentFlag.DISPLAY
  818. );
  819. if (!appearance) {
  820. if (!isUsingOwnCanvas) {
  821. return {
  822. opList: new OperatorList(),
  823. separateForm: false,
  824. separateCanvas: false,
  825. };
  826. }
  827. appearance = new StringStream("");
  828. appearance.dict = new Dict();
  829. }
  830. const appearanceDict = appearance.dict;
  831. const resources = await this.loadResources(
  832. ["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"],
  833. appearance
  834. );
  835. const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];
  836. const matrix = appearanceDict.getArray("Matrix") || [1, 0, 0, 1, 0, 0];
  837. const transform = getTransformMatrix(data.rect, bbox, matrix);
  838. const opList = new OperatorList();
  839. let optionalContent;
  840. if (this.oc) {
  841. optionalContent = await evaluator.parseMarkedContentProps(
  842. this.oc,
  843. /* resources = */ null
  844. );
  845. }
  846. if (optionalContent !== undefined) {
  847. opList.addOp(OPS.beginMarkedContentProps, ["OC", optionalContent]);
  848. }
  849. opList.addOp(OPS.beginAnnotation, [
  850. data.id,
  851. data.rect,
  852. transform,
  853. matrix,
  854. isUsingOwnCanvas,
  855. ]);
  856. await evaluator.getOperatorList({
  857. stream: appearance,
  858. task,
  859. resources,
  860. operatorList: opList,
  861. fallbackFontDict: this._fallbackFontDict,
  862. });
  863. opList.addOp(OPS.endAnnotation, []);
  864. if (optionalContent !== undefined) {
  865. opList.addOp(OPS.endMarkedContent, []);
  866. }
  867. this.reset();
  868. return { opList, separateForm: false, separateCanvas: isUsingOwnCanvas };
  869. }
  870. async save(evaluator, task, annotationStorage) {
  871. return null;
  872. }
  873. get hasTextContent() {
  874. return false;
  875. }
  876. async extractTextContent(evaluator, task, viewBox) {
  877. if (!this.appearance) {
  878. return;
  879. }
  880. const resources = await this.loadResources(
  881. ["ExtGState", "Font", "Properties", "XObject"],
  882. this.appearance
  883. );
  884. const text = [];
  885. const buffer = [];
  886. const sink = {
  887. desiredSize: Math.Infinity,
  888. ready: true,
  889. enqueue(chunk, size) {
  890. for (const item of chunk.items) {
  891. buffer.push(item.str);
  892. if (item.hasEOL) {
  893. text.push(buffer.join(""));
  894. buffer.length = 0;
  895. }
  896. }
  897. },
  898. };
  899. await evaluator.getTextContent({
  900. stream: this.appearance,
  901. task,
  902. resources,
  903. includeMarkedContent: true,
  904. combineTextItems: true,
  905. sink,
  906. viewBox,
  907. });
  908. this.reset();
  909. if (buffer.length) {
  910. text.push(buffer.join(""));
  911. }
  912. if (text.length > 0) {
  913. this.data.textContent = text;
  914. }
  915. }
  916. /**
  917. * Get field data for usage in JS sandbox.
  918. *
  919. * Field object is defined here:
  920. * https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf#page=16
  921. *
  922. * @public
  923. * @memberof Annotation
  924. * @returns {Object | null}
  925. */
  926. getFieldObject() {
  927. if (this.data.kidIds) {
  928. return {
  929. id: this.data.id,
  930. actions: this.data.actions,
  931. name: this.data.fieldName,
  932. strokeColor: this.data.borderColor,
  933. fillColor: this.data.backgroundColor,
  934. type: "",
  935. kidIds: this.data.kidIds,
  936. page: this.data.pageIndex,
  937. rotation: this.rotation,
  938. };
  939. }
  940. return null;
  941. }
  942. /**
  943. * Reset the annotation.
  944. *
  945. * This involves resetting the various streams that are either cached on the
  946. * annotation instance or created during its construction.
  947. *
  948. * @public
  949. * @memberof Annotation
  950. */
  951. reset() {
  952. if (
  953. (typeof PDFJSDev === "undefined" ||
  954. PDFJSDev.test("!PRODUCTION || TESTING")) &&
  955. this.appearance &&
  956. !this._streams.includes(this.appearance)
  957. ) {
  958. unreachable("The appearance stream should always be reset.");
  959. }
  960. for (const stream of this._streams) {
  961. stream.reset();
  962. }
  963. }
  964. /**
  965. * Construct the (fully qualified) field name from the (partial) field
  966. * names of the field and its ancestors.
  967. *
  968. * @private
  969. * @memberof Annotation
  970. * @param {Dict} dict - Complete widget annotation dictionary
  971. * @returns {string}
  972. */
  973. _constructFieldName(dict) {
  974. // Both the `Parent` and `T` fields are optional. While at least one of
  975. // them should be provided, bad PDF generators may fail to do so.
  976. if (!dict.has("T") && !dict.has("Parent")) {
  977. warn("Unknown field name, falling back to empty field name.");
  978. return "";
  979. }
  980. // If no parent exists, the partial and fully qualified names are equal.
  981. if (!dict.has("Parent")) {
  982. return stringToPDFString(dict.get("T"));
  983. }
  984. // Form the fully qualified field name by appending the partial name to
  985. // the parent's fully qualified name, separated by a period.
  986. const fieldName = [];
  987. if (dict.has("T")) {
  988. fieldName.unshift(stringToPDFString(dict.get("T")));
  989. }
  990. let loopDict = dict;
  991. const visited = new RefSet();
  992. if (dict.objId) {
  993. visited.put(dict.objId);
  994. }
  995. while (loopDict.has("Parent")) {
  996. loopDict = loopDict.get("Parent");
  997. if (
  998. !(loopDict instanceof Dict) ||
  999. (loopDict.objId && visited.has(loopDict.objId))
  1000. ) {
  1001. // Even though it is not allowed according to the PDF specification,
  1002. // bad PDF generators may provide a `Parent` entry that is not a
  1003. // dictionary, but `null` for example (issue 8143).
  1004. //
  1005. // If parent has been already visited, it means that we're
  1006. // in an infinite loop.
  1007. break;
  1008. }
  1009. if (loopDict.objId) {
  1010. visited.put(loopDict.objId);
  1011. }
  1012. if (loopDict.has("T")) {
  1013. fieldName.unshift(stringToPDFString(loopDict.get("T")));
  1014. }
  1015. }
  1016. return fieldName.join(".");
  1017. }
  1018. }
  1019. /**
  1020. * Contains all data regarding an annotation's border style.
  1021. */
  1022. class AnnotationBorderStyle {
  1023. constructor() {
  1024. this.width = 1;
  1025. this.style = AnnotationBorderStyleType.SOLID;
  1026. this.dashArray = [3];
  1027. this.horizontalCornerRadius = 0;
  1028. this.verticalCornerRadius = 0;
  1029. }
  1030. /**
  1031. * Set the width.
  1032. *
  1033. * @public
  1034. * @memberof AnnotationBorderStyle
  1035. * @param {number} width - The width.
  1036. * @param {Array} rect - The annotation `Rect` entry.
  1037. */
  1038. setWidth(width, rect = [0, 0, 0, 0]) {
  1039. if (
  1040. typeof PDFJSDev === "undefined" ||
  1041. PDFJSDev.test("!PRODUCTION || TESTING")
  1042. ) {
  1043. assert(
  1044. Array.isArray(rect) && rect.length === 4,
  1045. "A valid `rect` parameter must be provided."
  1046. );
  1047. }
  1048. // Some corrupt PDF generators may provide the width as a `Name`,
  1049. // rather than as a number (fixes issue 10385).
  1050. if (width instanceof Name) {
  1051. this.width = 0; // This is consistent with the behaviour in Adobe Reader.
  1052. return;
  1053. }
  1054. if (typeof width === "number") {
  1055. if (width > 0) {
  1056. const maxWidth = (rect[2] - rect[0]) / 2;
  1057. const maxHeight = (rect[3] - rect[1]) / 2;
  1058. // Ignore large `width`s, since they lead to the Annotation overflowing
  1059. // the size set by the `Rect` entry thus causing the `annotationLayer`
  1060. // to render it over the surrounding document (fixes bug1552113.pdf).
  1061. if (
  1062. maxWidth > 0 &&
  1063. maxHeight > 0 &&
  1064. (width > maxWidth || width > maxHeight)
  1065. ) {
  1066. warn(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
  1067. width = 1;
  1068. }
  1069. }
  1070. this.width = width;
  1071. }
  1072. }
  1073. /**
  1074. * Set the style.
  1075. *
  1076. * @public
  1077. * @memberof AnnotationBorderStyle
  1078. * @param {Name} style - The annotation style.
  1079. * @see {@link shared/util.js}
  1080. */
  1081. setStyle(style) {
  1082. if (!(style instanceof Name)) {
  1083. return;
  1084. }
  1085. switch (style.name) {
  1086. case "S":
  1087. this.style = AnnotationBorderStyleType.SOLID;
  1088. break;
  1089. case "D":
  1090. this.style = AnnotationBorderStyleType.DASHED;
  1091. break;
  1092. case "B":
  1093. this.style = AnnotationBorderStyleType.BEVELED;
  1094. break;
  1095. case "I":
  1096. this.style = AnnotationBorderStyleType.INSET;
  1097. break;
  1098. case "U":
  1099. this.style = AnnotationBorderStyleType.UNDERLINE;
  1100. break;
  1101. default:
  1102. break;
  1103. }
  1104. }
  1105. /**
  1106. * Set the dash array.
  1107. *
  1108. * @public
  1109. * @memberof AnnotationBorderStyle
  1110. * @param {Array} dashArray - The dash array with at least one element
  1111. * @param {boolean} [forceStyle]
  1112. */
  1113. setDashArray(dashArray, forceStyle = false) {
  1114. // We validate the dash array, but we do not use it because CSS does not
  1115. // allow us to change spacing of dashes. For more information, visit
  1116. // http://www.w3.org/TR/css3-background/#the-border-style.
  1117. if (Array.isArray(dashArray) && dashArray.length > 0) {
  1118. // According to the PDF specification: the elements in `dashArray`
  1119. // shall be numbers that are nonnegative and not all equal to zero.
  1120. let isValid = true;
  1121. let allZeros = true;
  1122. for (const element of dashArray) {
  1123. const validNumber = +element >= 0;
  1124. if (!validNumber) {
  1125. isValid = false;
  1126. break;
  1127. } else if (element > 0) {
  1128. allZeros = false;
  1129. }
  1130. }
  1131. if (isValid && !allZeros) {
  1132. this.dashArray = dashArray;
  1133. if (forceStyle) {
  1134. // Even though we cannot use the dash array in the display layer,
  1135. // at least ensure that we use the correct border-style.
  1136. this.setStyle(Name.get("D"));
  1137. }
  1138. } else {
  1139. this.width = 0; // Adobe behavior when the array is invalid.
  1140. }
  1141. } else if (dashArray) {
  1142. this.width = 0; // Adobe behavior when the array is invalid.
  1143. }
  1144. }
  1145. /**
  1146. * Set the horizontal corner radius (from a Border dictionary).
  1147. *
  1148. * @public
  1149. * @memberof AnnotationBorderStyle
  1150. * @param {number} radius - The horizontal corner radius.
  1151. */
  1152. setHorizontalCornerRadius(radius) {
  1153. if (Number.isInteger(radius)) {
  1154. this.horizontalCornerRadius = radius;
  1155. }
  1156. }
  1157. /**
  1158. * Set the vertical corner radius (from a Border dictionary).
  1159. *
  1160. * @public
  1161. * @memberof AnnotationBorderStyle
  1162. * @param {number} radius - The vertical corner radius.
  1163. */
  1164. setVerticalCornerRadius(radius) {
  1165. if (Number.isInteger(radius)) {
  1166. this.verticalCornerRadius = radius;
  1167. }
  1168. }
  1169. }
  1170. class MarkupAnnotation extends Annotation {
  1171. constructor(params) {
  1172. super(params);
  1173. const { dict } = params;
  1174. if (dict.has("IRT")) {
  1175. const rawIRT = dict.getRaw("IRT");
  1176. this.data.inReplyTo = rawIRT instanceof Ref ? rawIRT.toString() : null;
  1177. const rt = dict.get("RT");
  1178. this.data.replyType =
  1179. rt instanceof Name ? rt.name : AnnotationReplyType.REPLY;
  1180. }
  1181. if (this.data.replyType === AnnotationReplyType.GROUP) {
  1182. // Subordinate annotations in a group should inherit
  1183. // the group attributes from the primary annotation.
  1184. const parent = dict.get("IRT");
  1185. this.setTitle(parent.get("T"));
  1186. this.data.titleObj = this._title;
  1187. this.setContents(parent.get("Contents"));
  1188. this.data.contentsObj = this._contents;
  1189. if (!parent.has("CreationDate")) {
  1190. this.data.creationDate = null;
  1191. } else {
  1192. this.setCreationDate(parent.get("CreationDate"));
  1193. this.data.creationDate = this.creationDate;
  1194. }
  1195. if (!parent.has("M")) {
  1196. this.data.modificationDate = null;
  1197. } else {
  1198. this.setModificationDate(parent.get("M"));
  1199. this.data.modificationDate = this.modificationDate;
  1200. }
  1201. this.data.hasPopup = parent.has("Popup");
  1202. if (!parent.has("C")) {
  1203. // Fall back to the default background color.
  1204. this.data.color = null;
  1205. } else {
  1206. this.setColor(parent.getArray("C"));
  1207. this.data.color = this.color;
  1208. }
  1209. } else {
  1210. this.data.titleObj = this._title;
  1211. this.setCreationDate(dict.get("CreationDate"));
  1212. this.data.creationDate = this.creationDate;
  1213. this.data.hasPopup = dict.has("Popup");
  1214. if (!dict.has("C")) {
  1215. // Fall back to the default background color.
  1216. this.data.color = null;
  1217. }
  1218. }
  1219. if (dict.has("RC")) {
  1220. this.data.richText = XFAFactory.getRichTextAsHtml(dict.get("RC"));
  1221. }
  1222. }
  1223. /**
  1224. * Set the creation date.
  1225. *
  1226. * @public
  1227. * @memberof MarkupAnnotation
  1228. * @param {string} creationDate - PDF date string that indicates when the
  1229. * annotation was originally created
  1230. */
  1231. setCreationDate(creationDate) {
  1232. this.creationDate = typeof creationDate === "string" ? creationDate : null;
  1233. }
  1234. _setDefaultAppearance({
  1235. xref,
  1236. extra,
  1237. strokeColor,
  1238. fillColor,
  1239. blendMode,
  1240. strokeAlpha,
  1241. fillAlpha,
  1242. pointsCallback,
  1243. }) {
  1244. let minX = Number.MAX_VALUE;
  1245. let minY = Number.MAX_VALUE;
  1246. let maxX = Number.MIN_VALUE;
  1247. let maxY = Number.MIN_VALUE;
  1248. const buffer = ["q"];
  1249. if (extra) {
  1250. buffer.push(extra);
  1251. }
  1252. if (strokeColor) {
  1253. buffer.push(`${strokeColor[0]} ${strokeColor[1]} ${strokeColor[2]} RG`);
  1254. }
  1255. if (fillColor) {
  1256. buffer.push(`${fillColor[0]} ${fillColor[1]} ${fillColor[2]} rg`);
  1257. }
  1258. let pointsArray = this.data.quadPoints;
  1259. if (!pointsArray) {
  1260. // If there are no quadpoints, the rectangle should be used instead.
  1261. // Convert the rectangle definition to a points array similar to how the
  1262. // quadpoints are defined.
  1263. pointsArray = [
  1264. [
  1265. { x: this.rectangle[0], y: this.rectangle[3] },
  1266. { x: this.rectangle[2], y: this.rectangle[3] },
  1267. { x: this.rectangle[0], y: this.rectangle[1] },
  1268. { x: this.rectangle[2], y: this.rectangle[1] },
  1269. ],
  1270. ];
  1271. }
  1272. for (const points of pointsArray) {
  1273. const [mX, MX, mY, MY] = pointsCallback(buffer, points);
  1274. minX = Math.min(minX, mX);
  1275. maxX = Math.max(maxX, MX);
  1276. minY = Math.min(minY, mY);
  1277. maxY = Math.max(maxY, MY);
  1278. }
  1279. buffer.push("Q");
  1280. const formDict = new Dict(xref);
  1281. const appearanceStreamDict = new Dict(xref);
  1282. appearanceStreamDict.set("Subtype", Name.get("Form"));
  1283. const appearanceStream = new StringStream(buffer.join(" "));
  1284. appearanceStream.dict = appearanceStreamDict;
  1285. formDict.set("Fm0", appearanceStream);
  1286. const gsDict = new Dict(xref);
  1287. if (blendMode) {
  1288. gsDict.set("BM", Name.get(blendMode));
  1289. }
  1290. if (typeof strokeAlpha === "number") {
  1291. gsDict.set("CA", strokeAlpha);
  1292. }
  1293. if (typeof fillAlpha === "number") {
  1294. gsDict.set("ca", fillAlpha);
  1295. }
  1296. const stateDict = new Dict(xref);
  1297. stateDict.set("GS0", gsDict);
  1298. const resources = new Dict(xref);
  1299. resources.set("ExtGState", stateDict);
  1300. resources.set("XObject", formDict);
  1301. const appearanceDict = new Dict(xref);
  1302. appearanceDict.set("Resources", resources);
  1303. const bbox = (this.data.rect = [minX, minY, maxX, maxY]);
  1304. appearanceDict.set("BBox", bbox);
  1305. this.appearance = new StringStream("/GS0 gs /Fm0 Do");
  1306. this.appearance.dict = appearanceDict;
  1307. // This method is only called if there is no appearance for the annotation,
  1308. // so `this.appearance` is not pushed yet in the `Annotation` constructor.
  1309. this._streams.push(this.appearance, appearanceStream);
  1310. }
  1311. static async createNewAnnotation(xref, annotation, dependencies, params) {
  1312. const annotationRef = xref.getNewTemporaryRef();
  1313. const ap = await this.createNewAppearanceStream(annotation, xref, params);
  1314. const buffer = [];
  1315. let annotationDict;
  1316. if (ap) {
  1317. const apRef = xref.getNewTemporaryRef();
  1318. annotationDict = this.createNewDict(annotation, xref, { apRef });
  1319. const transform = xref.encrypt
  1320. ? xref.encrypt.createCipherTransform(apRef.num, apRef.gen)
  1321. : null;
  1322. writeObject(apRef, ap, buffer, transform);
  1323. dependencies.push({ ref: apRef, data: buffer.join("") });
  1324. } else {
  1325. annotationDict = this.createNewDict(annotation, xref, {});
  1326. }
  1327. buffer.length = 0;
  1328. const transform = xref.encrypt
  1329. ? xref.encrypt.createCipherTransform(annotationRef.num, annotationRef.gen)
  1330. : null;
  1331. writeObject(annotationRef, annotationDict, buffer, transform);
  1332. return { ref: annotationRef, data: buffer.join("") };
  1333. }
  1334. static async createNewPrintAnnotation(xref, annotation, params) {
  1335. const ap = await this.createNewAppearanceStream(annotation, xref, params);
  1336. const annotationDict = this.createNewDict(annotation, xref, { ap });
  1337. return new this.prototype.constructor({
  1338. dict: annotationDict,
  1339. xref,
  1340. isOffscreenCanvasSupported: params.isOffscreenCanvasSupported,
  1341. });
  1342. }
  1343. }
  1344. class WidgetAnnotation extends Annotation {
  1345. constructor(params) {
  1346. super(params);
  1347. const { dict, xref } = params;
  1348. const data = this.data;
  1349. this.ref = params.ref;
  1350. this._needAppearances = params.needAppearances;
  1351. data.annotationType = AnnotationType.WIDGET;
  1352. if (data.fieldName === undefined) {
  1353. data.fieldName = this._constructFieldName(dict);
  1354. }
  1355. if (data.actions === undefined) {
  1356. data.actions = collectActions(xref, dict, AnnotationActionEventType);
  1357. }
  1358. let fieldValue = getInheritableProperty({
  1359. dict,
  1360. key: "V",
  1361. getArray: true,
  1362. });
  1363. data.fieldValue = this._decodeFormValue(fieldValue);
  1364. const defaultFieldValue = getInheritableProperty({
  1365. dict,
  1366. key: "DV",
  1367. getArray: true,
  1368. });
  1369. data.defaultFieldValue = this._decodeFormValue(defaultFieldValue);
  1370. if (fieldValue === undefined && params.xfaDatasets) {
  1371. // Try to figure out if we have something in the xfa dataset.
  1372. const path = this._title.str;
  1373. if (path) {
  1374. this._hasValueFromXFA = true;
  1375. data.fieldValue = fieldValue = params.xfaDatasets.getValue(path);
  1376. }
  1377. }
  1378. // When no "V" entry exists, let the fieldValue fallback to the "DV" entry
  1379. // (fixes issue13823.pdf).
  1380. if (fieldValue === undefined && data.defaultFieldValue !== null) {
  1381. data.fieldValue = data.defaultFieldValue;
  1382. }
  1383. data.alternativeText = stringToPDFString(dict.get("TU") || "");
  1384. this.setDefaultAppearance(params);
  1385. data.hasAppearance =
  1386. (this._needAppearances &&
  1387. data.fieldValue !== undefined &&
  1388. data.fieldValue !== null) ||
  1389. data.hasAppearance;
  1390. const fieldType = getInheritableProperty({ dict, key: "FT" });
  1391. data.fieldType = fieldType instanceof Name ? fieldType.name : null;
  1392. const localResources = getInheritableProperty({ dict, key: "DR" });
  1393. const acroFormResources = params.acroForm.get("DR");
  1394. const appearanceResources =
  1395. this.appearance && this.appearance.dict.get("Resources");
  1396. this._fieldResources = {
  1397. localResources,
  1398. acroFormResources,
  1399. appearanceResources,
  1400. mergedResources: Dict.merge({
  1401. xref,
  1402. dictArray: [localResources, appearanceResources, acroFormResources],
  1403. mergeSubDicts: true,
  1404. }),
  1405. };
  1406. data.fieldFlags = getInheritableProperty({ dict, key: "Ff" });
  1407. if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
  1408. data.fieldFlags = 0;
  1409. }
  1410. data.readOnly = this.hasFieldFlag(AnnotationFieldFlag.READONLY);
  1411. data.required = this.hasFieldFlag(AnnotationFieldFlag.REQUIRED);
  1412. data.hidden = this._hasFlag(data.annotationFlags, AnnotationFlag.HIDDEN);
  1413. }
  1414. /**
  1415. * Decode the given form value.
  1416. *
  1417. * @private
  1418. * @memberof WidgetAnnotation
  1419. * @param {Array<string>|Name|string} formValue - The (possibly encoded)
  1420. * form value.
  1421. * @returns {Array<string>|string|null}
  1422. */
  1423. _decodeFormValue(formValue) {
  1424. if (Array.isArray(formValue)) {
  1425. return formValue
  1426. .filter(item => typeof item === "string")
  1427. .map(item => stringToPDFString(item));
  1428. } else if (formValue instanceof Name) {
  1429. return stringToPDFString(formValue.name);
  1430. } else if (typeof formValue === "string") {
  1431. return stringToPDFString(formValue);
  1432. }
  1433. return null;
  1434. }
  1435. /**
  1436. * Check if a provided field flag is set.
  1437. *
  1438. * @public
  1439. * @memberof WidgetAnnotation
  1440. * @param {number} flag - Hexadecimal representation for an annotation
  1441. * field characteristic
  1442. * @returns {boolean}
  1443. * @see {@link shared/util.js}
  1444. */
  1445. hasFieldFlag(flag) {
  1446. return !!(this.data.fieldFlags & flag);
  1447. }
  1448. getRotationMatrix(annotationStorage) {
  1449. const storageEntry = annotationStorage
  1450. ? annotationStorage.get(this.data.id)
  1451. : undefined;
  1452. let rotation = storageEntry && storageEntry.rotation;
  1453. if (rotation === undefined) {
  1454. rotation = this.rotation;
  1455. }
  1456. if (rotation === 0) {
  1457. return IDENTITY_MATRIX;
  1458. }
  1459. const width = this.data.rect[2] - this.data.rect[0];
  1460. const height = this.data.rect[3] - this.data.rect[1];
  1461. return getRotationMatrix(rotation, width, height);
  1462. }
  1463. getBorderAndBackgroundAppearances(annotationStorage) {
  1464. const storageEntry = annotationStorage
  1465. ? annotationStorage.get(this.data.id)
  1466. : undefined;
  1467. let rotation = storageEntry && storageEntry.rotation;
  1468. if (rotation === undefined) {
  1469. rotation = this.rotation;
  1470. }
  1471. if (!this.backgroundColor && !this.borderColor) {
  1472. return "";
  1473. }
  1474. const width = this.data.rect[2] - this.data.rect[0];
  1475. const height = this.data.rect[3] - this.data.rect[1];
  1476. const rect =
  1477. rotation === 0 || rotation === 180
  1478. ? `0 0 ${width} ${height} re`
  1479. : `0 0 ${height} ${width} re`;
  1480. let str = "";
  1481. if (this.backgroundColor) {
  1482. str = `${getPdfColor(
  1483. this.backgroundColor,
  1484. /* isFill */ true
  1485. )} ${rect} f `;
  1486. }
  1487. if (this.borderColor) {
  1488. const borderWidth = this.borderStyle.width || 1;
  1489. str += `${borderWidth} w ${getPdfColor(
  1490. this.borderColor,
  1491. /* isFill */ false
  1492. )} ${rect} S `;
  1493. }
  1494. return str;
  1495. }
  1496. async getOperatorList(
  1497. evaluator,
  1498. task,
  1499. intent,
  1500. renderForms,
  1501. annotationStorage
  1502. ) {
  1503. // Do not render form elements on the canvas when interactive forms are
  1504. // enabled. The display layer is responsible for rendering them instead.
  1505. if (renderForms && !(this instanceof SignatureWidgetAnnotation)) {
  1506. return {
  1507. opList: new OperatorList(),
  1508. separateForm: true,
  1509. separateCanvas: false,
  1510. };
  1511. }
  1512. if (!this._hasText) {
  1513. return super.getOperatorList(
  1514. evaluator,
  1515. task,
  1516. intent,
  1517. renderForms,
  1518. annotationStorage
  1519. );
  1520. }
  1521. const content = await this._getAppearance(
  1522. evaluator,
  1523. task,
  1524. intent,
  1525. annotationStorage
  1526. );
  1527. if (this.appearance && content === null) {
  1528. return super.getOperatorList(
  1529. evaluator,
  1530. task,
  1531. intent,
  1532. renderForms,
  1533. annotationStorage
  1534. );
  1535. }
  1536. const opList = new OperatorList();
  1537. // Even if there is an appearance stream, ignore it. This is the
  1538. // behaviour used by Adobe Reader.
  1539. if (!this._defaultAppearance || content === null) {
  1540. return { opList, separateForm: false, separateCanvas: false };
  1541. }
  1542. const matrix = [1, 0, 0, 1, 0, 0];
  1543. const bbox = [
  1544. 0,
  1545. 0,
  1546. this.data.rect[2] - this.data.rect[0],
  1547. this.data.rect[3] - this.data.rect[1],
  1548. ];
  1549. const transform = getTransformMatrix(this.data.rect, bbox, matrix);
  1550. let optionalContent;
  1551. if (this.oc) {
  1552. optionalContent = await evaluator.parseMarkedContentProps(
  1553. this.oc,
  1554. /* resources = */ null
  1555. );
  1556. }
  1557. if (optionalContent !== undefined) {
  1558. opList.addOp(OPS.beginMarkedContentProps, ["OC", optionalContent]);
  1559. }
  1560. opList.addOp(OPS.beginAnnotation, [
  1561. this.data.id,
  1562. this.data.rect,
  1563. transform,
  1564. this.getRotationMatrix(annotationStorage),
  1565. /* isUsingOwnCanvas = */ false,
  1566. ]);
  1567. const stream = new StringStream(content);
  1568. await evaluator.getOperatorList({
  1569. stream,
  1570. task,
  1571. resources: this._fieldResources.mergedResources,
  1572. operatorList: opList,
  1573. });
  1574. opList.addOp(OPS.endAnnotation, []);
  1575. if (optionalContent !== undefined) {
  1576. opList.addOp(OPS.endMarkedContent, []);
  1577. }
  1578. return { opList, separateForm: false, separateCanvas: false };
  1579. }
  1580. _getMKDict(rotation) {
  1581. const mk = new Dict(null);
  1582. if (rotation) {
  1583. mk.set("R", rotation);
  1584. }
  1585. if (this.borderColor) {
  1586. mk.set("BC", getPdfColorArray(this.borderColor));
  1587. }
  1588. if (this.backgroundColor) {
  1589. mk.set("BG", getPdfColorArray(this.backgroundColor));
  1590. }
  1591. return mk.size > 0 ? mk : null;
  1592. }
  1593. async save(evaluator, task, annotationStorage) {
  1594. const storageEntry = annotationStorage
  1595. ? annotationStorage.get(this.data.id)
  1596. : undefined;
  1597. let value = storageEntry && storageEntry.value;
  1598. let rotation = storageEntry && storageEntry.rotation;
  1599. if (value === this.data.fieldValue || value === undefined) {
  1600. if (!this._hasValueFromXFA && rotation === undefined) {
  1601. return null;
  1602. }
  1603. value = value || this.data.fieldValue;
  1604. }
  1605. // Value can be an array (with choice list and multiple selections)
  1606. if (
  1607. rotation === undefined &&
  1608. !this._hasValueFromXFA &&
  1609. Array.isArray(value) &&
  1610. Array.isArray(this.data.fieldValue) &&
  1611. value.length === this.data.fieldValue.length &&
  1612. value.every((x, i) => x === this.data.fieldValue[i])
  1613. ) {
  1614. return null;
  1615. }
  1616. if (rotation === undefined) {
  1617. rotation = this.rotation;
  1618. }
  1619. let appearance = null;
  1620. if (!this._needAppearances) {
  1621. appearance = await this._getAppearance(
  1622. evaluator,
  1623. task,
  1624. RenderingIntentFlag.SAVE,
  1625. annotationStorage
  1626. );
  1627. if (appearance === null) {
  1628. // Appearance didn't change.
  1629. return null;
  1630. }
  1631. } else {
  1632. // No need to create an appearance: the pdf has the flag /NeedAppearances
  1633. // which means that it's up to the reader to produce an appearance.
  1634. }
  1635. let needAppearances = false;
  1636. if (appearance && appearance.needAppearances) {
  1637. needAppearances = true;
  1638. appearance = null;
  1639. }
  1640. const { xref } = evaluator;
  1641. const originalDict = xref.fetchIfRef(this.ref);
  1642. if (!(originalDict instanceof Dict)) {
  1643. return null;
  1644. }
  1645. const dict = new Dict(xref);
  1646. for (const key of originalDict.getKeys()) {
  1647. if (key !== "AP") {
  1648. dict.set(key, originalDict.getRaw(key));
  1649. }
  1650. }
  1651. const xfa = {
  1652. path: stringToPDFString(dict.get("T") || ""),
  1653. value,
  1654. };
  1655. const encoder = val => {
  1656. return isAscii(val)
  1657. ? val
  1658. : stringToUTF16String(val, /* bigEndian = */ true);
  1659. };
  1660. dict.set("V", Array.isArray(value) ? value.map(encoder) : encoder(value));
  1661. const maybeMK = this._getMKDict(rotation);
  1662. if (maybeMK) {
  1663. dict.set("MK", maybeMK);
  1664. }
  1665. const encrypt = xref.encrypt;
  1666. const originalTransform = encrypt
  1667. ? encrypt.createCipherTransform(this.ref.num, this.ref.gen)
  1668. : null;
  1669. const buffer = [];
  1670. const changes = [
  1671. // data for the original object
  1672. // V field changed + reference for new AP
  1673. { ref: this.ref, data: "", xfa, needAppearances },
  1674. ];
  1675. if (appearance !== null) {
  1676. const newRef = xref.getNewTemporaryRef();
  1677. const AP = new Dict(xref);
  1678. dict.set("AP", AP);
  1679. AP.set("N", newRef);
  1680. let newTransform = null;
  1681. if (encrypt) {
  1682. newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
  1683. appearance = newTransform.encryptString(appearance);
  1684. }
  1685. const resources = this._getSaveFieldResources(xref);
  1686. const appearanceStream = new StringStream(appearance);
  1687. const appearanceDict = (appearanceStream.dict = new Dict(xref));
  1688. appearanceDict.set("Length", appearance.length);
  1689. appearanceDict.set("Subtype", Name.get("Form"));
  1690. appearanceDict.set("Resources", resources);
  1691. appearanceDict.set("BBox", [
  1692. 0,
  1693. 0,
  1694. this.data.rect[2] - this.data.rect[0],
  1695. this.data.rect[3] - this.data.rect[1],
  1696. ]);
  1697. const rotationMatrix = this.getRotationMatrix(annotationStorage);
  1698. if (rotationMatrix !== IDENTITY_MATRIX) {
  1699. // The matrix isn't the identity one.
  1700. appearanceDict.set("Matrix", rotationMatrix);
  1701. }
  1702. writeObject(newRef, appearanceStream, buffer, newTransform);
  1703. changes.push(
  1704. // data for the new AP
  1705. {
  1706. ref: newRef,
  1707. data: buffer.join(""),
  1708. xfa: null,
  1709. needAppearances: false,
  1710. }
  1711. );
  1712. buffer.length = 0;
  1713. }
  1714. dict.set("M", `D:${getModificationDate()}`);
  1715. writeObject(this.ref, dict, buffer, originalTransform);
  1716. changes[0].data = buffer.join("");
  1717. return changes;
  1718. }
  1719. async _getAppearance(evaluator, task, intent, annotationStorage) {
  1720. const isPassword = this.hasFieldFlag(AnnotationFieldFlag.PASSWORD);
  1721. if (isPassword) {
  1722. return null;
  1723. }
  1724. const storageEntry = annotationStorage
  1725. ? annotationStorage.get(this.data.id)
  1726. : undefined;
  1727. let value, rotation;
  1728. if (storageEntry) {
  1729. value = storageEntry.formattedValue || storageEntry.value;
  1730. rotation = storageEntry.rotation;
  1731. }
  1732. if (
  1733. rotation === undefined &&
  1734. value === undefined &&
  1735. !this._needAppearances
  1736. ) {
  1737. if (!this._hasValueFromXFA || this.appearance) {
  1738. // The annotation hasn't been rendered so use the appearance.
  1739. return null;
  1740. }
  1741. }
  1742. // Empty or it has a trailing whitespace.
  1743. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  1744. if (value === undefined) {
  1745. // The annotation has its value in XFA datasets but not in the V field.
  1746. value = this.data.fieldValue;
  1747. if (!value) {
  1748. return `/Tx BMC q ${colors}Q EMC`;
  1749. }
  1750. }
  1751. if (Array.isArray(value) && value.length === 1) {
  1752. value = value[0];
  1753. }
  1754. assert(typeof value === "string", "Expected `value` to be a string.");
  1755. if (!this.data.combo) {
  1756. value = value.trim();
  1757. } else {
  1758. // The value is supposed to be one of the exportValue.
  1759. const option =
  1760. this.data.options.find(({ exportValue }) => value === exportValue) ||
  1761. this.data.options[0];
  1762. value = (option && option.displayValue) || "";
  1763. }
  1764. if (value === "") {
  1765. // the field is empty: nothing to render
  1766. return `/Tx BMC q ${colors}Q EMC`;
  1767. }
  1768. if (rotation === undefined) {
  1769. rotation = this.rotation;
  1770. }
  1771. let lineCount = -1;
  1772. let lines;
  1773. // We could have a text containing for example some sequences of chars and
  1774. // their diacritics (e.g. "é".normalize("NFKD") shows 1 char when it's 2).
  1775. // Positioning diacritics is really something we don't want to do here.
  1776. // So if a font has a glyph for a acute accent and one for "e" then we won't
  1777. // get any encoding issues but we'll render "e" and then "´".
  1778. // It's why we normalize the string. We use NFC to preserve the initial
  1779. // string, (e.g. "²".normalize("NFC") === "²"
  1780. // but "²".normalize("NFKC") === "2").
  1781. //
  1782. // TODO: it isn't a perfect solution, some chars like "ẹ́" will be
  1783. // decomposed into two chars ("ẹ" and "´"), so we should detect such
  1784. // situations and then use either FakeUnicodeFont or set the
  1785. // /NeedAppearances flag.
  1786. if (this.data.multiLine) {
  1787. lines = value.split(/\r\n?|\n/).map(line => line.normalize("NFC"));
  1788. lineCount = lines.length;
  1789. } else {
  1790. lines = [value.replace(/\r\n?|\n/, "").normalize("NFC")];
  1791. }
  1792. const defaultPadding = 1;
  1793. const defaultHPadding = 2;
  1794. let totalHeight = this.data.rect[3] - this.data.rect[1];
  1795. let totalWidth = this.data.rect[2] - this.data.rect[0];
  1796. if (rotation === 90 || rotation === 270) {
  1797. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  1798. }
  1799. if (!this._defaultAppearance) {
  1800. // The DA is required and must be a string.
  1801. // If there is no font named Helvetica in the resource dictionary,
  1802. // the evaluator will fall back to a default font.
  1803. // Doing so prevents exceptions and allows saving/printing
  1804. // the file as expected.
  1805. this.data.defaultAppearanceData = parseDefaultAppearance(
  1806. (this._defaultAppearance = "/Helvetica 0 Tf 0 g")
  1807. );
  1808. }
  1809. let font = await WidgetAnnotation._getFontData(
  1810. evaluator,
  1811. task,
  1812. this.data.defaultAppearanceData,
  1813. this._fieldResources.mergedResources
  1814. );
  1815. let defaultAppearance, fontSize, lineHeight;
  1816. const encodedLines = [];
  1817. let encodingError = false;
  1818. for (const line of lines) {
  1819. const encodedString = font.encodeString(line);
  1820. if (encodedString.length > 1) {
  1821. encodingError = true;
  1822. }
  1823. encodedLines.push(encodedString.join(""));
  1824. }
  1825. if (encodingError && intent & RenderingIntentFlag.SAVE) {
  1826. // We don't have a way to render the field, so we just rely on the
  1827. // /NeedAppearances trick to let the different sofware correctly render
  1828. // this pdf.
  1829. return { needAppearances: true };
  1830. }
  1831. // We check that the font is able to encode the string.
  1832. if (encodingError && this._isOffscreenCanvasSupported) {
  1833. // If it can't then we fallback on fake unicode font (mapped to sans-serif
  1834. // for the rendering).
  1835. // It means that a printed form can be rendered differently (it depends on
  1836. // the sans-serif font) but at least we've something to render.
  1837. // In an ideal world the associated font should correctly handle the
  1838. // possible chars but a user can add a smiley or whatever.
  1839. // We could try to embed a font but it means that we must have access
  1840. // to the raw font file.
  1841. const fontFamily = this.data.comb ? "monospace" : "sans-serif";
  1842. const fakeUnicodeFont = new FakeUnicodeFont(evaluator.xref, fontFamily);
  1843. const resources = fakeUnicodeFont.createFontResources(lines.join(""));
  1844. const newFont = resources.getRaw("Font");
  1845. if (this._fieldResources.mergedResources.has("Font")) {
  1846. const oldFont = this._fieldResources.mergedResources.get("Font");
  1847. for (const key of newFont.getKeys()) {
  1848. oldFont.set(key, newFont.getRaw(key));
  1849. }
  1850. } else {
  1851. this._fieldResources.mergedResources.set("Font", newFont);
  1852. }
  1853. const fontName = fakeUnicodeFont.fontName.name;
  1854. font = await WidgetAnnotation._getFontData(
  1855. evaluator,
  1856. task,
  1857. { fontName, fontSize: 0 },
  1858. resources
  1859. );
  1860. for (let i = 0, ii = encodedLines.length; i < ii; i++) {
  1861. encodedLines[i] = stringToUTF16String(lines[i]);
  1862. }
  1863. const savedDefaultAppearance = Object.assign(
  1864. Object.create(null),
  1865. this.data.defaultAppearanceData
  1866. );
  1867. this.data.defaultAppearanceData.fontSize = 0;
  1868. this.data.defaultAppearanceData.fontName = fontName;
  1869. [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(
  1870. totalHeight - 2 * defaultPadding,
  1871. totalWidth - 2 * defaultHPadding,
  1872. value,
  1873. font,
  1874. lineCount
  1875. );
  1876. this.data.defaultAppearanceData = savedDefaultAppearance;
  1877. } else {
  1878. if (!this._isOffscreenCanvasSupported) {
  1879. warn(
  1880. "_getAppearance: OffscreenCanvas is not supported, annotation may not render correctly."
  1881. );
  1882. }
  1883. [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(
  1884. totalHeight - 2 * defaultPadding,
  1885. totalWidth - 2 * defaultHPadding,
  1886. value,
  1887. font,
  1888. lineCount
  1889. );
  1890. }
  1891. let descent = font.descent;
  1892. if (isNaN(descent)) {
  1893. descent = BASELINE_FACTOR * lineHeight;
  1894. } else {
  1895. descent = Math.max(
  1896. BASELINE_FACTOR * lineHeight,
  1897. Math.abs(descent) * fontSize
  1898. );
  1899. }
  1900. // Take into account the space we have to compute the default vertical
  1901. // padding.
  1902. const defaultVPadding = Math.min(
  1903. Math.floor((totalHeight - fontSize) / 2),
  1904. defaultPadding
  1905. );
  1906. const alignment = this.data.textAlignment;
  1907. if (this.data.multiLine) {
  1908. return this._getMultilineAppearance(
  1909. defaultAppearance,
  1910. encodedLines,
  1911. font,
  1912. fontSize,
  1913. totalWidth,
  1914. totalHeight,
  1915. alignment,
  1916. defaultHPadding,
  1917. defaultVPadding,
  1918. descent,
  1919. lineHeight,
  1920. annotationStorage
  1921. );
  1922. }
  1923. if (this.data.comb) {
  1924. return this._getCombAppearance(
  1925. defaultAppearance,
  1926. font,
  1927. encodedLines[0],
  1928. fontSize,
  1929. totalWidth,
  1930. totalHeight,
  1931. defaultHPadding,
  1932. defaultVPadding,
  1933. descent,
  1934. lineHeight,
  1935. annotationStorage
  1936. );
  1937. }
  1938. const bottomPadding = defaultVPadding + descent;
  1939. if (alignment === 0 || alignment > 2) {
  1940. // Left alignment: nothing to do
  1941. return (
  1942. `/Tx BMC q ${colors}BT ` +
  1943. defaultAppearance +
  1944. ` 1 0 0 1 ${numberToString(defaultHPadding)} ${numberToString(
  1945. bottomPadding
  1946. )} Tm (${escapeString(encodedLines[0])}) Tj` +
  1947. " ET Q EMC"
  1948. );
  1949. }
  1950. const prevInfo = { shift: 0 };
  1951. const renderedText = this._renderText(
  1952. encodedLines[0],
  1953. font,
  1954. fontSize,
  1955. totalWidth,
  1956. alignment,
  1957. prevInfo,
  1958. defaultHPadding,
  1959. bottomPadding
  1960. );
  1961. return (
  1962. `/Tx BMC q ${colors}BT ` +
  1963. defaultAppearance +
  1964. ` 1 0 0 1 0 0 Tm ${renderedText}` +
  1965. " ET Q EMC"
  1966. );
  1967. }
  1968. static async _getFontData(evaluator, task, appearanceData, resources) {
  1969. const operatorList = new OperatorList();
  1970. const initialState = {
  1971. font: null,
  1972. clone() {
  1973. return this;
  1974. },
  1975. };
  1976. const { fontName, fontSize } = appearanceData;
  1977. await evaluator.handleSetFont(
  1978. resources,
  1979. [fontName && Name.get(fontName), fontSize],
  1980. /* fontRef = */ null,
  1981. operatorList,
  1982. task,
  1983. initialState,
  1984. /* fallbackFontDict = */ null
  1985. );
  1986. return initialState.font;
  1987. }
  1988. _getTextWidth(text, font) {
  1989. return (
  1990. font
  1991. .charsToGlyphs(text)
  1992. .reduce((width, glyph) => width + glyph.width, 0) / 1000
  1993. );
  1994. }
  1995. _computeFontSize(height, width, text, font, lineCount) {
  1996. let { fontSize } = this.data.defaultAppearanceData;
  1997. let lineHeight = (fontSize || 12) * LINE_FACTOR,
  1998. numberOfLines = Math.round(height / lineHeight);
  1999. if (!fontSize) {
  2000. // A zero value for size means that the font shall be auto-sized:
  2001. // its size shall be computed as a function of the height of the
  2002. // annotation rectangle (see 12.7.3.3).
  2003. const roundWithTwoDigits = x => Math.floor(x * 100) / 100;
  2004. if (lineCount === -1) {
  2005. const textWidth = this._getTextWidth(text, font);
  2006. fontSize = roundWithTwoDigits(
  2007. Math.min(
  2008. height / LINE_FACTOR,
  2009. textWidth > width ? width / textWidth : Infinity
  2010. )
  2011. );
  2012. numberOfLines = 1;
  2013. } else {
  2014. const lines = text.split(/\r\n?|\n/);
  2015. const cachedLines = [];
  2016. for (const line of lines) {
  2017. const encoded = font.encodeString(line).join("");
  2018. const glyphs = font.charsToGlyphs(encoded);
  2019. const positions = font.getCharPositions(encoded);
  2020. cachedLines.push({
  2021. line: encoded,
  2022. glyphs,
  2023. positions,
  2024. });
  2025. }
  2026. const isTooBig = fsize => {
  2027. // Return true when the text doesn't fit the given height.
  2028. let totalHeight = 0;
  2029. for (const cache of cachedLines) {
  2030. const chunks = this._splitLine(null, font, fsize, width, cache);
  2031. totalHeight += chunks.length * fsize;
  2032. if (totalHeight > height) {
  2033. return true;
  2034. }
  2035. }
  2036. return false;
  2037. };
  2038. // Hard to guess how many lines there are.
  2039. // The field may have been sized to have 10 lines
  2040. // and the user entered only 1 so if we get font size from
  2041. // height and number of lines then we'll get something too big.
  2042. // So we compute a fake number of lines based on height and
  2043. // a font size equal to 12 (this is the default font size in
  2044. // Acrobat).
  2045. // Then we'll adjust font size to what we have really.
  2046. numberOfLines = Math.max(numberOfLines, lineCount);
  2047. while (true) {
  2048. lineHeight = height / numberOfLines;
  2049. fontSize = roundWithTwoDigits(lineHeight / LINE_FACTOR);
  2050. if (isTooBig(fontSize)) {
  2051. numberOfLines++;
  2052. continue;
  2053. }
  2054. break;
  2055. }
  2056. }
  2057. const { fontName, fontColor } = this.data.defaultAppearanceData;
  2058. this._defaultAppearance = createDefaultAppearance({
  2059. fontSize,
  2060. fontName,
  2061. fontColor,
  2062. });
  2063. }
  2064. return [this._defaultAppearance, fontSize, height / numberOfLines];
  2065. }
  2066. _renderText(
  2067. text,
  2068. font,
  2069. fontSize,
  2070. totalWidth,
  2071. alignment,
  2072. prevInfo,
  2073. hPadding,
  2074. vPadding
  2075. ) {
  2076. // TODO: we need to take into account (if possible) how the text
  2077. // is rendered. For example in arabic, the cumulated width of some
  2078. // glyphs isn't equal to the width of the rendered glyphs because
  2079. // of ligatures.
  2080. let shift;
  2081. if (alignment === 1) {
  2082. // Center
  2083. const width = this._getTextWidth(text, font) * fontSize;
  2084. shift = (totalWidth - width) / 2;
  2085. } else if (alignment === 2) {
  2086. // Right
  2087. const width = this._getTextWidth(text, font) * fontSize;
  2088. shift = totalWidth - width - hPadding;
  2089. } else {
  2090. shift = hPadding;
  2091. }
  2092. const shiftStr = numberToString(shift - prevInfo.shift);
  2093. prevInfo.shift = shift;
  2094. vPadding = numberToString(vPadding);
  2095. return `${shiftStr} ${vPadding} Td (${escapeString(text)}) Tj`;
  2096. }
  2097. /**
  2098. * @private
  2099. */
  2100. _getSaveFieldResources(xref) {
  2101. if (
  2102. typeof PDFJSDev === "undefined" ||
  2103. PDFJSDev.test("!PRODUCTION || TESTING")
  2104. ) {
  2105. assert(
  2106. this.data.defaultAppearanceData,
  2107. "Expected `_defaultAppearanceData` to have been set."
  2108. );
  2109. }
  2110. const { localResources, appearanceResources, acroFormResources } =
  2111. this._fieldResources;
  2112. const fontName =
  2113. this.data.defaultAppearanceData &&
  2114. this.data.defaultAppearanceData.fontName;
  2115. if (!fontName) {
  2116. return localResources || Dict.empty;
  2117. }
  2118. for (const resources of [localResources, appearanceResources]) {
  2119. if (resources instanceof Dict) {
  2120. const localFont = resources.get("Font");
  2121. if (localFont instanceof Dict && localFont.has(fontName)) {
  2122. return resources;
  2123. }
  2124. }
  2125. }
  2126. if (acroFormResources instanceof Dict) {
  2127. const acroFormFont = acroFormResources.get("Font");
  2128. if (acroFormFont instanceof Dict && acroFormFont.has(fontName)) {
  2129. const subFontDict = new Dict(xref);
  2130. subFontDict.set(fontName, acroFormFont.getRaw(fontName));
  2131. const subResourcesDict = new Dict(xref);
  2132. subResourcesDict.set("Font", subFontDict);
  2133. return Dict.merge({
  2134. xref,
  2135. dictArray: [subResourcesDict, localResources],
  2136. mergeSubDicts: true,
  2137. });
  2138. }
  2139. }
  2140. return localResources || Dict.empty;
  2141. }
  2142. getFieldObject() {
  2143. return null;
  2144. }
  2145. }
  2146. class TextWidgetAnnotation extends WidgetAnnotation {
  2147. constructor(params) {
  2148. super(params);
  2149. this._hasText = true;
  2150. const dict = params.dict;
  2151. // The field value is always a string.
  2152. if (typeof this.data.fieldValue !== "string") {
  2153. this.data.fieldValue = "";
  2154. }
  2155. // Determine the alignment of text in the field.
  2156. let alignment = getInheritableProperty({ dict, key: "Q" });
  2157. if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
  2158. alignment = null;
  2159. }
  2160. this.data.textAlignment = alignment;
  2161. // Determine the maximum length of text in the field.
  2162. let maximumLength = getInheritableProperty({ dict, key: "MaxLen" });
  2163. if (!Number.isInteger(maximumLength) || maximumLength < 0) {
  2164. maximumLength = 0;
  2165. }
  2166. this.data.maxLen = maximumLength;
  2167. // Process field flags for the display layer.
  2168. this.data.multiLine = this.hasFieldFlag(AnnotationFieldFlag.MULTILINE);
  2169. this.data.comb =
  2170. this.hasFieldFlag(AnnotationFieldFlag.COMB) &&
  2171. !this.hasFieldFlag(AnnotationFieldFlag.MULTILINE) &&
  2172. !this.hasFieldFlag(AnnotationFieldFlag.PASSWORD) &&
  2173. !this.hasFieldFlag(AnnotationFieldFlag.FILESELECT) &&
  2174. this.data.maxLen !== 0;
  2175. this.data.doNotScroll = this.hasFieldFlag(AnnotationFieldFlag.DONOTSCROLL);
  2176. }
  2177. _getCombAppearance(
  2178. defaultAppearance,
  2179. font,
  2180. text,
  2181. fontSize,
  2182. width,
  2183. height,
  2184. hPadding,
  2185. vPadding,
  2186. descent,
  2187. lineHeight,
  2188. annotationStorage
  2189. ) {
  2190. const combWidth = width / this.data.maxLen;
  2191. // Empty or it has a trailing whitespace.
  2192. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  2193. const buf = [];
  2194. const positions = font.getCharPositions(text);
  2195. for (const [start, end] of positions) {
  2196. buf.push(`(${escapeString(text.substring(start, end))}) Tj`);
  2197. }
  2198. const renderedComb = buf.join(` ${numberToString(combWidth)} 0 Td `);
  2199. return (
  2200. `/Tx BMC q ${colors}BT ` +
  2201. defaultAppearance +
  2202. ` 1 0 0 1 ${numberToString(hPadding)} ${numberToString(
  2203. vPadding + descent
  2204. )} Tm ${renderedComb}` +
  2205. " ET Q EMC"
  2206. );
  2207. }
  2208. _getMultilineAppearance(
  2209. defaultAppearance,
  2210. lines,
  2211. font,
  2212. fontSize,
  2213. width,
  2214. height,
  2215. alignment,
  2216. hPadding,
  2217. vPadding,
  2218. descent,
  2219. lineHeight,
  2220. annotationStorage
  2221. ) {
  2222. const buf = [];
  2223. const totalWidth = width - 2 * hPadding;
  2224. const prevInfo = { shift: 0 };
  2225. for (let i = 0, ii = lines.length; i < ii; i++) {
  2226. const line = lines[i];
  2227. const chunks = this._splitLine(line, font, fontSize, totalWidth);
  2228. for (let j = 0, jj = chunks.length; j < jj; j++) {
  2229. const chunk = chunks[j];
  2230. const vShift =
  2231. i === 0 && j === 0 ? -vPadding - (lineHeight - descent) : -lineHeight;
  2232. buf.push(
  2233. this._renderText(
  2234. chunk,
  2235. font,
  2236. fontSize,
  2237. width,
  2238. alignment,
  2239. prevInfo,
  2240. hPadding,
  2241. vShift
  2242. )
  2243. );
  2244. }
  2245. }
  2246. // Empty or it has a trailing whitespace.
  2247. const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
  2248. const renderedText = buf.join("\n");
  2249. return (
  2250. `/Tx BMC q ${colors}BT ` +
  2251. defaultAppearance +
  2252. ` 1 0 0 1 0 ${numberToString(height)} Tm ${renderedText}` +
  2253. " ET Q EMC"
  2254. );
  2255. }
  2256. _splitLine(line, font, fontSize, width, cache = {}) {
  2257. line = cache.line || line;
  2258. const glyphs = cache.glyphs || font.charsToGlyphs(line);
  2259. if (glyphs.length <= 1) {
  2260. // Nothing to split
  2261. return [line];
  2262. }
  2263. const positions = cache.positions || font.getCharPositions(line);
  2264. const scale = fontSize / 1000;
  2265. const chunks = [];
  2266. let lastSpacePosInStringStart = -1,
  2267. lastSpacePosInStringEnd = -1,
  2268. lastSpacePos = -1,
  2269. startChunk = 0,
  2270. currentWidth = 0;
  2271. for (let i = 0, ii = glyphs.length; i < ii; i++) {
  2272. const [start, end] = positions[i];
  2273. const glyph = glyphs[i];
  2274. const glyphWidth = glyph.width * scale;
  2275. if (glyph.unicode === " ") {
  2276. if (currentWidth + glyphWidth > width) {
  2277. // We can break here
  2278. chunks.push(line.substring(startChunk, start));
  2279. startChunk = start;
  2280. currentWidth = glyphWidth;
  2281. lastSpacePosInStringStart = -1;
  2282. lastSpacePos = -1;
  2283. } else {
  2284. currentWidth += glyphWidth;
  2285. lastSpacePosInStringStart = start;
  2286. lastSpacePosInStringEnd = end;
  2287. lastSpacePos = i;
  2288. }
  2289. } else {
  2290. if (currentWidth + glyphWidth > width) {
  2291. // We must break to the last white position (if available)
  2292. if (lastSpacePosInStringStart !== -1) {
  2293. chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
  2294. startChunk = lastSpacePosInStringEnd;
  2295. i = lastSpacePos + 1;
  2296. lastSpacePosInStringStart = -1;
  2297. currentWidth = 0;
  2298. } else {
  2299. // Just break in the middle of the word
  2300. chunks.push(line.substring(startChunk, start));
  2301. startChunk = start;
  2302. currentWidth = glyphWidth;
  2303. }
  2304. } else {
  2305. currentWidth += glyphWidth;
  2306. }
  2307. }
  2308. }
  2309. if (startChunk < line.length) {
  2310. chunks.push(line.substring(startChunk, line.length));
  2311. }
  2312. return chunks;
  2313. }
  2314. getFieldObject() {
  2315. return {
  2316. id: this.data.id,
  2317. value: this.data.fieldValue,
  2318. defaultValue: this.data.defaultFieldValue || "",
  2319. multiline: this.data.multiLine,
  2320. password: this.hasFieldFlag(AnnotationFieldFlag.PASSWORD),
  2321. charLimit: this.data.maxLen,
  2322. comb: this.data.comb,
  2323. editable: !this.data.readOnly,
  2324. hidden: this.data.hidden,
  2325. name: this.data.fieldName,
  2326. rect: this.data.rect,
  2327. actions: this.data.actions,
  2328. page: this.data.pageIndex,
  2329. strokeColor: this.data.borderColor,
  2330. fillColor: this.data.backgroundColor,
  2331. rotation: this.rotation,
  2332. type: "text",
  2333. };
  2334. }
  2335. }
  2336. class ButtonWidgetAnnotation extends WidgetAnnotation {
  2337. constructor(params) {
  2338. super(params);
  2339. this.checkedAppearance = null;
  2340. this.uncheckedAppearance = null;
  2341. this.data.checkBox =
  2342. !this.hasFieldFlag(AnnotationFieldFlag.RADIO) &&
  2343. !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
  2344. this.data.radioButton =
  2345. this.hasFieldFlag(AnnotationFieldFlag.RADIO) &&
  2346. !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
  2347. this.data.pushButton = this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
  2348. this.data.isTooltipOnly = false;
  2349. if (this.data.checkBox) {
  2350. this._processCheckBox(params);
  2351. } else if (this.data.radioButton) {
  2352. this._processRadioButton(params);
  2353. } else if (this.data.pushButton) {
  2354. this.data.hasOwnCanvas = true;
  2355. this._processPushButton(params);
  2356. } else {
  2357. warn("Invalid field flags for button widget annotation");
  2358. }
  2359. }
  2360. async getOperatorList(
  2361. evaluator,
  2362. task,
  2363. intent,
  2364. renderForms,
  2365. annotationStorage
  2366. ) {
  2367. if (this.data.pushButton) {
  2368. return super.getOperatorList(
  2369. evaluator,
  2370. task,
  2371. intent,
  2372. false, // we use normalAppearance to render the button
  2373. annotationStorage
  2374. );
  2375. }
  2376. let value = null;
  2377. let rotation = null;
  2378. if (annotationStorage) {
  2379. const storageEntry = annotationStorage.get(this.data.id);
  2380. value = storageEntry ? storageEntry.value : null;
  2381. rotation = storageEntry ? storageEntry.rotation : null;
  2382. }
  2383. if (value === null && this.appearance) {
  2384. // Nothing in the annotationStorage.
  2385. // But we've a default appearance so use it.
  2386. return super.getOperatorList(
  2387. evaluator,
  2388. task,
  2389. intent,
  2390. renderForms,
  2391. annotationStorage
  2392. );
  2393. }
  2394. if (value === null || value === undefined) {
  2395. // There is no default appearance so use the one derived
  2396. // from the field value.
  2397. if (this.data.checkBox) {
  2398. value = this.data.fieldValue === this.data.exportValue;
  2399. } else {
  2400. value = this.data.fieldValue === this.data.buttonValue;
  2401. }
  2402. }
  2403. const appearance = value
  2404. ? this.checkedAppearance
  2405. : this.uncheckedAppearance;
  2406. if (appearance) {
  2407. const savedAppearance = this.appearance;
  2408. const savedMatrix = appearance.dict.getArray("Matrix") || IDENTITY_MATRIX;
  2409. if (rotation) {
  2410. appearance.dict.set(
  2411. "Matrix",
  2412. this.getRotationMatrix(annotationStorage)
  2413. );
  2414. }
  2415. this.appearance = appearance;
  2416. const operatorList = super.getOperatorList(
  2417. evaluator,
  2418. task,
  2419. intent,
  2420. renderForms,
  2421. annotationStorage
  2422. );
  2423. this.appearance = savedAppearance;
  2424. appearance.dict.set("Matrix", savedMatrix);
  2425. return operatorList;
  2426. }
  2427. // No appearance
  2428. return {
  2429. opList: new OperatorList(),
  2430. separateForm: false,
  2431. separateCanvas: false,
  2432. };
  2433. }
  2434. async save(evaluator, task, annotationStorage) {
  2435. if (this.data.checkBox) {
  2436. return this._saveCheckbox(evaluator, task, annotationStorage);
  2437. }
  2438. if (this.data.radioButton) {
  2439. return this._saveRadioButton(evaluator, task, annotationStorage);
  2440. }
  2441. // Nothing to save
  2442. return null;
  2443. }
  2444. async _saveCheckbox(evaluator, task, annotationStorage) {
  2445. if (!annotationStorage) {
  2446. return null;
  2447. }
  2448. const storageEntry = annotationStorage.get(this.data.id);
  2449. let rotation = storageEntry && storageEntry.rotation;
  2450. let value = storageEntry && storageEntry.value;
  2451. if (rotation === undefined) {
  2452. if (value === undefined) {
  2453. return null;
  2454. }
  2455. const defaultValue = this.data.fieldValue === this.data.exportValue;
  2456. if (defaultValue === value) {
  2457. return null;
  2458. }
  2459. }
  2460. const dict = evaluator.xref.fetchIfRef(this.ref);
  2461. if (!(dict instanceof Dict)) {
  2462. return null;
  2463. }
  2464. if (rotation === undefined) {
  2465. rotation = this.rotation;
  2466. }
  2467. if (value === undefined) {
  2468. value = this.data.fieldValue === this.data.exportValue;
  2469. }
  2470. const xfa = {
  2471. path: stringToPDFString(dict.get("T") || ""),
  2472. value: value ? this.data.exportValue : "",
  2473. };
  2474. const name = Name.get(value ? this.data.exportValue : "Off");
  2475. dict.set("V", name);
  2476. dict.set("AS", name);
  2477. dict.set("M", `D:${getModificationDate()}`);
  2478. const maybeMK = this._getMKDict(rotation);
  2479. if (maybeMK) {
  2480. dict.set("MK", maybeMK);
  2481. }
  2482. const encrypt = evaluator.xref.encrypt;
  2483. let originalTransform = null;
  2484. if (encrypt) {
  2485. originalTransform = encrypt.createCipherTransform(
  2486. this.ref.num,
  2487. this.ref.gen
  2488. );
  2489. }
  2490. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  2491. writeDict(dict, buffer, originalTransform);
  2492. buffer.push("\nendobj\n");
  2493. return [{ ref: this.ref, data: buffer.join(""), xfa }];
  2494. }
  2495. async _saveRadioButton(evaluator, task, annotationStorage) {
  2496. if (!annotationStorage) {
  2497. return null;
  2498. }
  2499. const storageEntry = annotationStorage.get(this.data.id);
  2500. let rotation = storageEntry && storageEntry.rotation;
  2501. let value = storageEntry && storageEntry.value;
  2502. if (rotation === undefined) {
  2503. if (value === undefined) {
  2504. return null;
  2505. }
  2506. const defaultValue = this.data.fieldValue === this.data.buttonValue;
  2507. if (defaultValue === value) {
  2508. return null;
  2509. }
  2510. }
  2511. const dict = evaluator.xref.fetchIfRef(this.ref);
  2512. if (!(dict instanceof Dict)) {
  2513. return null;
  2514. }
  2515. if (value === undefined) {
  2516. value = this.data.fieldValue === this.data.buttonValue;
  2517. }
  2518. if (rotation === undefined) {
  2519. rotation = this.rotation;
  2520. }
  2521. const xfa = {
  2522. path: stringToPDFString(dict.get("T") || ""),
  2523. value: value ? this.data.buttonValue : "",
  2524. };
  2525. const name = Name.get(value ? this.data.buttonValue : "Off");
  2526. let parentBuffer = null;
  2527. const encrypt = evaluator.xref.encrypt;
  2528. if (value) {
  2529. if (this.parent instanceof Ref) {
  2530. const parent = evaluator.xref.fetch(this.parent);
  2531. let parentTransform = null;
  2532. if (encrypt) {
  2533. parentTransform = encrypt.createCipherTransform(
  2534. this.parent.num,
  2535. this.parent.gen
  2536. );
  2537. }
  2538. parent.set("V", name);
  2539. parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
  2540. writeDict(parent, parentBuffer, parentTransform);
  2541. parentBuffer.push("\nendobj\n");
  2542. } else if (this.parent instanceof Dict) {
  2543. this.parent.set("V", name);
  2544. }
  2545. }
  2546. dict.set("AS", name);
  2547. dict.set("M", `D:${getModificationDate()}`);
  2548. const maybeMK = this._getMKDict(rotation);
  2549. if (maybeMK) {
  2550. dict.set("MK", maybeMK);
  2551. }
  2552. let originalTransform = null;
  2553. if (encrypt) {
  2554. originalTransform = encrypt.createCipherTransform(
  2555. this.ref.num,
  2556. this.ref.gen
  2557. );
  2558. }
  2559. const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
  2560. writeDict(dict, buffer, originalTransform);
  2561. buffer.push("\nendobj\n");
  2562. const newRefs = [{ ref: this.ref, data: buffer.join(""), xfa }];
  2563. if (parentBuffer !== null) {
  2564. newRefs.push({
  2565. ref: this.parent,
  2566. data: parentBuffer.join(""),
  2567. xfa: null,
  2568. });
  2569. }
  2570. return newRefs;
  2571. }
  2572. _getDefaultCheckedAppearance(params, type) {
  2573. const width = this.data.rect[2] - this.data.rect[0];
  2574. const height = this.data.rect[3] - this.data.rect[1];
  2575. const bbox = [0, 0, width, height];
  2576. // Ratio used to have a mark slightly smaller than the bbox.
  2577. const FONT_RATIO = 0.8;
  2578. const fontSize = Math.min(width, height) * FONT_RATIO;
  2579. // Char Metrics
  2580. // Widths came from widths for ZapfDingbats.
  2581. // Heights are guessed with Fontforge and FoxitDingbats.pfb.
  2582. let metrics, char;
  2583. if (type === "check") {
  2584. // Char 33 (2713 in unicode)
  2585. metrics = {
  2586. width: 0.755 * fontSize,
  2587. height: 0.705 * fontSize,
  2588. };
  2589. char = "\x33";
  2590. } else if (type === "disc") {
  2591. // Char 6C (25CF in unicode)
  2592. metrics = {
  2593. width: 0.791 * fontSize,
  2594. height: 0.705 * fontSize,
  2595. };
  2596. char = "\x6C";
  2597. } else {
  2598. unreachable(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
  2599. }
  2600. // Values to center the glyph in the bbox.
  2601. const xShift = numberToString((width - metrics.width) / 2);
  2602. const yShift = numberToString((height - metrics.height) / 2);
  2603. const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
  2604. const appearanceStreamDict = new Dict(params.xref);
  2605. appearanceStreamDict.set("FormType", 1);
  2606. appearanceStreamDict.set("Subtype", Name.get("Form"));
  2607. appearanceStreamDict.set("Type", Name.get("XObject"));
  2608. appearanceStreamDict.set("BBox", bbox);
  2609. appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
  2610. appearanceStreamDict.set("Length", appearance.length);
  2611. const resources = new Dict(params.xref);
  2612. const font = new Dict(params.xref);
  2613. font.set("PdfJsZaDb", this.fallbackFontDict);
  2614. resources.set("Font", font);
  2615. appearanceStreamDict.set("Resources", resources);
  2616. this.checkedAppearance = new StringStream(appearance);
  2617. this.checkedAppearance.dict = appearanceStreamDict;
  2618. this._streams.push(this.checkedAppearance);
  2619. }
  2620. _processCheckBox(params) {
  2621. const customAppearance = params.dict.get("AP");
  2622. if (!(customAppearance instanceof Dict)) {
  2623. return;
  2624. }
  2625. const normalAppearance = customAppearance.get("N");
  2626. if (!(normalAppearance instanceof Dict)) {
  2627. return;
  2628. }
  2629. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1722036.
  2630. // If we've an AS and a V then take AS.
  2631. const asValue = this._decodeFormValue(params.dict.get("AS"));
  2632. if (typeof asValue === "string") {
  2633. this.data.fieldValue = asValue;
  2634. }
  2635. const yes =
  2636. this.data.fieldValue !== null && this.data.fieldValue !== "Off"
  2637. ? this.data.fieldValue
  2638. : "Yes";
  2639. const exportValues = normalAppearance.getKeys();
  2640. if (exportValues.length === 0) {
  2641. exportValues.push("Off", yes);
  2642. } else if (exportValues.length === 1) {
  2643. if (exportValues[0] === "Off") {
  2644. exportValues.push(yes);
  2645. } else {
  2646. exportValues.unshift("Off");
  2647. }
  2648. } else if (exportValues.includes(yes)) {
  2649. exportValues.length = 0;
  2650. exportValues.push("Off", yes);
  2651. } else {
  2652. const otherYes = exportValues.find(v => v !== "Off");
  2653. exportValues.length = 0;
  2654. exportValues.push("Off", otherYes);
  2655. }
  2656. // Don't use a "V" entry pointing to a non-existent appearance state,
  2657. // see e.g. bug1720411.pdf where it's an *empty* Name-instance.
  2658. if (!exportValues.includes(this.data.fieldValue)) {
  2659. this.data.fieldValue = "Off";
  2660. }
  2661. this.data.exportValue = exportValues[1];
  2662. this.checkedAppearance =
  2663. normalAppearance.get(this.data.exportValue) || null;
  2664. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  2665. if (this.checkedAppearance) {
  2666. this._streams.push(this.checkedAppearance);
  2667. } else {
  2668. this._getDefaultCheckedAppearance(params, "check");
  2669. }
  2670. if (this.uncheckedAppearance) {
  2671. this._streams.push(this.uncheckedAppearance);
  2672. }
  2673. this._fallbackFontDict = this.fallbackFontDict;
  2674. }
  2675. _processRadioButton(params) {
  2676. this.data.fieldValue = this.data.buttonValue = null;
  2677. // The parent field's `V` entry holds a `Name` object with the appearance
  2678. // state of whichever child field is currently in the "on" state.
  2679. const fieldParent = params.dict.get("Parent");
  2680. if (fieldParent instanceof Dict) {
  2681. this.parent = params.dict.getRaw("Parent");
  2682. const fieldParentValue = fieldParent.get("V");
  2683. if (fieldParentValue instanceof Name) {
  2684. this.data.fieldValue = this._decodeFormValue(fieldParentValue);
  2685. }
  2686. }
  2687. // The button's value corresponds to its appearance state.
  2688. const appearanceStates = params.dict.get("AP");
  2689. if (!(appearanceStates instanceof Dict)) {
  2690. return;
  2691. }
  2692. const normalAppearance = appearanceStates.get("N");
  2693. if (!(normalAppearance instanceof Dict)) {
  2694. return;
  2695. }
  2696. for (const key of normalAppearance.getKeys()) {
  2697. if (key !== "Off") {
  2698. this.data.buttonValue = this._decodeFormValue(key);
  2699. break;
  2700. }
  2701. }
  2702. this.checkedAppearance =
  2703. normalAppearance.get(this.data.buttonValue) || null;
  2704. this.uncheckedAppearance = normalAppearance.get("Off") || null;
  2705. if (this.checkedAppearance) {
  2706. this._streams.push(this.checkedAppearance);
  2707. } else {
  2708. this._getDefaultCheckedAppearance(params, "disc");
  2709. }
  2710. if (this.uncheckedAppearance) {
  2711. this._streams.push(this.uncheckedAppearance);
  2712. }
  2713. this._fallbackFontDict = this.fallbackFontDict;
  2714. }
  2715. _processPushButton(params) {
  2716. if (
  2717. !params.dict.has("A") &&
  2718. !params.dict.has("AA") &&
  2719. !this.data.alternativeText
  2720. ) {
  2721. warn("Push buttons without action dictionaries are not supported");
  2722. return;
  2723. }
  2724. this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
  2725. Catalog.parseDestDictionary({
  2726. destDict: params.dict,
  2727. resultObj: this.data,
  2728. docBaseUrl: params.pdfManager.docBaseUrl,
  2729. docAttachments: params.attachments,
  2730. });
  2731. }
  2732. getFieldObject() {
  2733. let type = "button";
  2734. let exportValues;
  2735. if (this.data.checkBox) {
  2736. type = "checkbox";
  2737. exportValues = this.data.exportValue;
  2738. } else if (this.data.radioButton) {
  2739. type = "radiobutton";
  2740. exportValues = this.data.buttonValue;
  2741. }
  2742. return {
  2743. id: this.data.id,
  2744. value: this.data.fieldValue || "Off",
  2745. defaultValue: this.data.defaultFieldValue,
  2746. exportValues,
  2747. editable: !this.data.readOnly,
  2748. name: this.data.fieldName,
  2749. rect: this.data.rect,
  2750. hidden: this.data.hidden,
  2751. actions: this.data.actions,
  2752. page: this.data.pageIndex,
  2753. strokeColor: this.data.borderColor,
  2754. fillColor: this.data.backgroundColor,
  2755. rotation: this.rotation,
  2756. type,
  2757. };
  2758. }
  2759. get fallbackFontDict() {
  2760. const dict = new Dict();
  2761. dict.set("BaseFont", Name.get("ZapfDingbats"));
  2762. dict.set("Type", Name.get("FallbackType"));
  2763. dict.set("Subtype", Name.get("FallbackType"));
  2764. dict.set("Encoding", Name.get("ZapfDingbatsEncoding"));
  2765. return shadow(this, "fallbackFontDict", dict);
  2766. }
  2767. }
  2768. class ChoiceWidgetAnnotation extends WidgetAnnotation {
  2769. constructor(params) {
  2770. super(params);
  2771. const { dict, xref } = params;
  2772. // Determine the options. The options array may consist of strings or
  2773. // arrays. If the array consists of arrays, then the first element of
  2774. // each array is the export value and the second element of each array is
  2775. // the display value. If the array consists of strings, then these
  2776. // represent both the export and display value. In this case, we convert
  2777. // it to an array of arrays as well for convenience in the display layer.
  2778. // Note that the specification does not state that the `Opt` field is
  2779. // inheritable, but in practice PDF generators do make annotations
  2780. // inherit the options from a parent annotation (issue 8094).
  2781. this.data.options = [];
  2782. const options = getInheritableProperty({ dict, key: "Opt" });
  2783. if (Array.isArray(options)) {
  2784. for (let i = 0, ii = options.length; i < ii; i++) {
  2785. const option = xref.fetchIfRef(options[i]);
  2786. const isOptionArray = Array.isArray(option);
  2787. this.data.options[i] = {
  2788. exportValue: this._decodeFormValue(
  2789. isOptionArray ? xref.fetchIfRef(option[0]) : option
  2790. ),
  2791. displayValue: this._decodeFormValue(
  2792. isOptionArray ? xref.fetchIfRef(option[1]) : option
  2793. ),
  2794. };
  2795. }
  2796. }
  2797. // The field value can be `null` if no item is selected, a string if one
  2798. // item is selected or an array of strings if multiple items are selected.
  2799. // For consistency in the API and convenience in the display layer, we
  2800. // always make the field value an array with zero, one or multiple items.
  2801. if (typeof this.data.fieldValue === "string") {
  2802. this.data.fieldValue = [this.data.fieldValue];
  2803. } else if (!this.data.fieldValue) {
  2804. this.data.fieldValue = [];
  2805. }
  2806. // Process field flags for the display layer.
  2807. this.data.combo = this.hasFieldFlag(AnnotationFieldFlag.COMBO);
  2808. this.data.multiSelect = this.hasFieldFlag(AnnotationFieldFlag.MULTISELECT);
  2809. this._hasText = true;
  2810. }
  2811. getFieldObject() {
  2812. const type = this.data.combo ? "combobox" : "listbox";
  2813. const value =
  2814. this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
  2815. return {
  2816. id: this.data.id,
  2817. value,
  2818. defaultValue: this.data.defaultFieldValue,
  2819. editable: !this.data.readOnly,
  2820. name: this.data.fieldName,
  2821. rect: this.data.rect,
  2822. numItems: this.data.fieldValue.length,
  2823. multipleSelection: this.data.multiSelect,
  2824. hidden: this.data.hidden,
  2825. actions: this.data.actions,
  2826. items: this.data.options,
  2827. page: this.data.pageIndex,
  2828. strokeColor: this.data.borderColor,
  2829. fillColor: this.data.backgroundColor,
  2830. rotation: this.rotation,
  2831. type,
  2832. };
  2833. }
  2834. async _getAppearance(evaluator, task, intent, annotationStorage) {
  2835. if (this.data.combo) {
  2836. return super._getAppearance(evaluator, task, intent, annotationStorage);
  2837. }
  2838. let exportedValue, rotation;
  2839. const storageEntry = annotationStorage
  2840. ? annotationStorage.get(this.data.id)
  2841. : undefined;
  2842. if (storageEntry) {
  2843. rotation = storageEntry.rotation;
  2844. exportedValue = storageEntry.value;
  2845. }
  2846. if (
  2847. rotation === undefined &&
  2848. exportedValue === undefined &&
  2849. !this._needAppearances
  2850. ) {
  2851. // The annotation hasn't been rendered so use the appearance
  2852. return null;
  2853. }
  2854. if (exportedValue === undefined) {
  2855. exportedValue = this.data.fieldValue;
  2856. } else if (!Array.isArray(exportedValue)) {
  2857. exportedValue = [exportedValue];
  2858. }
  2859. const defaultPadding = 1;
  2860. const defaultHPadding = 2;
  2861. let totalHeight = this.data.rect[3] - this.data.rect[1];
  2862. let totalWidth = this.data.rect[2] - this.data.rect[0];
  2863. if (rotation === 90 || rotation === 270) {
  2864. [totalWidth, totalHeight] = [totalHeight, totalWidth];
  2865. }
  2866. const lineCount = this.data.options.length;
  2867. const valueIndices = [];
  2868. for (let i = 0; i < lineCount; i++) {
  2869. const { exportValue } = this.data.options[i];
  2870. if (exportedValue.includes(exportValue)) {
  2871. valueIndices.push(i);
  2872. }
  2873. }
  2874. if (!this._defaultAppearance) {
  2875. // The DA is required and must be a string.
  2876. // If there is no font named Helvetica in the resource dictionary,
  2877. // the evaluator will fall back to a default font.
  2878. // Doing so prevents exceptions and allows saving/printing
  2879. // the file as expected.
  2880. this.data.defaultAppearanceData = parseDefaultAppearance(
  2881. (this._defaultAppearance = "/Helvetica 0 Tf 0 g")
  2882. );
  2883. }
  2884. const font = await WidgetAnnotation._getFontData(
  2885. evaluator,
  2886. task,
  2887. this.data.defaultAppearanceData,
  2888. this._fieldResources.mergedResources
  2889. );
  2890. let defaultAppearance;
  2891. let { fontSize } = this.data.defaultAppearanceData;
  2892. if (!fontSize) {
  2893. const lineHeight = (totalHeight - defaultPadding) / lineCount;
  2894. let lineWidth = -1;
  2895. let value;
  2896. for (const { displayValue } of this.data.options) {
  2897. const width = this._getTextWidth(displayValue, font);
  2898. if (width > lineWidth) {
  2899. lineWidth = width;
  2900. value = displayValue;
  2901. }
  2902. }
  2903. [defaultAppearance, fontSize] = this._computeFontSize(
  2904. lineHeight,
  2905. totalWidth - 2 * defaultHPadding,
  2906. value,
  2907. font,
  2908. -1
  2909. );
  2910. } else {
  2911. defaultAppearance = this._defaultAppearance;
  2912. }
  2913. const lineHeight = fontSize * LINE_FACTOR;
  2914. const vPadding = (lineHeight - fontSize) / 2;
  2915. const numberOfVisibleLines = Math.floor(totalHeight / lineHeight);
  2916. let firstIndex;
  2917. if (valueIndices.length === 1) {
  2918. const valuePosition = valueIndices[0];
  2919. const indexInPage = valuePosition % numberOfVisibleLines;
  2920. firstIndex = valuePosition - indexInPage;
  2921. } else {
  2922. // If nothing is selected (valueIndice.length === 0), we render
  2923. // from the first element.
  2924. firstIndex = valueIndices.length ? valueIndices[0] : 0;
  2925. }
  2926. const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount);
  2927. const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`];
  2928. if (valueIndices.length) {
  2929. // This value has been copied/pasted from annotation-choice-widget.pdf.
  2930. // It corresponds to rgb(153, 193, 218).
  2931. buf.push("0.600006 0.756866 0.854904 rg");
  2932. // Highlight the lines in filling a blue rectangle at the selected
  2933. // positions.
  2934. for (const index of valueIndices) {
  2935. if (firstIndex <= index && index < end) {
  2936. buf.push(
  2937. `1 ${
  2938. totalHeight - (index - firstIndex + 1) * lineHeight
  2939. } ${totalWidth} ${lineHeight} re f`
  2940. );
  2941. }
  2942. }
  2943. }
  2944. buf.push("BT", defaultAppearance, `1 0 0 1 0 ${totalHeight} Tm`);
  2945. const prevInfo = { shift: 0 };
  2946. for (let i = firstIndex; i < end; i++) {
  2947. const { displayValue } = this.data.options[i];
  2948. const vpadding = i === firstIndex ? vPadding : 0;
  2949. buf.push(
  2950. this._renderText(
  2951. displayValue,
  2952. font,
  2953. fontSize,
  2954. totalWidth,
  2955. 0,
  2956. prevInfo,
  2957. defaultHPadding,
  2958. -lineHeight + vpadding
  2959. )
  2960. );
  2961. }
  2962. buf.push("ET Q EMC");
  2963. return buf.join("\n");
  2964. }
  2965. }
  2966. class SignatureWidgetAnnotation extends WidgetAnnotation {
  2967. constructor(params) {
  2968. super(params);
  2969. // Unset the fieldValue since it's (most likely) a `Dict` which is
  2970. // non-serializable and will thus cause errors when sending annotations
  2971. // to the main-thread (issue 10347).
  2972. this.data.fieldValue = null;
  2973. }
  2974. getFieldObject() {
  2975. return {
  2976. id: this.data.id,
  2977. value: null,
  2978. page: this.data.pageIndex,
  2979. type: "signature",
  2980. };
  2981. }
  2982. }
  2983. class TextAnnotation extends MarkupAnnotation {
  2984. constructor(params) {
  2985. const DEFAULT_ICON_SIZE = 22; // px
  2986. super(params);
  2987. const { dict } = params;
  2988. this.data.annotationType = AnnotationType.TEXT;
  2989. if (this.data.hasAppearance) {
  2990. this.data.name = "NoIcon";
  2991. } else {
  2992. this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
  2993. this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
  2994. this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
  2995. }
  2996. if (dict.has("State")) {
  2997. this.data.state = dict.get("State") || null;
  2998. this.data.stateModel = dict.get("StateModel") || null;
  2999. } else {
  3000. this.data.state = null;
  3001. this.data.stateModel = null;
  3002. }
  3003. }
  3004. }
  3005. class LinkAnnotation extends Annotation {
  3006. constructor(params) {
  3007. super(params);
  3008. this.data.annotationType = AnnotationType.LINK;
  3009. const quadPoints = getQuadPoints(params.dict, this.rectangle);
  3010. if (quadPoints) {
  3011. this.data.quadPoints = quadPoints;
  3012. }
  3013. // The color entry for a link annotation is the color of the border.
  3014. this.data.borderColor = this.data.borderColor || this.data.color;
  3015. Catalog.parseDestDictionary({
  3016. destDict: params.dict,
  3017. resultObj: this.data,
  3018. docBaseUrl: params.pdfManager.docBaseUrl,
  3019. docAttachments: params.attachments,
  3020. });
  3021. }
  3022. }
  3023. class PopupAnnotation extends Annotation {
  3024. constructor(params) {
  3025. super(params);
  3026. const { dict } = params;
  3027. this.data.annotationType = AnnotationType.POPUP;
  3028. let parentItem = dict.get("Parent");
  3029. if (!parentItem) {
  3030. warn("Popup annotation has a missing or invalid parent annotation.");
  3031. return;
  3032. }
  3033. const parentSubtype = parentItem.get("Subtype");
  3034. this.data.parentType =
  3035. parentSubtype instanceof Name ? parentSubtype.name : null;
  3036. const rawParent = dict.getRaw("Parent");
  3037. this.data.parentId = rawParent instanceof Ref ? rawParent.toString() : null;
  3038. const parentRect = parentItem.getArray("Rect");
  3039. if (Array.isArray(parentRect) && parentRect.length === 4) {
  3040. this.data.parentRect = Util.normalizeRect(parentRect);
  3041. } else {
  3042. this.data.parentRect = [0, 0, 0, 0];
  3043. }
  3044. const rt = parentItem.get("RT");
  3045. if (isName(rt, AnnotationReplyType.GROUP)) {
  3046. // Subordinate annotations in a group should inherit
  3047. // the group attributes from the primary annotation.
  3048. parentItem = parentItem.get("IRT");
  3049. }
  3050. if (!parentItem.has("M")) {
  3051. this.data.modificationDate = null;
  3052. } else {
  3053. this.setModificationDate(parentItem.get("M"));
  3054. this.data.modificationDate = this.modificationDate;
  3055. }
  3056. if (!parentItem.has("C")) {
  3057. // Fall back to the default background color.
  3058. this.data.color = null;
  3059. } else {
  3060. this.setColor(parentItem.getArray("C"));
  3061. this.data.color = this.color;
  3062. }
  3063. // If the Popup annotation is not viewable, but the parent annotation is,
  3064. // that is most likely a bug. Fallback to inherit the flags from the parent
  3065. // annotation (this is consistent with the behaviour in Adobe Reader).
  3066. if (!this.viewable) {
  3067. const parentFlags = parentItem.get("F");
  3068. if (this._isViewable(parentFlags)) {
  3069. this.setFlags(parentFlags);
  3070. }
  3071. }
  3072. this.setTitle(parentItem.get("T"));
  3073. this.data.titleObj = this._title;
  3074. this.setContents(parentItem.get("Contents"));
  3075. this.data.contentsObj = this._contents;
  3076. if (parentItem.has("RC")) {
  3077. this.data.richText = XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
  3078. }
  3079. }
  3080. }
  3081. class FreeTextAnnotation extends MarkupAnnotation {
  3082. constructor(params) {
  3083. super(params);
  3084. const { xref } = params;
  3085. this.data.annotationType = AnnotationType.FREETEXT;
  3086. this.setDefaultAppearance(params);
  3087. if (!this.appearance && this._isOffscreenCanvasSupported) {
  3088. const fakeUnicodeFont = new FakeUnicodeFont(xref, "sans-serif");
  3089. const fontData = this.data.defaultAppearanceData;
  3090. this.appearance = fakeUnicodeFont.createAppearance(
  3091. this._contents.str,
  3092. this.rectangle,
  3093. this.rotation,
  3094. fontData.fontSize || 10,
  3095. fontData.fontColor
  3096. );
  3097. this._streams.push(this.appearance, FakeUnicodeFont.toUnicodeStream);
  3098. } else if (!this._isOffscreenCanvasSupported) {
  3099. warn(
  3100. "FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly."
  3101. );
  3102. }
  3103. }
  3104. get hasTextContent() {
  3105. return !!this.appearance;
  3106. }
  3107. static createNewDict(annotation, xref, { apRef, ap }) {
  3108. const { color, fontSize, rect, rotation, user, value } = annotation;
  3109. const freetext = new Dict(xref);
  3110. freetext.set("Type", Name.get("Annot"));
  3111. freetext.set("Subtype", Name.get("FreeText"));
  3112. freetext.set("CreationDate", `D:${getModificationDate()}`);
  3113. freetext.set("Rect", rect);
  3114. const da = `/Helv ${fontSize} Tf ${getPdfColor(color, /* isFill */ true)}`;
  3115. freetext.set("DA", da);
  3116. freetext.set(
  3117. "Contents",
  3118. isAscii(value)
  3119. ? value
  3120. : stringToUTF16String(value, /* bigEndian = */ true)
  3121. );
  3122. freetext.set("F", 4);
  3123. freetext.set("Border", [0, 0, 0]);
  3124. freetext.set("Rotate", rotation);
  3125. if (user) {
  3126. freetext.set(
  3127. "T",
  3128. isAscii(user) ? user : stringToUTF16String(user, /* bigEndian = */ true)
  3129. );
  3130. }
  3131. if (apRef || ap) {
  3132. const n = new Dict(xref);
  3133. freetext.set("AP", n);
  3134. if (apRef) {
  3135. n.set("N", apRef);
  3136. } else {
  3137. n.set("N", ap);
  3138. }
  3139. }
  3140. return freetext;
  3141. }
  3142. static async createNewAppearanceStream(annotation, xref, params) {
  3143. const { baseFontRef, evaluator, task } = params;
  3144. const { color, fontSize, rect, rotation, value } = annotation;
  3145. const resources = new Dict(xref);
  3146. const font = new Dict(xref);
  3147. if (baseFontRef) {
  3148. font.set("Helv", baseFontRef);
  3149. } else {
  3150. const baseFont = new Dict(xref);
  3151. baseFont.set("BaseFont", Name.get("Helvetica"));
  3152. baseFont.set("Type", Name.get("Font"));
  3153. baseFont.set("Subtype", Name.get("Type1"));
  3154. baseFont.set("Encoding", Name.get("WinAnsiEncoding"));
  3155. font.set("Helv", baseFont);
  3156. }
  3157. resources.set("Font", font);
  3158. const helv = await WidgetAnnotation._getFontData(
  3159. evaluator,
  3160. task,
  3161. {
  3162. fontName: "Helvetica",
  3163. fontSize,
  3164. },
  3165. resources
  3166. );
  3167. const [x1, y1, x2, y2] = rect;
  3168. let w = x2 - x1;
  3169. let h = y2 - y1;
  3170. if (rotation % 180 !== 0) {
  3171. [w, h] = [h, w];
  3172. }
  3173. const lines = value.split("\n");
  3174. const scale = fontSize / 1000;
  3175. let totalWidth = -Infinity;
  3176. const encodedLines = [];
  3177. for (let line of lines) {
  3178. const encoded = helv.encodeString(line);
  3179. if (encoded.length > 1) {
  3180. // The font doesn't contain all the chars.
  3181. return null;
  3182. }
  3183. line = encoded.join("");
  3184. encodedLines.push(line);
  3185. let lineWidth = 0;
  3186. const glyphs = helv.charsToGlyphs(line);
  3187. for (const glyph of glyphs) {
  3188. lineWidth += glyph.width * scale;
  3189. }
  3190. totalWidth = Math.max(totalWidth, lineWidth);
  3191. }
  3192. let hscale = 1;
  3193. if (totalWidth > w) {
  3194. hscale = w / totalWidth;
  3195. }
  3196. let vscale = 1;
  3197. const lineHeight = LINE_FACTOR * fontSize;
  3198. const lineDescent = LINE_DESCENT_FACTOR * fontSize;
  3199. const totalHeight = lineHeight * lines.length;
  3200. if (totalHeight > h) {
  3201. vscale = h / totalHeight;
  3202. }
  3203. const fscale = Math.min(hscale, vscale);
  3204. const newFontSize = fontSize * fscale;
  3205. const buffer = [
  3206. "q",
  3207. `0 0 ${numberToString(w)} ${numberToString(h)} re W n`,
  3208. `BT`,
  3209. `1 0 0 1 0 ${numberToString(h + lineDescent)} Tm 0 Tc ${getPdfColor(
  3210. color,
  3211. /* isFill */ true
  3212. )}`,
  3213. `/Helv ${numberToString(newFontSize)} Tf`,
  3214. ];
  3215. const vShift = numberToString(lineHeight);
  3216. for (const line of encodedLines) {
  3217. buffer.push(`0 -${vShift} Td (${escapeString(line)}) Tj`);
  3218. }
  3219. buffer.push("ET", "Q");
  3220. const appearance = buffer.join("\n");
  3221. const appearanceStreamDict = new Dict(xref);
  3222. appearanceStreamDict.set("FormType", 1);
  3223. appearanceStreamDict.set("Subtype", Name.get("Form"));
  3224. appearanceStreamDict.set("Type", Name.get("XObject"));
  3225. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  3226. appearanceStreamDict.set("Length", appearance.length);
  3227. appearanceStreamDict.set("Resources", resources);
  3228. if (rotation) {
  3229. const matrix = getRotationMatrix(rotation, w, h);
  3230. appearanceStreamDict.set("Matrix", matrix);
  3231. }
  3232. const ap = new StringStream(appearance);
  3233. ap.dict = appearanceStreamDict;
  3234. return ap;
  3235. }
  3236. }
  3237. class LineAnnotation extends MarkupAnnotation {
  3238. constructor(params) {
  3239. super(params);
  3240. const { dict, xref } = params;
  3241. this.data.annotationType = AnnotationType.LINE;
  3242. const lineCoordinates = dict.getArray("L");
  3243. this.data.lineCoordinates = Util.normalizeRect(lineCoordinates);
  3244. this.setLineEndings(dict.getArray("LE"));
  3245. this.data.lineEndings = this.lineEndings;
  3246. if (!this.appearance) {
  3247. // The default stroke color is black.
  3248. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  3249. const strokeAlpha = dict.get("CA");
  3250. const interiorColor = getRgbColor(dict.getArray("IC"), null);
  3251. // The default fill color is transparent. Setting the fill colour is
  3252. // necessary if/when we want to add support for non-default line endings.
  3253. const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
  3254. const fillAlpha = fillColor ? strokeAlpha : null;
  3255. const borderWidth = this.borderStyle.width || 1,
  3256. borderAdjust = 2 * borderWidth;
  3257. // If the /Rect-entry is empty/wrong, create a fallback rectangle so that
  3258. // we get similar rendering/highlighting behaviour as in Adobe Reader.
  3259. const bbox = [
  3260. this.data.lineCoordinates[0] - borderAdjust,
  3261. this.data.lineCoordinates[1] - borderAdjust,
  3262. this.data.lineCoordinates[2] + borderAdjust,
  3263. this.data.lineCoordinates[3] + borderAdjust,
  3264. ];
  3265. if (!Util.intersect(this.rectangle, bbox)) {
  3266. this.rectangle = bbox;
  3267. }
  3268. this._setDefaultAppearance({
  3269. xref,
  3270. extra: `${borderWidth} w`,
  3271. strokeColor,
  3272. fillColor,
  3273. strokeAlpha,
  3274. fillAlpha,
  3275. pointsCallback: (buffer, points) => {
  3276. buffer.push(
  3277. `${lineCoordinates[0]} ${lineCoordinates[1]} m`,
  3278. `${lineCoordinates[2]} ${lineCoordinates[3]} l`,
  3279. "S"
  3280. );
  3281. return [
  3282. points[0].x - borderWidth,
  3283. points[1].x + borderWidth,
  3284. points[3].y - borderWidth,
  3285. points[1].y + borderWidth,
  3286. ];
  3287. },
  3288. });
  3289. }
  3290. }
  3291. }
  3292. class SquareAnnotation extends MarkupAnnotation {
  3293. constructor(params) {
  3294. super(params);
  3295. const { dict, xref } = params;
  3296. this.data.annotationType = AnnotationType.SQUARE;
  3297. if (!this.appearance) {
  3298. // The default stroke color is black.
  3299. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  3300. const strokeAlpha = dict.get("CA");
  3301. const interiorColor = getRgbColor(dict.getArray("IC"), null);
  3302. // The default fill color is transparent.
  3303. const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
  3304. const fillAlpha = fillColor ? strokeAlpha : null;
  3305. if (this.borderStyle.width === 0 && !fillColor) {
  3306. // Prevent rendering a "hairline" border (fixes issue14164.pdf).
  3307. return;
  3308. }
  3309. this._setDefaultAppearance({
  3310. xref,
  3311. extra: `${this.borderStyle.width} w`,
  3312. strokeColor,
  3313. fillColor,
  3314. strokeAlpha,
  3315. fillAlpha,
  3316. pointsCallback: (buffer, points) => {
  3317. const x = points[2].x + this.borderStyle.width / 2;
  3318. const y = points[2].y + this.borderStyle.width / 2;
  3319. const width = points[3].x - points[2].x - this.borderStyle.width;
  3320. const height = points[1].y - points[3].y - this.borderStyle.width;
  3321. buffer.push(`${x} ${y} ${width} ${height} re`);
  3322. if (fillColor) {
  3323. buffer.push("B");
  3324. } else {
  3325. buffer.push("S");
  3326. }
  3327. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3328. },
  3329. });
  3330. }
  3331. }
  3332. }
  3333. class CircleAnnotation extends MarkupAnnotation {
  3334. constructor(params) {
  3335. super(params);
  3336. const { dict, xref } = params;
  3337. this.data.annotationType = AnnotationType.CIRCLE;
  3338. if (!this.appearance) {
  3339. // The default stroke color is black.
  3340. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  3341. const strokeAlpha = dict.get("CA");
  3342. const interiorColor = getRgbColor(dict.getArray("IC"), null);
  3343. // The default fill color is transparent.
  3344. const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
  3345. const fillAlpha = fillColor ? strokeAlpha : null;
  3346. if (this.borderStyle.width === 0 && !fillColor) {
  3347. // Prevent rendering a "hairline" border (fixes issue14164.pdf).
  3348. return;
  3349. }
  3350. // Circles are approximated by Bézier curves with four segments since
  3351. // there is no circle primitive in the PDF specification. For the control
  3352. // points distance, see https://stackoverflow.com/a/27863181.
  3353. const controlPointsDistance = (4 / 3) * Math.tan(Math.PI / (2 * 4));
  3354. this._setDefaultAppearance({
  3355. xref,
  3356. extra: `${this.borderStyle.width} w`,
  3357. strokeColor,
  3358. fillColor,
  3359. strokeAlpha,
  3360. fillAlpha,
  3361. pointsCallback: (buffer, points) => {
  3362. const x0 = points[0].x + this.borderStyle.width / 2;
  3363. const y0 = points[0].y - this.borderStyle.width / 2;
  3364. const x1 = points[3].x - this.borderStyle.width / 2;
  3365. const y1 = points[3].y + this.borderStyle.width / 2;
  3366. const xMid = x0 + (x1 - x0) / 2;
  3367. const yMid = y0 + (y1 - y0) / 2;
  3368. const xOffset = ((x1 - x0) / 2) * controlPointsDistance;
  3369. const yOffset = ((y1 - y0) / 2) * controlPointsDistance;
  3370. buffer.push(
  3371. `${xMid} ${y1} m`,
  3372. `${xMid + xOffset} ${y1} ${x1} ${yMid + yOffset} ${x1} ${yMid} c`,
  3373. `${x1} ${yMid - yOffset} ${xMid + xOffset} ${y0} ${xMid} ${y0} c`,
  3374. `${xMid - xOffset} ${y0} ${x0} ${yMid - yOffset} ${x0} ${yMid} c`,
  3375. `${x0} ${yMid + yOffset} ${xMid - xOffset} ${y1} ${xMid} ${y1} c`,
  3376. "h"
  3377. );
  3378. if (fillColor) {
  3379. buffer.push("B");
  3380. } else {
  3381. buffer.push("S");
  3382. }
  3383. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3384. },
  3385. });
  3386. }
  3387. }
  3388. }
  3389. class PolylineAnnotation extends MarkupAnnotation {
  3390. constructor(params) {
  3391. super(params);
  3392. const { dict, xref } = params;
  3393. this.data.annotationType = AnnotationType.POLYLINE;
  3394. this.data.vertices = [];
  3395. if (!(this instanceof PolygonAnnotation)) {
  3396. // Only meaningful for polyline annotations.
  3397. this.setLineEndings(dict.getArray("LE"));
  3398. this.data.lineEndings = this.lineEndings;
  3399. }
  3400. // The vertices array is an array of numbers representing the alternating
  3401. // horizontal and vertical coordinates, respectively, of each vertex.
  3402. // Convert this to an array of objects with x and y coordinates.
  3403. const rawVertices = dict.getArray("Vertices");
  3404. if (!Array.isArray(rawVertices)) {
  3405. return;
  3406. }
  3407. for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
  3408. this.data.vertices.push({
  3409. x: rawVertices[i],
  3410. y: rawVertices[i + 1],
  3411. });
  3412. }
  3413. if (!this.appearance) {
  3414. // The default stroke color is black.
  3415. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  3416. const strokeAlpha = dict.get("CA");
  3417. const borderWidth = this.borderStyle.width || 1,
  3418. borderAdjust = 2 * borderWidth;
  3419. // If the /Rect-entry is empty/wrong, create a fallback rectangle so that
  3420. // we get similar rendering/highlighting behaviour as in Adobe Reader.
  3421. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  3422. for (const vertex of this.data.vertices) {
  3423. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  3424. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  3425. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  3426. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  3427. }
  3428. if (!Util.intersect(this.rectangle, bbox)) {
  3429. this.rectangle = bbox;
  3430. }
  3431. this._setDefaultAppearance({
  3432. xref,
  3433. extra: `${borderWidth} w`,
  3434. strokeColor,
  3435. strokeAlpha,
  3436. pointsCallback: (buffer, points) => {
  3437. const vertices = this.data.vertices;
  3438. for (let i = 0, ii = vertices.length; i < ii; i++) {
  3439. buffer.push(
  3440. `${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`
  3441. );
  3442. }
  3443. buffer.push("S");
  3444. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3445. },
  3446. });
  3447. }
  3448. }
  3449. }
  3450. class PolygonAnnotation extends PolylineAnnotation {
  3451. constructor(params) {
  3452. // Polygons are specific forms of polylines, so reuse their logic.
  3453. super(params);
  3454. this.data.annotationType = AnnotationType.POLYGON;
  3455. }
  3456. }
  3457. class CaretAnnotation extends MarkupAnnotation {
  3458. constructor(params) {
  3459. super(params);
  3460. this.data.annotationType = AnnotationType.CARET;
  3461. }
  3462. }
  3463. class InkAnnotation extends MarkupAnnotation {
  3464. constructor(params) {
  3465. super(params);
  3466. const { dict, xref } = params;
  3467. this.data.annotationType = AnnotationType.INK;
  3468. this.data.inkLists = [];
  3469. const rawInkLists = dict.getArray("InkList");
  3470. if (!Array.isArray(rawInkLists)) {
  3471. return;
  3472. }
  3473. for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
  3474. // The raw ink lists array contains arrays of numbers representing
  3475. // the alternating horizontal and vertical coordinates, respectively,
  3476. // of each vertex. Convert this to an array of objects with x and y
  3477. // coordinates.
  3478. this.data.inkLists.push([]);
  3479. for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
  3480. this.data.inkLists[i].push({
  3481. x: xref.fetchIfRef(rawInkLists[i][j]),
  3482. y: xref.fetchIfRef(rawInkLists[i][j + 1]),
  3483. });
  3484. }
  3485. }
  3486. if (!this.appearance) {
  3487. // The default stroke color is black.
  3488. const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
  3489. const strokeAlpha = dict.get("CA");
  3490. const borderWidth = this.borderStyle.width || 1,
  3491. borderAdjust = 2 * borderWidth;
  3492. // If the /Rect-entry is empty/wrong, create a fallback rectangle so that
  3493. // we get similar rendering/highlighting behaviour as in Adobe Reader.
  3494. const bbox = [Infinity, Infinity, -Infinity, -Infinity];
  3495. for (const inkLists of this.data.inkLists) {
  3496. for (const vertex of inkLists) {
  3497. bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
  3498. bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
  3499. bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
  3500. bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
  3501. }
  3502. }
  3503. if (!Util.intersect(this.rectangle, bbox)) {
  3504. this.rectangle = bbox;
  3505. }
  3506. this._setDefaultAppearance({
  3507. xref,
  3508. extra: `${borderWidth} w`,
  3509. strokeColor,
  3510. strokeAlpha,
  3511. pointsCallback: (buffer, points) => {
  3512. // According to the specification, see "12.5.6.13 Ink Annotations":
  3513. // When drawn, the points shall be connected by straight lines or
  3514. // curves in an implementation-dependent way.
  3515. // In order to simplify things, we utilize straight lines for now.
  3516. for (const inkList of this.data.inkLists) {
  3517. for (let i = 0, ii = inkList.length; i < ii; i++) {
  3518. buffer.push(
  3519. `${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`
  3520. );
  3521. }
  3522. buffer.push("S");
  3523. }
  3524. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3525. },
  3526. });
  3527. }
  3528. }
  3529. static createNewDict(annotation, xref, { apRef, ap }) {
  3530. const { paths, rect, rotation } = annotation;
  3531. const ink = new Dict(xref);
  3532. ink.set("Type", Name.get("Annot"));
  3533. ink.set("Subtype", Name.get("Ink"));
  3534. ink.set("CreationDate", `D:${getModificationDate()}`);
  3535. ink.set("Rect", rect);
  3536. ink.set(
  3537. "InkList",
  3538. paths.map(p => p.points)
  3539. );
  3540. ink.set("F", 4);
  3541. ink.set("Border", [0, 0, 0]);
  3542. ink.set("Rotate", rotation);
  3543. const n = new Dict(xref);
  3544. ink.set("AP", n);
  3545. if (apRef) {
  3546. n.set("N", apRef);
  3547. } else {
  3548. n.set("N", ap);
  3549. }
  3550. return ink;
  3551. }
  3552. static async createNewAppearanceStream(annotation, xref, params) {
  3553. const { color, rect, rotation, paths, thickness, opacity } = annotation;
  3554. const [x1, y1, x2, y2] = rect;
  3555. let w = x2 - x1;
  3556. let h = y2 - y1;
  3557. if (rotation % 180 !== 0) {
  3558. [w, h] = [h, w];
  3559. }
  3560. const appearanceBuffer = [
  3561. `${thickness} w 1 J 1 j`,
  3562. `${getPdfColor(color, /* isFill */ false)}`,
  3563. ];
  3564. if (opacity !== 1) {
  3565. appearanceBuffer.push("/R0 gs");
  3566. }
  3567. const buffer = [];
  3568. for (const { bezier } of paths) {
  3569. buffer.length = 0;
  3570. buffer.push(
  3571. `${numberToString(bezier[0])} ${numberToString(bezier[1])} m`
  3572. );
  3573. for (let i = 2, ii = bezier.length; i < ii; i += 6) {
  3574. const curve = bezier
  3575. .slice(i, i + 6)
  3576. .map(numberToString)
  3577. .join(" ");
  3578. buffer.push(`${curve} c`);
  3579. }
  3580. buffer.push("S");
  3581. appearanceBuffer.push(buffer.join("\n"));
  3582. }
  3583. const appearance = appearanceBuffer.join("\n");
  3584. const appearanceStreamDict = new Dict(xref);
  3585. appearanceStreamDict.set("FormType", 1);
  3586. appearanceStreamDict.set("Subtype", Name.get("Form"));
  3587. appearanceStreamDict.set("Type", Name.get("XObject"));
  3588. appearanceStreamDict.set("BBox", [0, 0, w, h]);
  3589. appearanceStreamDict.set("Length", appearance.length);
  3590. if (rotation) {
  3591. const matrix = getRotationMatrix(rotation, w, h);
  3592. appearanceStreamDict.set("Matrix", matrix);
  3593. }
  3594. if (opacity !== 1) {
  3595. const resources = new Dict(xref);
  3596. const extGState = new Dict(xref);
  3597. const r0 = new Dict(xref);
  3598. r0.set("CA", opacity);
  3599. r0.set("Type", Name.get("ExtGState"));
  3600. extGState.set("R0", r0);
  3601. resources.set("ExtGState", extGState);
  3602. appearanceStreamDict.set("Resources", resources);
  3603. }
  3604. const ap = new StringStream(appearance);
  3605. ap.dict = appearanceStreamDict;
  3606. return ap;
  3607. }
  3608. }
  3609. class HighlightAnnotation extends MarkupAnnotation {
  3610. constructor(params) {
  3611. super(params);
  3612. const { dict, xref } = params;
  3613. this.data.annotationType = AnnotationType.HIGHLIGHT;
  3614. const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
  3615. if (quadPoints) {
  3616. const resources =
  3617. this.appearance && this.appearance.dict.get("Resources");
  3618. if (!this.appearance || !(resources && resources.has("ExtGState"))) {
  3619. if (this.appearance) {
  3620. // Workaround for cases where there's no /ExtGState-entry directly
  3621. // available, e.g. when the appearance stream contains a /XObject of
  3622. // the /Form-type, since that causes the highlighting to completely
  3623. // obscure the PDF content below it (fixes issue13242.pdf).
  3624. warn("HighlightAnnotation - ignoring built-in appearance stream.");
  3625. }
  3626. // Default color is yellow in Acrobat Reader
  3627. const fillColor = this.color ? getPdfColorArray(this.color) : [1, 1, 0];
  3628. const fillAlpha = dict.get("CA");
  3629. this._setDefaultAppearance({
  3630. xref,
  3631. fillColor,
  3632. blendMode: "Multiply",
  3633. fillAlpha,
  3634. pointsCallback: (buffer, points) => {
  3635. buffer.push(
  3636. `${points[0].x} ${points[0].y} m`,
  3637. `${points[1].x} ${points[1].y} l`,
  3638. `${points[3].x} ${points[3].y} l`,
  3639. `${points[2].x} ${points[2].y} l`,
  3640. "f"
  3641. );
  3642. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3643. },
  3644. });
  3645. }
  3646. } else {
  3647. this.data.hasPopup = false;
  3648. }
  3649. }
  3650. }
  3651. class UnderlineAnnotation extends MarkupAnnotation {
  3652. constructor(params) {
  3653. super(params);
  3654. const { dict, xref } = params;
  3655. this.data.annotationType = AnnotationType.UNDERLINE;
  3656. const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
  3657. if (quadPoints) {
  3658. if (!this.appearance) {
  3659. // Default color is black
  3660. const strokeColor = this.color
  3661. ? getPdfColorArray(this.color)
  3662. : [0, 0, 0];
  3663. const strokeAlpha = dict.get("CA");
  3664. this._setDefaultAppearance({
  3665. xref,
  3666. extra: "[] 0 d 1 w",
  3667. strokeColor,
  3668. strokeAlpha,
  3669. pointsCallback: (buffer, points) => {
  3670. buffer.push(
  3671. `${points[2].x} ${points[2].y} m`,
  3672. `${points[3].x} ${points[3].y} l`,
  3673. "S"
  3674. );
  3675. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3676. },
  3677. });
  3678. }
  3679. } else {
  3680. this.data.hasPopup = false;
  3681. }
  3682. }
  3683. }
  3684. class SquigglyAnnotation extends MarkupAnnotation {
  3685. constructor(params) {
  3686. super(params);
  3687. const { dict, xref } = params;
  3688. this.data.annotationType = AnnotationType.SQUIGGLY;
  3689. const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
  3690. if (quadPoints) {
  3691. if (!this.appearance) {
  3692. // Default color is black
  3693. const strokeColor = this.color
  3694. ? getPdfColorArray(this.color)
  3695. : [0, 0, 0];
  3696. const strokeAlpha = dict.get("CA");
  3697. this._setDefaultAppearance({
  3698. xref,
  3699. extra: "[] 0 d 1 w",
  3700. strokeColor,
  3701. strokeAlpha,
  3702. pointsCallback: (buffer, points) => {
  3703. const dy = (points[0].y - points[2].y) / 6;
  3704. let shift = dy;
  3705. let x = points[2].x;
  3706. const y = points[2].y;
  3707. const xEnd = points[3].x;
  3708. buffer.push(`${x} ${y + shift} m`);
  3709. do {
  3710. x += 2;
  3711. shift = shift === 0 ? dy : 0;
  3712. buffer.push(`${x} ${y + shift} l`);
  3713. } while (x < xEnd);
  3714. buffer.push("S");
  3715. return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
  3716. },
  3717. });
  3718. }
  3719. } else {
  3720. this.data.hasPopup = false;
  3721. }
  3722. }
  3723. }
  3724. class StrikeOutAnnotation extends MarkupAnnotation {
  3725. constructor(params) {
  3726. super(params);
  3727. const { dict, xref } = params;
  3728. this.data.annotationType = AnnotationType.STRIKEOUT;
  3729. const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
  3730. if (quadPoints) {
  3731. if (!this.appearance) {
  3732. // Default color is black
  3733. const strokeColor = this.color
  3734. ? getPdfColorArray(this.color)
  3735. : [0, 0, 0];
  3736. const strokeAlpha = dict.get("CA");
  3737. this._setDefaultAppearance({
  3738. xref,
  3739. extra: "[] 0 d 1 w",
  3740. strokeColor,
  3741. strokeAlpha,
  3742. pointsCallback: (buffer, points) => {
  3743. buffer.push(
  3744. `${(points[0].x + points[2].x) / 2} ` +
  3745. `${(points[0].y + points[2].y) / 2} m`,
  3746. `${(points[1].x + points[3].x) / 2} ` +
  3747. `${(points[1].y + points[3].y) / 2} l`,
  3748. "S"
  3749. );
  3750. return [points[0].x, points[1].x, points[3].y, points[1].y];
  3751. },
  3752. });
  3753. }
  3754. } else {
  3755. this.data.hasPopup = false;
  3756. }
  3757. }
  3758. }
  3759. class StampAnnotation extends MarkupAnnotation {
  3760. constructor(params) {
  3761. super(params);
  3762. this.data.annotationType = AnnotationType.STAMP;
  3763. }
  3764. }
  3765. class FileAttachmentAnnotation extends MarkupAnnotation {
  3766. constructor(params) {
  3767. super(params);
  3768. const { dict, xref } = params;
  3769. const file = new FileSpec(dict.get("FS"), xref);
  3770. this.data.annotationType = AnnotationType.FILEATTACHMENT;
  3771. this.data.file = file.serializable;
  3772. const name = dict.get("Name");
  3773. this.data.name =
  3774. name instanceof Name ? stringToPDFString(name.name) : "PushPin";
  3775. }
  3776. }
  3777. export {
  3778. Annotation,
  3779. AnnotationBorderStyle,
  3780. AnnotationFactory,
  3781. getQuadPoints,
  3782. MarkupAnnotation,
  3783. PopupAnnotation,
  3784. };