12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304 |
- /* Copyright 2012 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- import {
- AnnotationActionEventType,
- AnnotationBorderStyleType,
- AnnotationEditorType,
- AnnotationFieldFlag,
- AnnotationFlag,
- AnnotationReplyType,
- AnnotationType,
- assert,
- BASELINE_FACTOR,
- FeatureTest,
- getModificationDate,
- IDENTITY_MATRIX,
- LINE_DESCENT_FACTOR,
- LINE_FACTOR,
- OPS,
- RenderingIntentFlag,
- shadow,
- stringToPDFString,
- unreachable,
- Util,
- warn,
- } from "../shared/util.js";
- import {
- collectActions,
- escapeString,
- getInheritableProperty,
- getRotationMatrix,
- isAscii,
- numberToString,
- stringToUTF16String,
- } from "./core_utils.js";
- import {
- createDefaultAppearance,
- FakeUnicodeFont,
- getPdfColor,
- parseDefaultAppearance,
- } from "./default_appearance.js";
- import { Dict, isName, Name, Ref, RefSet } from "./primitives.js";
- import { writeDict, writeObject } from "./writer.js";
- import { BaseStream } from "./base_stream.js";
- import { bidi } from "./bidi.js";
- import { Catalog } from "./catalog.js";
- import { ColorSpace } from "./colorspace.js";
- import { FileSpec } from "./file_spec.js";
- import { ObjectLoader } from "./object_loader.js";
- import { OperatorList } from "./operator_list.js";
- import { StringStream } from "./stream.js";
- import { XFAFactory } from "./xfa/factory.js";
- class AnnotationFactory {
- /**
- * Create an `Annotation` object of the correct type for the given reference
- * to an annotation dictionary. This yields a promise that is resolved when
- * the `Annotation` object is constructed.
- *
- * @param {XRef} xref
- * @param {Object} ref
- * @param {PDFManager} pdfManager
- * @param {Object} idFactory
- * @param {boolean} collectFields
- * @returns {Promise} A promise that is resolved with an {Annotation}
- * instance.
- */
- static create(xref, ref, pdfManager, idFactory, collectFields) {
- return Promise.all([
- pdfManager.ensureCatalog("acroForm"),
- // Only necessary to prevent the `pdfManager.docBaseUrl`-getter, used
- // with certain Annotations, from throwing and thus breaking parsing:
- pdfManager.ensureCatalog("baseUrl"),
- // Only necessary in the `Catalog.parseDestDictionary`-method,
- // when parsing "GoToE" actions:
- pdfManager.ensureCatalog("attachments"),
- pdfManager.ensureDoc("xfaDatasets"),
- collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1,
- ]).then(([acroForm, baseUrl, attachments, xfaDatasets, pageIndex]) =>
- pdfManager.ensure(this, "_create", [
- xref,
- ref,
- pdfManager,
- idFactory,
- acroForm,
- attachments,
- xfaDatasets,
- collectFields,
- pageIndex,
- ])
- );
- }
- /**
- * @private
- */
- static _create(
- xref,
- ref,
- pdfManager,
- idFactory,
- acroForm,
- attachments = null,
- xfaDatasets,
- collectFields,
- pageIndex = -1
- ) {
- const dict = xref.fetchIfRef(ref);
- if (!(dict instanceof Dict)) {
- return undefined;
- }
- const id =
- ref instanceof Ref ? ref.toString() : `annot_${idFactory.createObjId()}`;
- // Determine the annotation's subtype.
- let subtype = dict.get("Subtype");
- subtype = subtype instanceof Name ? subtype.name : null;
- const acroFormDict = acroForm instanceof Dict ? acroForm : Dict.empty;
- // Return the right annotation object based on the subtype and field type.
- const parameters = {
- xref,
- ref,
- dict,
- subtype,
- id,
- pdfManager,
- acroForm: acroFormDict,
- attachments,
- xfaDatasets,
- collectFields,
- needAppearances:
- !collectFields && acroFormDict.get("NeedAppearances") === true,
- pageIndex,
- isOffscreenCanvasSupported:
- FeatureTest.isOffscreenCanvasSupported &&
- pdfManager.evaluatorOptions.isOffscreenCanvasSupported,
- };
- switch (subtype) {
- case "Link":
- return new LinkAnnotation(parameters);
- case "Text":
- return new TextAnnotation(parameters);
- case "Widget":
- let fieldType = getInheritableProperty({ dict, key: "FT" });
- fieldType = fieldType instanceof Name ? fieldType.name : null;
- switch (fieldType) {
- case "Tx":
- return new TextWidgetAnnotation(parameters);
- case "Btn":
- return new ButtonWidgetAnnotation(parameters);
- case "Ch":
- return new ChoiceWidgetAnnotation(parameters);
- case "Sig":
- return new SignatureWidgetAnnotation(parameters);
- }
- warn(
- `Unimplemented widget field type "${fieldType}", ` +
- "falling back to base field type."
- );
- return new WidgetAnnotation(parameters);
- case "Popup":
- return new PopupAnnotation(parameters);
- case "FreeText":
- return new FreeTextAnnotation(parameters);
- case "Line":
- return new LineAnnotation(parameters);
- case "Square":
- return new SquareAnnotation(parameters);
- case "Circle":
- return new CircleAnnotation(parameters);
- case "PolyLine":
- return new PolylineAnnotation(parameters);
- case "Polygon":
- return new PolygonAnnotation(parameters);
- case "Caret":
- return new CaretAnnotation(parameters);
- case "Ink":
- return new InkAnnotation(parameters);
- case "Highlight":
- return new HighlightAnnotation(parameters);
- case "Underline":
- return new UnderlineAnnotation(parameters);
- case "Squiggly":
- return new SquigglyAnnotation(parameters);
- case "StrikeOut":
- return new StrikeOutAnnotation(parameters);
- case "Stamp":
- return new StampAnnotation(parameters);
- case "FileAttachment":
- return new FileAttachmentAnnotation(parameters);
- default:
- if (!collectFields) {
- if (!subtype) {
- warn("Annotation is missing the required /Subtype.");
- } else {
- warn(
- `Unimplemented annotation type "${subtype}", ` +
- "falling back to base annotation."
- );
- }
- }
- return new Annotation(parameters);
- }
- }
- static async _getPageIndex(xref, ref, pdfManager) {
- try {
- const annotDict = await xref.fetchIfRefAsync(ref);
- if (!(annotDict instanceof Dict)) {
- return -1;
- }
- const pageRef = annotDict.getRaw("P");
- if (!(pageRef instanceof Ref)) {
- return -1;
- }
- const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [
- pageRef,
- ]);
- return pageIndex;
- } catch (ex) {
- warn(`_getPageIndex: "${ex}".`);
- return -1;
- }
- }
- static async saveNewAnnotations(evaluator, task, annotations) {
- const xref = evaluator.xref;
- let baseFontRef;
- const dependencies = [];
- const promises = [];
- for (const annotation of annotations) {
- switch (annotation.annotationType) {
- case AnnotationEditorType.FREETEXT:
- if (!baseFontRef) {
- const baseFont = new Dict(xref);
- baseFont.set("BaseFont", Name.get("Helvetica"));
- baseFont.set("Type", Name.get("Font"));
- baseFont.set("Subtype", Name.get("Type1"));
- baseFont.set("Encoding", Name.get("WinAnsiEncoding"));
- const buffer = [];
- baseFontRef = xref.getNewTemporaryRef();
- writeObject(baseFontRef, baseFont, buffer, null);
- dependencies.push({ ref: baseFontRef, data: buffer.join("") });
- }
- promises.push(
- FreeTextAnnotation.createNewAnnotation(
- xref,
- annotation,
- dependencies,
- { evaluator, task, baseFontRef }
- )
- );
- break;
- case AnnotationEditorType.INK:
- promises.push(
- InkAnnotation.createNewAnnotation(xref, annotation, dependencies)
- );
- }
- }
- return {
- annotations: await Promise.all(promises),
- dependencies,
- };
- }
- static async printNewAnnotations(evaluator, task, annotations) {
- if (!annotations) {
- return null;
- }
- const xref = evaluator.xref;
- const promises = [];
- const isOffscreenCanvasSupported =
- FeatureTest.isOffscreenCanvasSupported &&
- evaluator.options.isOffscreenCanvasSupported;
- for (const annotation of annotations) {
- switch (annotation.annotationType) {
- case AnnotationEditorType.FREETEXT:
- promises.push(
- FreeTextAnnotation.createNewPrintAnnotation(xref, annotation, {
- evaluator,
- task,
- isOffscreenCanvasSupported,
- })
- );
- break;
- case AnnotationEditorType.INK:
- promises.push(
- InkAnnotation.createNewPrintAnnotation(xref, annotation, {
- isOffscreenCanvasSupported,
- })
- );
- break;
- }
- }
- return Promise.all(promises);
- }
- }
- function getRgbColor(color, defaultColor = new Uint8ClampedArray(3)) {
- if (!Array.isArray(color)) {
- return defaultColor;
- }
- const rgbColor = defaultColor || new Uint8ClampedArray(3);
- switch (color.length) {
- case 0: // Transparent, which we indicate with a null value
- return null;
- case 1: // Convert grayscale to RGB
- ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
- return rgbColor;
- case 3: // Convert RGB percentages to RGB
- ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
- return rgbColor;
- case 4: // Convert CMYK to RGB
- ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
- return rgbColor;
- default:
- return defaultColor;
- }
- }
- function getPdfColorArray(color) {
- return Array.from(color, c => c / 255);
- }
- function getQuadPoints(dict, rect) {
- // The region is described as a number of quadrilaterals.
- // Each quadrilateral must consist of eight coordinates.
- const quadPoints = dict.getArray("QuadPoints");
- if (
- !Array.isArray(quadPoints) ||
- quadPoints.length === 0 ||
- quadPoints.length % 8 > 0
- ) {
- return null;
- }
- const quadPointsLists = [];
- for (let i = 0, ii = quadPoints.length / 8; i < ii; i++) {
- // Each series of eight numbers represents the coordinates for one
- // quadrilateral in the order [x1, y1, x2, y2, x3, y3, x4, y4].
- // Convert this to an array of objects with x and y coordinates.
- let minX = Infinity,
- maxX = -Infinity,
- minY = Infinity,
- maxY = -Infinity;
- for (let j = i * 8, jj = i * 8 + 8; j < jj; j += 2) {
- const x = quadPoints[j];
- const y = quadPoints[j + 1];
- minX = Math.min(x, minX);
- maxX = Math.max(x, maxX);
- minY = Math.min(y, minY);
- maxY = Math.max(y, maxY);
- }
- // The quadpoints should be ignored if any coordinate in the array
- // lies outside the region specified by the rectangle. The rectangle
- // can be `null` for markup annotations since their rectangle may be
- // incorrect (fixes bug 1538111).
- if (
- rect !== null &&
- (minX < rect[0] || maxX > rect[2] || minY < rect[1] || maxY > rect[3])
- ) {
- return null;
- }
- // The PDF specification states in section 12.5.6.10 (figure 64) that the
- // order of the quadpoints should be bottom left, bottom right, top right
- // and top left. However, in practice PDF files use a different order,
- // namely bottom left, bottom right, top left and top right (this is also
- // mentioned on https://github.com/highkite/pdfAnnotate#QuadPoints), so
- // this is the actual order we should work with. However, the situation is
- // even worse since Adobe's own applications and other applications violate
- // the specification and create annotations with other orders, namely top
- // left, top right, bottom left and bottom right or even top left,
- // top right, bottom right and bottom left. To avoid inconsistency and
- // broken rendering, we normalize all lists to put the quadpoints in the
- // same standard order (see https://stackoverflow.com/a/10729881).
- quadPointsLists.push([
- { x: minX, y: maxY },
- { x: maxX, y: maxY },
- { x: minX, y: minY },
- { x: maxX, y: minY },
- ]);
- }
- return quadPointsLists;
- }
- function getTransformMatrix(rect, bbox, matrix) {
- // 12.5.5: Algorithm: Appearance streams
- const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox(
- bbox,
- matrix
- );
- if (minX === maxX || minY === maxY) {
- // From real-life file, bbox was [0, 0, 0, 0]. In this case,
- // just apply the transform for rect
- return [1, 0, 0, 1, rect[0], rect[1]];
- }
- const xRatio = (rect[2] - rect[0]) / (maxX - minX);
- const yRatio = (rect[3] - rect[1]) / (maxY - minY);
- return [
- xRatio,
- 0,
- 0,
- yRatio,
- rect[0] - minX * xRatio,
- rect[1] - minY * yRatio,
- ];
- }
- class Annotation {
- constructor(params) {
- const { dict, xref } = params;
- this.setTitle(dict.get("T"));
- this.setContents(dict.get("Contents"));
- this.setModificationDate(dict.get("M"));
- this.setFlags(dict.get("F"));
- this.setRectangle(dict.getArray("Rect"));
- this.setColor(dict.getArray("C"));
- this.setBorderStyle(dict);
- this.setAppearance(dict);
- this.setOptionalContent(dict);
- const MK = dict.get("MK");
- this.setBorderAndBackgroundColors(MK);
- this.setRotation(MK);
- this._streams = [];
- if (this.appearance) {
- this._streams.push(this.appearance);
- }
- // Expose public properties using a data object.
- this.data = {
- annotationFlags: this.flags,
- borderStyle: this.borderStyle,
- color: this.color,
- backgroundColor: this.backgroundColor,
- borderColor: this.borderColor,
- rotation: this.rotation,
- contentsObj: this._contents,
- hasAppearance: !!this.appearance,
- id: params.id,
- modificationDate: this.modificationDate,
- rect: this.rectangle,
- subtype: params.subtype,
- hasOwnCanvas: false,
- };
- if (params.collectFields) {
- // Fields can act as container for other fields and have
- // some actions even if no Annotation inherit from them.
- // Those fields can be referenced by CO (calculation order).
- const kids = dict.get("Kids");
- if (Array.isArray(kids)) {
- const kidIds = [];
- for (const kid of kids) {
- if (kid instanceof Ref) {
- kidIds.push(kid.toString());
- }
- }
- if (kidIds.length !== 0) {
- this.data.kidIds = kidIds;
- }
- }
- this.data.actions = collectActions(xref, dict, AnnotationActionEventType);
- this.data.fieldName = this._constructFieldName(dict);
- this.data.pageIndex = params.pageIndex;
- }
- this._isOffscreenCanvasSupported = params.isOffscreenCanvasSupported;
- this._fallbackFontDict = null;
- this._needAppearances = false;
- }
- /**
- * @private
- */
- _hasFlag(flags, flag) {
- return !!(flags & flag);
- }
- /**
- * @private
- */
- _isViewable(flags) {
- return (
- !this._hasFlag(flags, AnnotationFlag.INVISIBLE) &&
- !this._hasFlag(flags, AnnotationFlag.NOVIEW)
- );
- }
- /**
- * @private
- */
- _isPrintable(flags) {
- return (
- this._hasFlag(flags, AnnotationFlag.PRINT) &&
- !this._hasFlag(flags, AnnotationFlag.INVISIBLE)
- );
- }
- /**
- * Check if the annotation must be displayed by taking into account
- * the value found in the annotationStorage which may have been set
- * through JS.
- *
- * @public
- * @memberof Annotation
- * @param {AnnotationStorage} [annotationStorage] - Storage for annotation
- */
- mustBeViewed(annotationStorage) {
- const storageEntry =
- annotationStorage && annotationStorage.get(this.data.id);
- if (storageEntry && storageEntry.hidden !== undefined) {
- return !storageEntry.hidden;
- }
- return this.viewable && !this._hasFlag(this.flags, AnnotationFlag.HIDDEN);
- }
- /**
- * Check if the annotation must be printed by taking into account
- * the value found in the annotationStorage which may have been set
- * through JS.
- *
- * @public
- * @memberof Annotation
- * @param {AnnotationStorage} [annotationStorage] - Storage for annotation
- */
- mustBePrinted(annotationStorage) {
- const storageEntry =
- annotationStorage && annotationStorage.get(this.data.id);
- if (storageEntry && storageEntry.print !== undefined) {
- return storageEntry.print;
- }
- return this.printable;
- }
- /**
- * @type {boolean}
- */
- get viewable() {
- if (this.data.quadPoints === null) {
- return false;
- }
- if (this.flags === 0) {
- return true;
- }
- return this._isViewable(this.flags);
- }
- /**
- * @type {boolean}
- */
- get printable() {
- if (this.data.quadPoints === null) {
- return false;
- }
- if (this.flags === 0) {
- return false;
- }
- return this._isPrintable(this.flags);
- }
- /**
- * @private
- */
- _parseStringHelper(data) {
- const str = typeof data === "string" ? stringToPDFString(data) : "";
- const dir = str && bidi(str).dir === "rtl" ? "rtl" : "ltr";
- return { str, dir };
- }
- setDefaultAppearance(params) {
- const defaultAppearance =
- getInheritableProperty({ dict: params.dict, key: "DA" }) ||
- params.acroForm.get("DA");
- this._defaultAppearance =
- typeof defaultAppearance === "string" ? defaultAppearance : "";
- this.data.defaultAppearanceData = parseDefaultAppearance(
- this._defaultAppearance
- );
- }
- /**
- * Set the title.
- *
- * @param {string} title - The title of the annotation, used e.g. with
- * PopupAnnotations.
- */
- setTitle(title) {
- this._title = this._parseStringHelper(title);
- }
- /**
- * Set the contents.
- *
- * @param {string} contents - Text to display for the annotation or, if the
- * type of annotation does not display text, a
- * description of the annotation's contents
- */
- setContents(contents) {
- this._contents = this._parseStringHelper(contents);
- }
- /**
- * Set the modification date.
- *
- * @public
- * @memberof Annotation
- * @param {string} modificationDate - PDF date string that indicates when the
- * annotation was last modified
- */
- setModificationDate(modificationDate) {
- this.modificationDate =
- typeof modificationDate === "string" ? modificationDate : null;
- }
- /**
- * Set the flags.
- *
- * @public
- * @memberof Annotation
- * @param {number} flags - Unsigned 32-bit integer specifying annotation
- * characteristics
- * @see {@link shared/util.js}
- */
- setFlags(flags) {
- this.flags = Number.isInteger(flags) && flags > 0 ? flags : 0;
- }
- /**
- * Check if a provided flag is set.
- *
- * @public
- * @memberof Annotation
- * @param {number} flag - Hexadecimal representation for an annotation
- * characteristic
- * @returns {boolean}
- * @see {@link shared/util.js}
- */
- hasFlag(flag) {
- return this._hasFlag(this.flags, flag);
- }
- /**
- * Set the rectangle.
- *
- * @public
- * @memberof Annotation
- * @param {Array} rectangle - The rectangle array with exactly four entries
- */
- setRectangle(rectangle) {
- if (Array.isArray(rectangle) && rectangle.length === 4) {
- this.rectangle = Util.normalizeRect(rectangle);
- } else {
- this.rectangle = [0, 0, 0, 0];
- }
- }
- /**
- * Set the color and take care of color space conversion.
- * The default value is black, in RGB color space.
- *
- * @public
- * @memberof Annotation
- * @param {Array} color - The color array containing either 0
- * (transparent), 1 (grayscale), 3 (RGB) or
- * 4 (CMYK) elements
- */
- setColor(color) {
- this.color = getRgbColor(color);
- }
- /**
- * Set the line endings; should only be used with specific annotation types.
- * @param {Array} lineEndings - The line endings array.
- */
- setLineEndings(lineEndings) {
- this.lineEndings = ["None", "None"]; // The default values.
- if (Array.isArray(lineEndings) && lineEndings.length === 2) {
- for (let i = 0; i < 2; i++) {
- const obj = lineEndings[i];
- if (obj instanceof Name) {
- switch (obj.name) {
- case "None":
- continue;
- case "Square":
- case "Circle":
- case "Diamond":
- case "OpenArrow":
- case "ClosedArrow":
- case "Butt":
- case "ROpenArrow":
- case "RClosedArrow":
- case "Slash":
- this.lineEndings[i] = obj.name;
- continue;
- }
- }
- warn(`Ignoring invalid lineEnding: ${obj}`);
- }
- }
- }
- setRotation(mk) {
- this.rotation = 0;
- if (mk instanceof Dict) {
- let angle = mk.get("R") || 0;
- if (Number.isInteger(angle) && angle !== 0) {
- angle %= 360;
- if (angle < 0) {
- angle += 360;
- }
- if (angle % 90 === 0) {
- this.rotation = angle;
- }
- }
- }
- }
- /**
- * Set the color for background and border if any.
- * The default values are transparent.
- *
- * @public
- * @memberof Annotation
- * @param {Dict} mk - The MK dictionary
- */
- setBorderAndBackgroundColors(mk) {
- if (mk instanceof Dict) {
- this.borderColor = getRgbColor(mk.getArray("BC"), null);
- this.backgroundColor = getRgbColor(mk.getArray("BG"), null);
- } else {
- this.borderColor = this.backgroundColor = null;
- }
- }
- /**
- * Set the border style (as AnnotationBorderStyle object).
- *
- * @public
- * @memberof Annotation
- * @param {Dict} borderStyle - The border style dictionary
- */
- setBorderStyle(borderStyle) {
- if (
- typeof PDFJSDev === "undefined" ||
- PDFJSDev.test("!PRODUCTION || TESTING")
- ) {
- assert(this.rectangle, "setRectangle must have been called previously.");
- }
- this.borderStyle = new AnnotationBorderStyle();
- if (!(borderStyle instanceof Dict)) {
- return;
- }
- if (borderStyle.has("BS")) {
- const dict = borderStyle.get("BS");
- const dictType = dict.get("Type");
- if (!dictType || isName(dictType, "Border")) {
- this.borderStyle.setWidth(dict.get("W"), this.rectangle);
- this.borderStyle.setStyle(dict.get("S"));
- this.borderStyle.setDashArray(dict.getArray("D"));
- }
- } else if (borderStyle.has("Border")) {
- const array = borderStyle.getArray("Border");
- if (Array.isArray(array) && array.length >= 3) {
- this.borderStyle.setHorizontalCornerRadius(array[0]);
- this.borderStyle.setVerticalCornerRadius(array[1]);
- this.borderStyle.setWidth(array[2], this.rectangle);
- if (array.length === 4) {
- // Dash array available
- this.borderStyle.setDashArray(array[3], /* forceStyle = */ true);
- }
- }
- } else {
- // There are no border entries in the dictionary. According to the
- // specification, we should draw a solid border of width 1 in that
- // case, but Adobe Reader did not implement that part of the
- // specification and instead draws no border at all, so we do the same.
- // See also https://github.com/mozilla/pdf.js/issues/6179.
- this.borderStyle.setWidth(0);
- }
- }
- /**
- * Set the (normal) appearance.
- *
- * @public
- * @memberof Annotation
- * @param {Dict} dict - The annotation's data dictionary
- */
- setAppearance(dict) {
- this.appearance = null;
- const appearanceStates = dict.get("AP");
- if (!(appearanceStates instanceof Dict)) {
- return;
- }
- // In case the normal appearance is a stream, then it is used directly.
- const normalAppearanceState = appearanceStates.get("N");
- if (normalAppearanceState instanceof BaseStream) {
- this.appearance = normalAppearanceState;
- return;
- }
- if (!(normalAppearanceState instanceof Dict)) {
- return;
- }
- // In case the normal appearance is a dictionary, the `AS` entry provides
- // the key of the stream in this dictionary.
- const as = dict.get("AS");
- if (!(as instanceof Name) || !normalAppearanceState.has(as.name)) {
- return;
- }
- this.appearance = normalAppearanceState.get(as.name);
- }
- setOptionalContent(dict) {
- this.oc = null;
- const oc = dict.get("OC");
- if (oc instanceof Name) {
- warn("setOptionalContent: Support for /Name-entry is not implemented.");
- } else if (oc instanceof Dict) {
- this.oc = oc;
- }
- }
- loadResources(keys, appearance) {
- return appearance.dict.getAsync("Resources").then(resources => {
- if (!resources) {
- return undefined;
- }
- const objectLoader = new ObjectLoader(resources, keys, resources.xref);
- return objectLoader.load().then(function () {
- return resources;
- });
- });
- }
- async getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- ) {
- const data = this.data;
- let appearance = this.appearance;
- const isUsingOwnCanvas = !!(
- this.data.hasOwnCanvas && intent & RenderingIntentFlag.DISPLAY
- );
- if (!appearance) {
- if (!isUsingOwnCanvas) {
- return {
- opList: new OperatorList(),
- separateForm: false,
- separateCanvas: false,
- };
- }
- appearance = new StringStream("");
- appearance.dict = new Dict();
- }
- const appearanceDict = appearance.dict;
- const resources = await this.loadResources(
- ["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"],
- appearance
- );
- const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];
- const matrix = appearanceDict.getArray("Matrix") || [1, 0, 0, 1, 0, 0];
- const transform = getTransformMatrix(data.rect, bbox, matrix);
- const opList = new OperatorList();
- let optionalContent;
- if (this.oc) {
- optionalContent = await evaluator.parseMarkedContentProps(
- this.oc,
- /* resources = */ null
- );
- }
- if (optionalContent !== undefined) {
- opList.addOp(OPS.beginMarkedContentProps, ["OC", optionalContent]);
- }
- opList.addOp(OPS.beginAnnotation, [
- data.id,
- data.rect,
- transform,
- matrix,
- isUsingOwnCanvas,
- ]);
- await evaluator.getOperatorList({
- stream: appearance,
- task,
- resources,
- operatorList: opList,
- fallbackFontDict: this._fallbackFontDict,
- });
- opList.addOp(OPS.endAnnotation, []);
- if (optionalContent !== undefined) {
- opList.addOp(OPS.endMarkedContent, []);
- }
- this.reset();
- return { opList, separateForm: false, separateCanvas: isUsingOwnCanvas };
- }
- async save(evaluator, task, annotationStorage) {
- return null;
- }
- get hasTextContent() {
- return false;
- }
- async extractTextContent(evaluator, task, viewBox) {
- if (!this.appearance) {
- return;
- }
- const resources = await this.loadResources(
- ["ExtGState", "Font", "Properties", "XObject"],
- this.appearance
- );
- const text = [];
- const buffer = [];
- const sink = {
- desiredSize: Math.Infinity,
- ready: true,
- enqueue(chunk, size) {
- for (const item of chunk.items) {
- buffer.push(item.str);
- if (item.hasEOL) {
- text.push(buffer.join(""));
- buffer.length = 0;
- }
- }
- },
- };
- await evaluator.getTextContent({
- stream: this.appearance,
- task,
- resources,
- includeMarkedContent: true,
- combineTextItems: true,
- sink,
- viewBox,
- });
- this.reset();
- if (buffer.length) {
- text.push(buffer.join(""));
- }
- if (text.length > 0) {
- this.data.textContent = text;
- }
- }
- /**
- * Get field data for usage in JS sandbox.
- *
- * Field object is defined here:
- * https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf#page=16
- *
- * @public
- * @memberof Annotation
- * @returns {Object | null}
- */
- getFieldObject() {
- if (this.data.kidIds) {
- return {
- id: this.data.id,
- actions: this.data.actions,
- name: this.data.fieldName,
- strokeColor: this.data.borderColor,
- fillColor: this.data.backgroundColor,
- type: "",
- kidIds: this.data.kidIds,
- page: this.data.pageIndex,
- rotation: this.rotation,
- };
- }
- return null;
- }
- /**
- * Reset the annotation.
- *
- * This involves resetting the various streams that are either cached on the
- * annotation instance or created during its construction.
- *
- * @public
- * @memberof Annotation
- */
- reset() {
- if (
- (typeof PDFJSDev === "undefined" ||
- PDFJSDev.test("!PRODUCTION || TESTING")) &&
- this.appearance &&
- !this._streams.includes(this.appearance)
- ) {
- unreachable("The appearance stream should always be reset.");
- }
- for (const stream of this._streams) {
- stream.reset();
- }
- }
- /**
- * Construct the (fully qualified) field name from the (partial) field
- * names of the field and its ancestors.
- *
- * @private
- * @memberof Annotation
- * @param {Dict} dict - Complete widget annotation dictionary
- * @returns {string}
- */
- _constructFieldName(dict) {
- // Both the `Parent` and `T` fields are optional. While at least one of
- // them should be provided, bad PDF generators may fail to do so.
- if (!dict.has("T") && !dict.has("Parent")) {
- warn("Unknown field name, falling back to empty field name.");
- return "";
- }
- // If no parent exists, the partial and fully qualified names are equal.
- if (!dict.has("Parent")) {
- return stringToPDFString(dict.get("T"));
- }
- // Form the fully qualified field name by appending the partial name to
- // the parent's fully qualified name, separated by a period.
- const fieldName = [];
- if (dict.has("T")) {
- fieldName.unshift(stringToPDFString(dict.get("T")));
- }
- let loopDict = dict;
- const visited = new RefSet();
- if (dict.objId) {
- visited.put(dict.objId);
- }
- while (loopDict.has("Parent")) {
- loopDict = loopDict.get("Parent");
- if (
- !(loopDict instanceof Dict) ||
- (loopDict.objId && visited.has(loopDict.objId))
- ) {
- // Even though it is not allowed according to the PDF specification,
- // bad PDF generators may provide a `Parent` entry that is not a
- // dictionary, but `null` for example (issue 8143).
- //
- // If parent has been already visited, it means that we're
- // in an infinite loop.
- break;
- }
- if (loopDict.objId) {
- visited.put(loopDict.objId);
- }
- if (loopDict.has("T")) {
- fieldName.unshift(stringToPDFString(loopDict.get("T")));
- }
- }
- return fieldName.join(".");
- }
- }
- /**
- * Contains all data regarding an annotation's border style.
- */
- class AnnotationBorderStyle {
- constructor() {
- this.width = 1;
- this.style = AnnotationBorderStyleType.SOLID;
- this.dashArray = [3];
- this.horizontalCornerRadius = 0;
- this.verticalCornerRadius = 0;
- }
- /**
- * Set the width.
- *
- * @public
- * @memberof AnnotationBorderStyle
- * @param {number} width - The width.
- * @param {Array} rect - The annotation `Rect` entry.
- */
- setWidth(width, rect = [0, 0, 0, 0]) {
- if (
- typeof PDFJSDev === "undefined" ||
- PDFJSDev.test("!PRODUCTION || TESTING")
- ) {
- assert(
- Array.isArray(rect) && rect.length === 4,
- "A valid `rect` parameter must be provided."
- );
- }
- // Some corrupt PDF generators may provide the width as a `Name`,
- // rather than as a number (fixes issue 10385).
- if (width instanceof Name) {
- this.width = 0; // This is consistent with the behaviour in Adobe Reader.
- return;
- }
- if (typeof width === "number") {
- if (width > 0) {
- const maxWidth = (rect[2] - rect[0]) / 2;
- const maxHeight = (rect[3] - rect[1]) / 2;
- // Ignore large `width`s, since they lead to the Annotation overflowing
- // the size set by the `Rect` entry thus causing the `annotationLayer`
- // to render it over the surrounding document (fixes bug1552113.pdf).
- if (
- maxWidth > 0 &&
- maxHeight > 0 &&
- (width > maxWidth || width > maxHeight)
- ) {
- warn(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
- width = 1;
- }
- }
- this.width = width;
- }
- }
- /**
- * Set the style.
- *
- * @public
- * @memberof AnnotationBorderStyle
- * @param {Name} style - The annotation style.
- * @see {@link shared/util.js}
- */
- setStyle(style) {
- if (!(style instanceof Name)) {
- return;
- }
- switch (style.name) {
- case "S":
- this.style = AnnotationBorderStyleType.SOLID;
- break;
- case "D":
- this.style = AnnotationBorderStyleType.DASHED;
- break;
- case "B":
- this.style = AnnotationBorderStyleType.BEVELED;
- break;
- case "I":
- this.style = AnnotationBorderStyleType.INSET;
- break;
- case "U":
- this.style = AnnotationBorderStyleType.UNDERLINE;
- break;
- default:
- break;
- }
- }
- /**
- * Set the dash array.
- *
- * @public
- * @memberof AnnotationBorderStyle
- * @param {Array} dashArray - The dash array with at least one element
- * @param {boolean} [forceStyle]
- */
- setDashArray(dashArray, forceStyle = false) {
- // We validate the dash array, but we do not use it because CSS does not
- // allow us to change spacing of dashes. For more information, visit
- // http://www.w3.org/TR/css3-background/#the-border-style.
- if (Array.isArray(dashArray) && dashArray.length > 0) {
- // According to the PDF specification: the elements in `dashArray`
- // shall be numbers that are nonnegative and not all equal to zero.
- let isValid = true;
- let allZeros = true;
- for (const element of dashArray) {
- const validNumber = +element >= 0;
- if (!validNumber) {
- isValid = false;
- break;
- } else if (element > 0) {
- allZeros = false;
- }
- }
- if (isValid && !allZeros) {
- this.dashArray = dashArray;
- if (forceStyle) {
- // Even though we cannot use the dash array in the display layer,
- // at least ensure that we use the correct border-style.
- this.setStyle(Name.get("D"));
- }
- } else {
- this.width = 0; // Adobe behavior when the array is invalid.
- }
- } else if (dashArray) {
- this.width = 0; // Adobe behavior when the array is invalid.
- }
- }
- /**
- * Set the horizontal corner radius (from a Border dictionary).
- *
- * @public
- * @memberof AnnotationBorderStyle
- * @param {number} radius - The horizontal corner radius.
- */
- setHorizontalCornerRadius(radius) {
- if (Number.isInteger(radius)) {
- this.horizontalCornerRadius = radius;
- }
- }
- /**
- * Set the vertical corner radius (from a Border dictionary).
- *
- * @public
- * @memberof AnnotationBorderStyle
- * @param {number} radius - The vertical corner radius.
- */
- setVerticalCornerRadius(radius) {
- if (Number.isInteger(radius)) {
- this.verticalCornerRadius = radius;
- }
- }
- }
- class MarkupAnnotation extends Annotation {
- constructor(params) {
- super(params);
- const { dict } = params;
- if (dict.has("IRT")) {
- const rawIRT = dict.getRaw("IRT");
- this.data.inReplyTo = rawIRT instanceof Ref ? rawIRT.toString() : null;
- const rt = dict.get("RT");
- this.data.replyType =
- rt instanceof Name ? rt.name : AnnotationReplyType.REPLY;
- }
- if (this.data.replyType === AnnotationReplyType.GROUP) {
- // Subordinate annotations in a group should inherit
- // the group attributes from the primary annotation.
- const parent = dict.get("IRT");
- this.setTitle(parent.get("T"));
- this.data.titleObj = this._title;
- this.setContents(parent.get("Contents"));
- this.data.contentsObj = this._contents;
- if (!parent.has("CreationDate")) {
- this.data.creationDate = null;
- } else {
- this.setCreationDate(parent.get("CreationDate"));
- this.data.creationDate = this.creationDate;
- }
- if (!parent.has("M")) {
- this.data.modificationDate = null;
- } else {
- this.setModificationDate(parent.get("M"));
- this.data.modificationDate = this.modificationDate;
- }
- this.data.hasPopup = parent.has("Popup");
- if (!parent.has("C")) {
- // Fall back to the default background color.
- this.data.color = null;
- } else {
- this.setColor(parent.getArray("C"));
- this.data.color = this.color;
- }
- } else {
- this.data.titleObj = this._title;
- this.setCreationDate(dict.get("CreationDate"));
- this.data.creationDate = this.creationDate;
- this.data.hasPopup = dict.has("Popup");
- if (!dict.has("C")) {
- // Fall back to the default background color.
- this.data.color = null;
- }
- }
- if (dict.has("RC")) {
- this.data.richText = XFAFactory.getRichTextAsHtml(dict.get("RC"));
- }
- }
- /**
- * Set the creation date.
- *
- * @public
- * @memberof MarkupAnnotation
- * @param {string} creationDate - PDF date string that indicates when the
- * annotation was originally created
- */
- setCreationDate(creationDate) {
- this.creationDate = typeof creationDate === "string" ? creationDate : null;
- }
- _setDefaultAppearance({
- xref,
- extra,
- strokeColor,
- fillColor,
- blendMode,
- strokeAlpha,
- fillAlpha,
- pointsCallback,
- }) {
- let minX = Number.MAX_VALUE;
- let minY = Number.MAX_VALUE;
- let maxX = Number.MIN_VALUE;
- let maxY = Number.MIN_VALUE;
- const buffer = ["q"];
- if (extra) {
- buffer.push(extra);
- }
- if (strokeColor) {
- buffer.push(`${strokeColor[0]} ${strokeColor[1]} ${strokeColor[2]} RG`);
- }
- if (fillColor) {
- buffer.push(`${fillColor[0]} ${fillColor[1]} ${fillColor[2]} rg`);
- }
- let pointsArray = this.data.quadPoints;
- if (!pointsArray) {
- // If there are no quadpoints, the rectangle should be used instead.
- // Convert the rectangle definition to a points array similar to how the
- // quadpoints are defined.
- pointsArray = [
- [
- { x: this.rectangle[0], y: this.rectangle[3] },
- { x: this.rectangle[2], y: this.rectangle[3] },
- { x: this.rectangle[0], y: this.rectangle[1] },
- { x: this.rectangle[2], y: this.rectangle[1] },
- ],
- ];
- }
- for (const points of pointsArray) {
- const [mX, MX, mY, MY] = pointsCallback(buffer, points);
- minX = Math.min(minX, mX);
- maxX = Math.max(maxX, MX);
- minY = Math.min(minY, mY);
- maxY = Math.max(maxY, MY);
- }
- buffer.push("Q");
- const formDict = new Dict(xref);
- const appearanceStreamDict = new Dict(xref);
- appearanceStreamDict.set("Subtype", Name.get("Form"));
- const appearanceStream = new StringStream(buffer.join(" "));
- appearanceStream.dict = appearanceStreamDict;
- formDict.set("Fm0", appearanceStream);
- const gsDict = new Dict(xref);
- if (blendMode) {
- gsDict.set("BM", Name.get(blendMode));
- }
- if (typeof strokeAlpha === "number") {
- gsDict.set("CA", strokeAlpha);
- }
- if (typeof fillAlpha === "number") {
- gsDict.set("ca", fillAlpha);
- }
- const stateDict = new Dict(xref);
- stateDict.set("GS0", gsDict);
- const resources = new Dict(xref);
- resources.set("ExtGState", stateDict);
- resources.set("XObject", formDict);
- const appearanceDict = new Dict(xref);
- appearanceDict.set("Resources", resources);
- const bbox = (this.data.rect = [minX, minY, maxX, maxY]);
- appearanceDict.set("BBox", bbox);
- this.appearance = new StringStream("/GS0 gs /Fm0 Do");
- this.appearance.dict = appearanceDict;
- // This method is only called if there is no appearance for the annotation,
- // so `this.appearance` is not pushed yet in the `Annotation` constructor.
- this._streams.push(this.appearance, appearanceStream);
- }
- static async createNewAnnotation(xref, annotation, dependencies, params) {
- const annotationRef = xref.getNewTemporaryRef();
- const ap = await this.createNewAppearanceStream(annotation, xref, params);
- const buffer = [];
- let annotationDict;
- if (ap) {
- const apRef = xref.getNewTemporaryRef();
- annotationDict = this.createNewDict(annotation, xref, { apRef });
- const transform = xref.encrypt
- ? xref.encrypt.createCipherTransform(apRef.num, apRef.gen)
- : null;
- writeObject(apRef, ap, buffer, transform);
- dependencies.push({ ref: apRef, data: buffer.join("") });
- } else {
- annotationDict = this.createNewDict(annotation, xref, {});
- }
- buffer.length = 0;
- const transform = xref.encrypt
- ? xref.encrypt.createCipherTransform(annotationRef.num, annotationRef.gen)
- : null;
- writeObject(annotationRef, annotationDict, buffer, transform);
- return { ref: annotationRef, data: buffer.join("") };
- }
- static async createNewPrintAnnotation(xref, annotation, params) {
- const ap = await this.createNewAppearanceStream(annotation, xref, params);
- const annotationDict = this.createNewDict(annotation, xref, { ap });
- return new this.prototype.constructor({
- dict: annotationDict,
- xref,
- isOffscreenCanvasSupported: params.isOffscreenCanvasSupported,
- });
- }
- }
- class WidgetAnnotation extends Annotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- const data = this.data;
- this.ref = params.ref;
- this._needAppearances = params.needAppearances;
- data.annotationType = AnnotationType.WIDGET;
- if (data.fieldName === undefined) {
- data.fieldName = this._constructFieldName(dict);
- }
- if (data.actions === undefined) {
- data.actions = collectActions(xref, dict, AnnotationActionEventType);
- }
- let fieldValue = getInheritableProperty({
- dict,
- key: "V",
- getArray: true,
- });
- data.fieldValue = this._decodeFormValue(fieldValue);
- const defaultFieldValue = getInheritableProperty({
- dict,
- key: "DV",
- getArray: true,
- });
- data.defaultFieldValue = this._decodeFormValue(defaultFieldValue);
- if (fieldValue === undefined && params.xfaDatasets) {
- // Try to figure out if we have something in the xfa dataset.
- const path = this._title.str;
- if (path) {
- this._hasValueFromXFA = true;
- data.fieldValue = fieldValue = params.xfaDatasets.getValue(path);
- }
- }
- // When no "V" entry exists, let the fieldValue fallback to the "DV" entry
- // (fixes issue13823.pdf).
- if (fieldValue === undefined && data.defaultFieldValue !== null) {
- data.fieldValue = data.defaultFieldValue;
- }
- data.alternativeText = stringToPDFString(dict.get("TU") || "");
- this.setDefaultAppearance(params);
- data.hasAppearance =
- (this._needAppearances &&
- data.fieldValue !== undefined &&
- data.fieldValue !== null) ||
- data.hasAppearance;
- const fieldType = getInheritableProperty({ dict, key: "FT" });
- data.fieldType = fieldType instanceof Name ? fieldType.name : null;
- const localResources = getInheritableProperty({ dict, key: "DR" });
- const acroFormResources = params.acroForm.get("DR");
- const appearanceResources =
- this.appearance && this.appearance.dict.get("Resources");
- this._fieldResources = {
- localResources,
- acroFormResources,
- appearanceResources,
- mergedResources: Dict.merge({
- xref,
- dictArray: [localResources, appearanceResources, acroFormResources],
- mergeSubDicts: true,
- }),
- };
- data.fieldFlags = getInheritableProperty({ dict, key: "Ff" });
- if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
- data.fieldFlags = 0;
- }
- data.readOnly = this.hasFieldFlag(AnnotationFieldFlag.READONLY);
- data.required = this.hasFieldFlag(AnnotationFieldFlag.REQUIRED);
- data.hidden = this._hasFlag(data.annotationFlags, AnnotationFlag.HIDDEN);
- }
- /**
- * Decode the given form value.
- *
- * @private
- * @memberof WidgetAnnotation
- * @param {Array<string>|Name|string} formValue - The (possibly encoded)
- * form value.
- * @returns {Array<string>|string|null}
- */
- _decodeFormValue(formValue) {
- if (Array.isArray(formValue)) {
- return formValue
- .filter(item => typeof item === "string")
- .map(item => stringToPDFString(item));
- } else if (formValue instanceof Name) {
- return stringToPDFString(formValue.name);
- } else if (typeof formValue === "string") {
- return stringToPDFString(formValue);
- }
- return null;
- }
- /**
- * Check if a provided field flag is set.
- *
- * @public
- * @memberof WidgetAnnotation
- * @param {number} flag - Hexadecimal representation for an annotation
- * field characteristic
- * @returns {boolean}
- * @see {@link shared/util.js}
- */
- hasFieldFlag(flag) {
- return !!(this.data.fieldFlags & flag);
- }
- getRotationMatrix(annotationStorage) {
- const storageEntry = annotationStorage
- ? annotationStorage.get(this.data.id)
- : undefined;
- let rotation = storageEntry && storageEntry.rotation;
- if (rotation === undefined) {
- rotation = this.rotation;
- }
- if (rotation === 0) {
- return IDENTITY_MATRIX;
- }
- const width = this.data.rect[2] - this.data.rect[0];
- const height = this.data.rect[3] - this.data.rect[1];
- return getRotationMatrix(rotation, width, height);
- }
- getBorderAndBackgroundAppearances(annotationStorage) {
- const storageEntry = annotationStorage
- ? annotationStorage.get(this.data.id)
- : undefined;
- let rotation = storageEntry && storageEntry.rotation;
- if (rotation === undefined) {
- rotation = this.rotation;
- }
- if (!this.backgroundColor && !this.borderColor) {
- return "";
- }
- const width = this.data.rect[2] - this.data.rect[0];
- const height = this.data.rect[3] - this.data.rect[1];
- const rect =
- rotation === 0 || rotation === 180
- ? `0 0 ${width} ${height} re`
- : `0 0 ${height} ${width} re`;
- let str = "";
- if (this.backgroundColor) {
- str = `${getPdfColor(
- this.backgroundColor,
- /* isFill */ true
- )} ${rect} f `;
- }
- if (this.borderColor) {
- const borderWidth = this.borderStyle.width || 1;
- str += `${borderWidth} w ${getPdfColor(
- this.borderColor,
- /* isFill */ false
- )} ${rect} S `;
- }
- return str;
- }
- async getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- ) {
- // Do not render form elements on the canvas when interactive forms are
- // enabled. The display layer is responsible for rendering them instead.
- if (renderForms && !(this instanceof SignatureWidgetAnnotation)) {
- return {
- opList: new OperatorList(),
- separateForm: true,
- separateCanvas: false,
- };
- }
- if (!this._hasText) {
- return super.getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- );
- }
- const content = await this._getAppearance(
- evaluator,
- task,
- intent,
- annotationStorage
- );
- if (this.appearance && content === null) {
- return super.getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- );
- }
- const opList = new OperatorList();
- // Even if there is an appearance stream, ignore it. This is the
- // behaviour used by Adobe Reader.
- if (!this._defaultAppearance || content === null) {
- return { opList, separateForm: false, separateCanvas: false };
- }
- const matrix = [1, 0, 0, 1, 0, 0];
- const bbox = [
- 0,
- 0,
- this.data.rect[2] - this.data.rect[0],
- this.data.rect[3] - this.data.rect[1],
- ];
- const transform = getTransformMatrix(this.data.rect, bbox, matrix);
- let optionalContent;
- if (this.oc) {
- optionalContent = await evaluator.parseMarkedContentProps(
- this.oc,
- /* resources = */ null
- );
- }
- if (optionalContent !== undefined) {
- opList.addOp(OPS.beginMarkedContentProps, ["OC", optionalContent]);
- }
- opList.addOp(OPS.beginAnnotation, [
- this.data.id,
- this.data.rect,
- transform,
- this.getRotationMatrix(annotationStorage),
- /* isUsingOwnCanvas = */ false,
- ]);
- const stream = new StringStream(content);
- await evaluator.getOperatorList({
- stream,
- task,
- resources: this._fieldResources.mergedResources,
- operatorList: opList,
- });
- opList.addOp(OPS.endAnnotation, []);
- if (optionalContent !== undefined) {
- opList.addOp(OPS.endMarkedContent, []);
- }
- return { opList, separateForm: false, separateCanvas: false };
- }
- _getMKDict(rotation) {
- const mk = new Dict(null);
- if (rotation) {
- mk.set("R", rotation);
- }
- if (this.borderColor) {
- mk.set("BC", getPdfColorArray(this.borderColor));
- }
- if (this.backgroundColor) {
- mk.set("BG", getPdfColorArray(this.backgroundColor));
- }
- return mk.size > 0 ? mk : null;
- }
- async save(evaluator, task, annotationStorage) {
- const storageEntry = annotationStorage
- ? annotationStorage.get(this.data.id)
- : undefined;
- let value = storageEntry && storageEntry.value;
- let rotation = storageEntry && storageEntry.rotation;
- if (value === this.data.fieldValue || value === undefined) {
- if (!this._hasValueFromXFA && rotation === undefined) {
- return null;
- }
- value = value || this.data.fieldValue;
- }
- // Value can be an array (with choice list and multiple selections)
- if (
- rotation === undefined &&
- !this._hasValueFromXFA &&
- Array.isArray(value) &&
- Array.isArray(this.data.fieldValue) &&
- value.length === this.data.fieldValue.length &&
- value.every((x, i) => x === this.data.fieldValue[i])
- ) {
- return null;
- }
- if (rotation === undefined) {
- rotation = this.rotation;
- }
- let appearance = null;
- if (!this._needAppearances) {
- appearance = await this._getAppearance(
- evaluator,
- task,
- RenderingIntentFlag.SAVE,
- annotationStorage
- );
- if (appearance === null) {
- // Appearance didn't change.
- return null;
- }
- } else {
- // No need to create an appearance: the pdf has the flag /NeedAppearances
- // which means that it's up to the reader to produce an appearance.
- }
- let needAppearances = false;
- if (appearance && appearance.needAppearances) {
- needAppearances = true;
- appearance = null;
- }
- const { xref } = evaluator;
- const originalDict = xref.fetchIfRef(this.ref);
- if (!(originalDict instanceof Dict)) {
- return null;
- }
- const dict = new Dict(xref);
- for (const key of originalDict.getKeys()) {
- if (key !== "AP") {
- dict.set(key, originalDict.getRaw(key));
- }
- }
- const xfa = {
- path: stringToPDFString(dict.get("T") || ""),
- value,
- };
- const encoder = val => {
- return isAscii(val)
- ? val
- : stringToUTF16String(val, /* bigEndian = */ true);
- };
- dict.set("V", Array.isArray(value) ? value.map(encoder) : encoder(value));
- const maybeMK = this._getMKDict(rotation);
- if (maybeMK) {
- dict.set("MK", maybeMK);
- }
- const encrypt = xref.encrypt;
- const originalTransform = encrypt
- ? encrypt.createCipherTransform(this.ref.num, this.ref.gen)
- : null;
- const buffer = [];
- const changes = [
- // data for the original object
- // V field changed + reference for new AP
- { ref: this.ref, data: "", xfa, needAppearances },
- ];
- if (appearance !== null) {
- const newRef = xref.getNewTemporaryRef();
- const AP = new Dict(xref);
- dict.set("AP", AP);
- AP.set("N", newRef);
- let newTransform = null;
- if (encrypt) {
- newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
- appearance = newTransform.encryptString(appearance);
- }
- const resources = this._getSaveFieldResources(xref);
- const appearanceStream = new StringStream(appearance);
- const appearanceDict = (appearanceStream.dict = new Dict(xref));
- appearanceDict.set("Length", appearance.length);
- appearanceDict.set("Subtype", Name.get("Form"));
- appearanceDict.set("Resources", resources);
- appearanceDict.set("BBox", [
- 0,
- 0,
- this.data.rect[2] - this.data.rect[0],
- this.data.rect[3] - this.data.rect[1],
- ]);
- const rotationMatrix = this.getRotationMatrix(annotationStorage);
- if (rotationMatrix !== IDENTITY_MATRIX) {
- // The matrix isn't the identity one.
- appearanceDict.set("Matrix", rotationMatrix);
- }
- writeObject(newRef, appearanceStream, buffer, newTransform);
- changes.push(
- // data for the new AP
- {
- ref: newRef,
- data: buffer.join(""),
- xfa: null,
- needAppearances: false,
- }
- );
- buffer.length = 0;
- }
- dict.set("M", `D:${getModificationDate()}`);
- writeObject(this.ref, dict, buffer, originalTransform);
- changes[0].data = buffer.join("");
- return changes;
- }
- async _getAppearance(evaluator, task, intent, annotationStorage) {
- const isPassword = this.hasFieldFlag(AnnotationFieldFlag.PASSWORD);
- if (isPassword) {
- return null;
- }
- const storageEntry = annotationStorage
- ? annotationStorage.get(this.data.id)
- : undefined;
- let value, rotation;
- if (storageEntry) {
- value = storageEntry.formattedValue || storageEntry.value;
- rotation = storageEntry.rotation;
- }
- if (
- rotation === undefined &&
- value === undefined &&
- !this._needAppearances
- ) {
- if (!this._hasValueFromXFA || this.appearance) {
- // The annotation hasn't been rendered so use the appearance.
- return null;
- }
- }
- // Empty or it has a trailing whitespace.
- const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
- if (value === undefined) {
- // The annotation has its value in XFA datasets but not in the V field.
- value = this.data.fieldValue;
- if (!value) {
- return `/Tx BMC q ${colors}Q EMC`;
- }
- }
- if (Array.isArray(value) && value.length === 1) {
- value = value[0];
- }
- assert(typeof value === "string", "Expected `value` to be a string.");
- if (!this.data.combo) {
- value = value.trim();
- } else {
- // The value is supposed to be one of the exportValue.
- const option =
- this.data.options.find(({ exportValue }) => value === exportValue) ||
- this.data.options[0];
- value = (option && option.displayValue) || "";
- }
- if (value === "") {
- // the field is empty: nothing to render
- return `/Tx BMC q ${colors}Q EMC`;
- }
- if (rotation === undefined) {
- rotation = this.rotation;
- }
- let lineCount = -1;
- let lines;
- // We could have a text containing for example some sequences of chars and
- // their diacritics (e.g. "é".normalize("NFKD") shows 1 char when it's 2).
- // Positioning diacritics is really something we don't want to do here.
- // So if a font has a glyph for a acute accent and one for "e" then we won't
- // get any encoding issues but we'll render "e" and then "´".
- // It's why we normalize the string. We use NFC to preserve the initial
- // string, (e.g. "²".normalize("NFC") === "²"
- // but "²".normalize("NFKC") === "2").
- //
- // TODO: it isn't a perfect solution, some chars like "ẹ́" will be
- // decomposed into two chars ("ẹ" and "´"), so we should detect such
- // situations and then use either FakeUnicodeFont or set the
- // /NeedAppearances flag.
- if (this.data.multiLine) {
- lines = value.split(/\r\n?|\n/).map(line => line.normalize("NFC"));
- lineCount = lines.length;
- } else {
- lines = [value.replace(/\r\n?|\n/, "").normalize("NFC")];
- }
- const defaultPadding = 1;
- const defaultHPadding = 2;
- let totalHeight = this.data.rect[3] - this.data.rect[1];
- let totalWidth = this.data.rect[2] - this.data.rect[0];
- if (rotation === 90 || rotation === 270) {
- [totalWidth, totalHeight] = [totalHeight, totalWidth];
- }
- if (!this._defaultAppearance) {
- // The DA is required and must be a string.
- // If there is no font named Helvetica in the resource dictionary,
- // the evaluator will fall back to a default font.
- // Doing so prevents exceptions and allows saving/printing
- // the file as expected.
- this.data.defaultAppearanceData = parseDefaultAppearance(
- (this._defaultAppearance = "/Helvetica 0 Tf 0 g")
- );
- }
- let font = await WidgetAnnotation._getFontData(
- evaluator,
- task,
- this.data.defaultAppearanceData,
- this._fieldResources.mergedResources
- );
- let defaultAppearance, fontSize, lineHeight;
- const encodedLines = [];
- let encodingError = false;
- for (const line of lines) {
- const encodedString = font.encodeString(line);
- if (encodedString.length > 1) {
- encodingError = true;
- }
- encodedLines.push(encodedString.join(""));
- }
- if (encodingError && intent & RenderingIntentFlag.SAVE) {
- // We don't have a way to render the field, so we just rely on the
- // /NeedAppearances trick to let the different sofware correctly render
- // this pdf.
- return { needAppearances: true };
- }
- // We check that the font is able to encode the string.
- if (encodingError && this._isOffscreenCanvasSupported) {
- // If it can't then we fallback on fake unicode font (mapped to sans-serif
- // for the rendering).
- // It means that a printed form can be rendered differently (it depends on
- // the sans-serif font) but at least we've something to render.
- // In an ideal world the associated font should correctly handle the
- // possible chars but a user can add a smiley or whatever.
- // We could try to embed a font but it means that we must have access
- // to the raw font file.
- const fontFamily = this.data.comb ? "monospace" : "sans-serif";
- const fakeUnicodeFont = new FakeUnicodeFont(evaluator.xref, fontFamily);
- const resources = fakeUnicodeFont.createFontResources(lines.join(""));
- const newFont = resources.getRaw("Font");
- if (this._fieldResources.mergedResources.has("Font")) {
- const oldFont = this._fieldResources.mergedResources.get("Font");
- for (const key of newFont.getKeys()) {
- oldFont.set(key, newFont.getRaw(key));
- }
- } else {
- this._fieldResources.mergedResources.set("Font", newFont);
- }
- const fontName = fakeUnicodeFont.fontName.name;
- font = await WidgetAnnotation._getFontData(
- evaluator,
- task,
- { fontName, fontSize: 0 },
- resources
- );
- for (let i = 0, ii = encodedLines.length; i < ii; i++) {
- encodedLines[i] = stringToUTF16String(lines[i]);
- }
- const savedDefaultAppearance = Object.assign(
- Object.create(null),
- this.data.defaultAppearanceData
- );
- this.data.defaultAppearanceData.fontSize = 0;
- this.data.defaultAppearanceData.fontName = fontName;
- [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(
- totalHeight - 2 * defaultPadding,
- totalWidth - 2 * defaultHPadding,
- value,
- font,
- lineCount
- );
- this.data.defaultAppearanceData = savedDefaultAppearance;
- } else {
- if (!this._isOffscreenCanvasSupported) {
- warn(
- "_getAppearance: OffscreenCanvas is not supported, annotation may not render correctly."
- );
- }
- [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(
- totalHeight - 2 * defaultPadding,
- totalWidth - 2 * defaultHPadding,
- value,
- font,
- lineCount
- );
- }
- let descent = font.descent;
- if (isNaN(descent)) {
- descent = BASELINE_FACTOR * lineHeight;
- } else {
- descent = Math.max(
- BASELINE_FACTOR * lineHeight,
- Math.abs(descent) * fontSize
- );
- }
- // Take into account the space we have to compute the default vertical
- // padding.
- const defaultVPadding = Math.min(
- Math.floor((totalHeight - fontSize) / 2),
- defaultPadding
- );
- const alignment = this.data.textAlignment;
- if (this.data.multiLine) {
- return this._getMultilineAppearance(
- defaultAppearance,
- encodedLines,
- font,
- fontSize,
- totalWidth,
- totalHeight,
- alignment,
- defaultHPadding,
- defaultVPadding,
- descent,
- lineHeight,
- annotationStorage
- );
- }
- if (this.data.comb) {
- return this._getCombAppearance(
- defaultAppearance,
- font,
- encodedLines[0],
- fontSize,
- totalWidth,
- totalHeight,
- defaultHPadding,
- defaultVPadding,
- descent,
- lineHeight,
- annotationStorage
- );
- }
- const bottomPadding = defaultVPadding + descent;
- if (alignment === 0 || alignment > 2) {
- // Left alignment: nothing to do
- return (
- `/Tx BMC q ${colors}BT ` +
- defaultAppearance +
- ` 1 0 0 1 ${numberToString(defaultHPadding)} ${numberToString(
- bottomPadding
- )} Tm (${escapeString(encodedLines[0])}) Tj` +
- " ET Q EMC"
- );
- }
- const prevInfo = { shift: 0 };
- const renderedText = this._renderText(
- encodedLines[0],
- font,
- fontSize,
- totalWidth,
- alignment,
- prevInfo,
- defaultHPadding,
- bottomPadding
- );
- return (
- `/Tx BMC q ${colors}BT ` +
- defaultAppearance +
- ` 1 0 0 1 0 0 Tm ${renderedText}` +
- " ET Q EMC"
- );
- }
- static async _getFontData(evaluator, task, appearanceData, resources) {
- const operatorList = new OperatorList();
- const initialState = {
- font: null,
- clone() {
- return this;
- },
- };
- const { fontName, fontSize } = appearanceData;
- await evaluator.handleSetFont(
- resources,
- [fontName && Name.get(fontName), fontSize],
- /* fontRef = */ null,
- operatorList,
- task,
- initialState,
- /* fallbackFontDict = */ null
- );
- return initialState.font;
- }
- _getTextWidth(text, font) {
- return (
- font
- .charsToGlyphs(text)
- .reduce((width, glyph) => width + glyph.width, 0) / 1000
- );
- }
- _computeFontSize(height, width, text, font, lineCount) {
- let { fontSize } = this.data.defaultAppearanceData;
- let lineHeight = (fontSize || 12) * LINE_FACTOR,
- numberOfLines = Math.round(height / lineHeight);
- if (!fontSize) {
- // A zero value for size means that the font shall be auto-sized:
- // its size shall be computed as a function of the height of the
- // annotation rectangle (see 12.7.3.3).
- const roundWithTwoDigits = x => Math.floor(x * 100) / 100;
- if (lineCount === -1) {
- const textWidth = this._getTextWidth(text, font);
- fontSize = roundWithTwoDigits(
- Math.min(
- height / LINE_FACTOR,
- textWidth > width ? width / textWidth : Infinity
- )
- );
- numberOfLines = 1;
- } else {
- const lines = text.split(/\r\n?|\n/);
- const cachedLines = [];
- for (const line of lines) {
- const encoded = font.encodeString(line).join("");
- const glyphs = font.charsToGlyphs(encoded);
- const positions = font.getCharPositions(encoded);
- cachedLines.push({
- line: encoded,
- glyphs,
- positions,
- });
- }
- const isTooBig = fsize => {
- // Return true when the text doesn't fit the given height.
- let totalHeight = 0;
- for (const cache of cachedLines) {
- const chunks = this._splitLine(null, font, fsize, width, cache);
- totalHeight += chunks.length * fsize;
- if (totalHeight > height) {
- return true;
- }
- }
- return false;
- };
- // Hard to guess how many lines there are.
- // The field may have been sized to have 10 lines
- // and the user entered only 1 so if we get font size from
- // height and number of lines then we'll get something too big.
- // So we compute a fake number of lines based on height and
- // a font size equal to 12 (this is the default font size in
- // Acrobat).
- // Then we'll adjust font size to what we have really.
- numberOfLines = Math.max(numberOfLines, lineCount);
- while (true) {
- lineHeight = height / numberOfLines;
- fontSize = roundWithTwoDigits(lineHeight / LINE_FACTOR);
- if (isTooBig(fontSize)) {
- numberOfLines++;
- continue;
- }
- break;
- }
- }
- const { fontName, fontColor } = this.data.defaultAppearanceData;
- this._defaultAppearance = createDefaultAppearance({
- fontSize,
- fontName,
- fontColor,
- });
- }
- return [this._defaultAppearance, fontSize, height / numberOfLines];
- }
- _renderText(
- text,
- font,
- fontSize,
- totalWidth,
- alignment,
- prevInfo,
- hPadding,
- vPadding
- ) {
- // TODO: we need to take into account (if possible) how the text
- // is rendered. For example in arabic, the cumulated width of some
- // glyphs isn't equal to the width of the rendered glyphs because
- // of ligatures.
- let shift;
- if (alignment === 1) {
- // Center
- const width = this._getTextWidth(text, font) * fontSize;
- shift = (totalWidth - width) / 2;
- } else if (alignment === 2) {
- // Right
- const width = this._getTextWidth(text, font) * fontSize;
- shift = totalWidth - width - hPadding;
- } else {
- shift = hPadding;
- }
- const shiftStr = numberToString(shift - prevInfo.shift);
- prevInfo.shift = shift;
- vPadding = numberToString(vPadding);
- return `${shiftStr} ${vPadding} Td (${escapeString(text)}) Tj`;
- }
- /**
- * @private
- */
- _getSaveFieldResources(xref) {
- if (
- typeof PDFJSDev === "undefined" ||
- PDFJSDev.test("!PRODUCTION || TESTING")
- ) {
- assert(
- this.data.defaultAppearanceData,
- "Expected `_defaultAppearanceData` to have been set."
- );
- }
- const { localResources, appearanceResources, acroFormResources } =
- this._fieldResources;
- const fontName =
- this.data.defaultAppearanceData &&
- this.data.defaultAppearanceData.fontName;
- if (!fontName) {
- return localResources || Dict.empty;
- }
- for (const resources of [localResources, appearanceResources]) {
- if (resources instanceof Dict) {
- const localFont = resources.get("Font");
- if (localFont instanceof Dict && localFont.has(fontName)) {
- return resources;
- }
- }
- }
- if (acroFormResources instanceof Dict) {
- const acroFormFont = acroFormResources.get("Font");
- if (acroFormFont instanceof Dict && acroFormFont.has(fontName)) {
- const subFontDict = new Dict(xref);
- subFontDict.set(fontName, acroFormFont.getRaw(fontName));
- const subResourcesDict = new Dict(xref);
- subResourcesDict.set("Font", subFontDict);
- return Dict.merge({
- xref,
- dictArray: [subResourcesDict, localResources],
- mergeSubDicts: true,
- });
- }
- }
- return localResources || Dict.empty;
- }
- getFieldObject() {
- return null;
- }
- }
- class TextWidgetAnnotation extends WidgetAnnotation {
- constructor(params) {
- super(params);
- this._hasText = true;
- const dict = params.dict;
- // The field value is always a string.
- if (typeof this.data.fieldValue !== "string") {
- this.data.fieldValue = "";
- }
- // Determine the alignment of text in the field.
- let alignment = getInheritableProperty({ dict, key: "Q" });
- if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
- alignment = null;
- }
- this.data.textAlignment = alignment;
- // Determine the maximum length of text in the field.
- let maximumLength = getInheritableProperty({ dict, key: "MaxLen" });
- if (!Number.isInteger(maximumLength) || maximumLength < 0) {
- maximumLength = 0;
- }
- this.data.maxLen = maximumLength;
- // Process field flags for the display layer.
- this.data.multiLine = this.hasFieldFlag(AnnotationFieldFlag.MULTILINE);
- this.data.comb =
- this.hasFieldFlag(AnnotationFieldFlag.COMB) &&
- !this.hasFieldFlag(AnnotationFieldFlag.MULTILINE) &&
- !this.hasFieldFlag(AnnotationFieldFlag.PASSWORD) &&
- !this.hasFieldFlag(AnnotationFieldFlag.FILESELECT) &&
- this.data.maxLen !== 0;
- this.data.doNotScroll = this.hasFieldFlag(AnnotationFieldFlag.DONOTSCROLL);
- }
- _getCombAppearance(
- defaultAppearance,
- font,
- text,
- fontSize,
- width,
- height,
- hPadding,
- vPadding,
- descent,
- lineHeight,
- annotationStorage
- ) {
- const combWidth = width / this.data.maxLen;
- // Empty or it has a trailing whitespace.
- const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
- const buf = [];
- const positions = font.getCharPositions(text);
- for (const [start, end] of positions) {
- buf.push(`(${escapeString(text.substring(start, end))}) Tj`);
- }
- const renderedComb = buf.join(` ${numberToString(combWidth)} 0 Td `);
- return (
- `/Tx BMC q ${colors}BT ` +
- defaultAppearance +
- ` 1 0 0 1 ${numberToString(hPadding)} ${numberToString(
- vPadding + descent
- )} Tm ${renderedComb}` +
- " ET Q EMC"
- );
- }
- _getMultilineAppearance(
- defaultAppearance,
- lines,
- font,
- fontSize,
- width,
- height,
- alignment,
- hPadding,
- vPadding,
- descent,
- lineHeight,
- annotationStorage
- ) {
- const buf = [];
- const totalWidth = width - 2 * hPadding;
- const prevInfo = { shift: 0 };
- for (let i = 0, ii = lines.length; i < ii; i++) {
- const line = lines[i];
- const chunks = this._splitLine(line, font, fontSize, totalWidth);
- for (let j = 0, jj = chunks.length; j < jj; j++) {
- const chunk = chunks[j];
- const vShift =
- i === 0 && j === 0 ? -vPadding - (lineHeight - descent) : -lineHeight;
- buf.push(
- this._renderText(
- chunk,
- font,
- fontSize,
- width,
- alignment,
- prevInfo,
- hPadding,
- vShift
- )
- );
- }
- }
- // Empty or it has a trailing whitespace.
- const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
- const renderedText = buf.join("\n");
- return (
- `/Tx BMC q ${colors}BT ` +
- defaultAppearance +
- ` 1 0 0 1 0 ${numberToString(height)} Tm ${renderedText}` +
- " ET Q EMC"
- );
- }
- _splitLine(line, font, fontSize, width, cache = {}) {
- line = cache.line || line;
- const glyphs = cache.glyphs || font.charsToGlyphs(line);
- if (glyphs.length <= 1) {
- // Nothing to split
- return [line];
- }
- const positions = cache.positions || font.getCharPositions(line);
- const scale = fontSize / 1000;
- const chunks = [];
- let lastSpacePosInStringStart = -1,
- lastSpacePosInStringEnd = -1,
- lastSpacePos = -1,
- startChunk = 0,
- currentWidth = 0;
- for (let i = 0, ii = glyphs.length; i < ii; i++) {
- const [start, end] = positions[i];
- const glyph = glyphs[i];
- const glyphWidth = glyph.width * scale;
- if (glyph.unicode === " ") {
- if (currentWidth + glyphWidth > width) {
- // We can break here
- chunks.push(line.substring(startChunk, start));
- startChunk = start;
- currentWidth = glyphWidth;
- lastSpacePosInStringStart = -1;
- lastSpacePos = -1;
- } else {
- currentWidth += glyphWidth;
- lastSpacePosInStringStart = start;
- lastSpacePosInStringEnd = end;
- lastSpacePos = i;
- }
- } else {
- if (currentWidth + glyphWidth > width) {
- // We must break to the last white position (if available)
- if (lastSpacePosInStringStart !== -1) {
- chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
- startChunk = lastSpacePosInStringEnd;
- i = lastSpacePos + 1;
- lastSpacePosInStringStart = -1;
- currentWidth = 0;
- } else {
- // Just break in the middle of the word
- chunks.push(line.substring(startChunk, start));
- startChunk = start;
- currentWidth = glyphWidth;
- }
- } else {
- currentWidth += glyphWidth;
- }
- }
- }
- if (startChunk < line.length) {
- chunks.push(line.substring(startChunk, line.length));
- }
- return chunks;
- }
- getFieldObject() {
- return {
- id: this.data.id,
- value: this.data.fieldValue,
- defaultValue: this.data.defaultFieldValue || "",
- multiline: this.data.multiLine,
- password: this.hasFieldFlag(AnnotationFieldFlag.PASSWORD),
- charLimit: this.data.maxLen,
- comb: this.data.comb,
- editable: !this.data.readOnly,
- hidden: this.data.hidden,
- name: this.data.fieldName,
- rect: this.data.rect,
- actions: this.data.actions,
- page: this.data.pageIndex,
- strokeColor: this.data.borderColor,
- fillColor: this.data.backgroundColor,
- rotation: this.rotation,
- type: "text",
- };
- }
- }
- class ButtonWidgetAnnotation extends WidgetAnnotation {
- constructor(params) {
- super(params);
- this.checkedAppearance = null;
- this.uncheckedAppearance = null;
- this.data.checkBox =
- !this.hasFieldFlag(AnnotationFieldFlag.RADIO) &&
- !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
- this.data.radioButton =
- this.hasFieldFlag(AnnotationFieldFlag.RADIO) &&
- !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
- this.data.pushButton = this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
- this.data.isTooltipOnly = false;
- if (this.data.checkBox) {
- this._processCheckBox(params);
- } else if (this.data.radioButton) {
- this._processRadioButton(params);
- } else if (this.data.pushButton) {
- this.data.hasOwnCanvas = true;
- this._processPushButton(params);
- } else {
- warn("Invalid field flags for button widget annotation");
- }
- }
- async getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- ) {
- if (this.data.pushButton) {
- return super.getOperatorList(
- evaluator,
- task,
- intent,
- false, // we use normalAppearance to render the button
- annotationStorage
- );
- }
- let value = null;
- let rotation = null;
- if (annotationStorage) {
- const storageEntry = annotationStorage.get(this.data.id);
- value = storageEntry ? storageEntry.value : null;
- rotation = storageEntry ? storageEntry.rotation : null;
- }
- if (value === null && this.appearance) {
- // Nothing in the annotationStorage.
- // But we've a default appearance so use it.
- return super.getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- );
- }
- if (value === null || value === undefined) {
- // There is no default appearance so use the one derived
- // from the field value.
- if (this.data.checkBox) {
- value = this.data.fieldValue === this.data.exportValue;
- } else {
- value = this.data.fieldValue === this.data.buttonValue;
- }
- }
- const appearance = value
- ? this.checkedAppearance
- : this.uncheckedAppearance;
- if (appearance) {
- const savedAppearance = this.appearance;
- const savedMatrix = appearance.dict.getArray("Matrix") || IDENTITY_MATRIX;
- if (rotation) {
- appearance.dict.set(
- "Matrix",
- this.getRotationMatrix(annotationStorage)
- );
- }
- this.appearance = appearance;
- const operatorList = super.getOperatorList(
- evaluator,
- task,
- intent,
- renderForms,
- annotationStorage
- );
- this.appearance = savedAppearance;
- appearance.dict.set("Matrix", savedMatrix);
- return operatorList;
- }
- // No appearance
- return {
- opList: new OperatorList(),
- separateForm: false,
- separateCanvas: false,
- };
- }
- async save(evaluator, task, annotationStorage) {
- if (this.data.checkBox) {
- return this._saveCheckbox(evaluator, task, annotationStorage);
- }
- if (this.data.radioButton) {
- return this._saveRadioButton(evaluator, task, annotationStorage);
- }
- // Nothing to save
- return null;
- }
- async _saveCheckbox(evaluator, task, annotationStorage) {
- if (!annotationStorage) {
- return null;
- }
- const storageEntry = annotationStorage.get(this.data.id);
- let rotation = storageEntry && storageEntry.rotation;
- let value = storageEntry && storageEntry.value;
- if (rotation === undefined) {
- if (value === undefined) {
- return null;
- }
- const defaultValue = this.data.fieldValue === this.data.exportValue;
- if (defaultValue === value) {
- return null;
- }
- }
- const dict = evaluator.xref.fetchIfRef(this.ref);
- if (!(dict instanceof Dict)) {
- return null;
- }
- if (rotation === undefined) {
- rotation = this.rotation;
- }
- if (value === undefined) {
- value = this.data.fieldValue === this.data.exportValue;
- }
- const xfa = {
- path: stringToPDFString(dict.get("T") || ""),
- value: value ? this.data.exportValue : "",
- };
- const name = Name.get(value ? this.data.exportValue : "Off");
- dict.set("V", name);
- dict.set("AS", name);
- dict.set("M", `D:${getModificationDate()}`);
- const maybeMK = this._getMKDict(rotation);
- if (maybeMK) {
- dict.set("MK", maybeMK);
- }
- const encrypt = evaluator.xref.encrypt;
- let originalTransform = null;
- if (encrypt) {
- originalTransform = encrypt.createCipherTransform(
- this.ref.num,
- this.ref.gen
- );
- }
- const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
- writeDict(dict, buffer, originalTransform);
- buffer.push("\nendobj\n");
- return [{ ref: this.ref, data: buffer.join(""), xfa }];
- }
- async _saveRadioButton(evaluator, task, annotationStorage) {
- if (!annotationStorage) {
- return null;
- }
- const storageEntry = annotationStorage.get(this.data.id);
- let rotation = storageEntry && storageEntry.rotation;
- let value = storageEntry && storageEntry.value;
- if (rotation === undefined) {
- if (value === undefined) {
- return null;
- }
- const defaultValue = this.data.fieldValue === this.data.buttonValue;
- if (defaultValue === value) {
- return null;
- }
- }
- const dict = evaluator.xref.fetchIfRef(this.ref);
- if (!(dict instanceof Dict)) {
- return null;
- }
- if (value === undefined) {
- value = this.data.fieldValue === this.data.buttonValue;
- }
- if (rotation === undefined) {
- rotation = this.rotation;
- }
- const xfa = {
- path: stringToPDFString(dict.get("T") || ""),
- value: value ? this.data.buttonValue : "",
- };
- const name = Name.get(value ? this.data.buttonValue : "Off");
- let parentBuffer = null;
- const encrypt = evaluator.xref.encrypt;
- if (value) {
- if (this.parent instanceof Ref) {
- const parent = evaluator.xref.fetch(this.parent);
- let parentTransform = null;
- if (encrypt) {
- parentTransform = encrypt.createCipherTransform(
- this.parent.num,
- this.parent.gen
- );
- }
- parent.set("V", name);
- parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
- writeDict(parent, parentBuffer, parentTransform);
- parentBuffer.push("\nendobj\n");
- } else if (this.parent instanceof Dict) {
- this.parent.set("V", name);
- }
- }
- dict.set("AS", name);
- dict.set("M", `D:${getModificationDate()}`);
- const maybeMK = this._getMKDict(rotation);
- if (maybeMK) {
- dict.set("MK", maybeMK);
- }
- let originalTransform = null;
- if (encrypt) {
- originalTransform = encrypt.createCipherTransform(
- this.ref.num,
- this.ref.gen
- );
- }
- const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
- writeDict(dict, buffer, originalTransform);
- buffer.push("\nendobj\n");
- const newRefs = [{ ref: this.ref, data: buffer.join(""), xfa }];
- if (parentBuffer !== null) {
- newRefs.push({
- ref: this.parent,
- data: parentBuffer.join(""),
- xfa: null,
- });
- }
- return newRefs;
- }
- _getDefaultCheckedAppearance(params, type) {
- const width = this.data.rect[2] - this.data.rect[0];
- const height = this.data.rect[3] - this.data.rect[1];
- const bbox = [0, 0, width, height];
- // Ratio used to have a mark slightly smaller than the bbox.
- const FONT_RATIO = 0.8;
- const fontSize = Math.min(width, height) * FONT_RATIO;
- // Char Metrics
- // Widths came from widths for ZapfDingbats.
- // Heights are guessed with Fontforge and FoxitDingbats.pfb.
- let metrics, char;
- if (type === "check") {
- // Char 33 (2713 in unicode)
- metrics = {
- width: 0.755 * fontSize,
- height: 0.705 * fontSize,
- };
- char = "\x33";
- } else if (type === "disc") {
- // Char 6C (25CF in unicode)
- metrics = {
- width: 0.791 * fontSize,
- height: 0.705 * fontSize,
- };
- char = "\x6C";
- } else {
- unreachable(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
- }
- // Values to center the glyph in the bbox.
- const xShift = numberToString((width - metrics.width) / 2);
- const yShift = numberToString((height - metrics.height) / 2);
- const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
- const appearanceStreamDict = new Dict(params.xref);
- appearanceStreamDict.set("FormType", 1);
- appearanceStreamDict.set("Subtype", Name.get("Form"));
- appearanceStreamDict.set("Type", Name.get("XObject"));
- appearanceStreamDict.set("BBox", bbox);
- appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
- appearanceStreamDict.set("Length", appearance.length);
- const resources = new Dict(params.xref);
- const font = new Dict(params.xref);
- font.set("PdfJsZaDb", this.fallbackFontDict);
- resources.set("Font", font);
- appearanceStreamDict.set("Resources", resources);
- this.checkedAppearance = new StringStream(appearance);
- this.checkedAppearance.dict = appearanceStreamDict;
- this._streams.push(this.checkedAppearance);
- }
- _processCheckBox(params) {
- const customAppearance = params.dict.get("AP");
- if (!(customAppearance instanceof Dict)) {
- return;
- }
- const normalAppearance = customAppearance.get("N");
- if (!(normalAppearance instanceof Dict)) {
- return;
- }
- // See https://bugzilla.mozilla.org/show_bug.cgi?id=1722036.
- // If we've an AS and a V then take AS.
- const asValue = this._decodeFormValue(params.dict.get("AS"));
- if (typeof asValue === "string") {
- this.data.fieldValue = asValue;
- }
- const yes =
- this.data.fieldValue !== null && this.data.fieldValue !== "Off"
- ? this.data.fieldValue
- : "Yes";
- const exportValues = normalAppearance.getKeys();
- if (exportValues.length === 0) {
- exportValues.push("Off", yes);
- } else if (exportValues.length === 1) {
- if (exportValues[0] === "Off") {
- exportValues.push(yes);
- } else {
- exportValues.unshift("Off");
- }
- } else if (exportValues.includes(yes)) {
- exportValues.length = 0;
- exportValues.push("Off", yes);
- } else {
- const otherYes = exportValues.find(v => v !== "Off");
- exportValues.length = 0;
- exportValues.push("Off", otherYes);
- }
- // Don't use a "V" entry pointing to a non-existent appearance state,
- // see e.g. bug1720411.pdf where it's an *empty* Name-instance.
- if (!exportValues.includes(this.data.fieldValue)) {
- this.data.fieldValue = "Off";
- }
- this.data.exportValue = exportValues[1];
- this.checkedAppearance =
- normalAppearance.get(this.data.exportValue) || null;
- this.uncheckedAppearance = normalAppearance.get("Off") || null;
- if (this.checkedAppearance) {
- this._streams.push(this.checkedAppearance);
- } else {
- this._getDefaultCheckedAppearance(params, "check");
- }
- if (this.uncheckedAppearance) {
- this._streams.push(this.uncheckedAppearance);
- }
- this._fallbackFontDict = this.fallbackFontDict;
- }
- _processRadioButton(params) {
- this.data.fieldValue = this.data.buttonValue = null;
- // The parent field's `V` entry holds a `Name` object with the appearance
- // state of whichever child field is currently in the "on" state.
- const fieldParent = params.dict.get("Parent");
- if (fieldParent instanceof Dict) {
- this.parent = params.dict.getRaw("Parent");
- const fieldParentValue = fieldParent.get("V");
- if (fieldParentValue instanceof Name) {
- this.data.fieldValue = this._decodeFormValue(fieldParentValue);
- }
- }
- // The button's value corresponds to its appearance state.
- const appearanceStates = params.dict.get("AP");
- if (!(appearanceStates instanceof Dict)) {
- return;
- }
- const normalAppearance = appearanceStates.get("N");
- if (!(normalAppearance instanceof Dict)) {
- return;
- }
- for (const key of normalAppearance.getKeys()) {
- if (key !== "Off") {
- this.data.buttonValue = this._decodeFormValue(key);
- break;
- }
- }
- this.checkedAppearance =
- normalAppearance.get(this.data.buttonValue) || null;
- this.uncheckedAppearance = normalAppearance.get("Off") || null;
- if (this.checkedAppearance) {
- this._streams.push(this.checkedAppearance);
- } else {
- this._getDefaultCheckedAppearance(params, "disc");
- }
- if (this.uncheckedAppearance) {
- this._streams.push(this.uncheckedAppearance);
- }
- this._fallbackFontDict = this.fallbackFontDict;
- }
- _processPushButton(params) {
- if (
- !params.dict.has("A") &&
- !params.dict.has("AA") &&
- !this.data.alternativeText
- ) {
- warn("Push buttons without action dictionaries are not supported");
- return;
- }
- this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
- Catalog.parseDestDictionary({
- destDict: params.dict,
- resultObj: this.data,
- docBaseUrl: params.pdfManager.docBaseUrl,
- docAttachments: params.attachments,
- });
- }
- getFieldObject() {
- let type = "button";
- let exportValues;
- if (this.data.checkBox) {
- type = "checkbox";
- exportValues = this.data.exportValue;
- } else if (this.data.radioButton) {
- type = "radiobutton";
- exportValues = this.data.buttonValue;
- }
- return {
- id: this.data.id,
- value: this.data.fieldValue || "Off",
- defaultValue: this.data.defaultFieldValue,
- exportValues,
- editable: !this.data.readOnly,
- name: this.data.fieldName,
- rect: this.data.rect,
- hidden: this.data.hidden,
- actions: this.data.actions,
- page: this.data.pageIndex,
- strokeColor: this.data.borderColor,
- fillColor: this.data.backgroundColor,
- rotation: this.rotation,
- type,
- };
- }
- get fallbackFontDict() {
- const dict = new Dict();
- dict.set("BaseFont", Name.get("ZapfDingbats"));
- dict.set("Type", Name.get("FallbackType"));
- dict.set("Subtype", Name.get("FallbackType"));
- dict.set("Encoding", Name.get("ZapfDingbatsEncoding"));
- return shadow(this, "fallbackFontDict", dict);
- }
- }
- class ChoiceWidgetAnnotation extends WidgetAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- // Determine the options. The options array may consist of strings or
- // arrays. If the array consists of arrays, then the first element of
- // each array is the export value and the second element of each array is
- // the display value. If the array consists of strings, then these
- // represent both the export and display value. In this case, we convert
- // it to an array of arrays as well for convenience in the display layer.
- // Note that the specification does not state that the `Opt` field is
- // inheritable, but in practice PDF generators do make annotations
- // inherit the options from a parent annotation (issue 8094).
- this.data.options = [];
- const options = getInheritableProperty({ dict, key: "Opt" });
- if (Array.isArray(options)) {
- for (let i = 0, ii = options.length; i < ii; i++) {
- const option = xref.fetchIfRef(options[i]);
- const isOptionArray = Array.isArray(option);
- this.data.options[i] = {
- exportValue: this._decodeFormValue(
- isOptionArray ? xref.fetchIfRef(option[0]) : option
- ),
- displayValue: this._decodeFormValue(
- isOptionArray ? xref.fetchIfRef(option[1]) : option
- ),
- };
- }
- }
- // The field value can be `null` if no item is selected, a string if one
- // item is selected or an array of strings if multiple items are selected.
- // For consistency in the API and convenience in the display layer, we
- // always make the field value an array with zero, one or multiple items.
- if (typeof this.data.fieldValue === "string") {
- this.data.fieldValue = [this.data.fieldValue];
- } else if (!this.data.fieldValue) {
- this.data.fieldValue = [];
- }
- // Process field flags for the display layer.
- this.data.combo = this.hasFieldFlag(AnnotationFieldFlag.COMBO);
- this.data.multiSelect = this.hasFieldFlag(AnnotationFieldFlag.MULTISELECT);
- this._hasText = true;
- }
- getFieldObject() {
- const type = this.data.combo ? "combobox" : "listbox";
- const value =
- this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
- return {
- id: this.data.id,
- value,
- defaultValue: this.data.defaultFieldValue,
- editable: !this.data.readOnly,
- name: this.data.fieldName,
- rect: this.data.rect,
- numItems: this.data.fieldValue.length,
- multipleSelection: this.data.multiSelect,
- hidden: this.data.hidden,
- actions: this.data.actions,
- items: this.data.options,
- page: this.data.pageIndex,
- strokeColor: this.data.borderColor,
- fillColor: this.data.backgroundColor,
- rotation: this.rotation,
- type,
- };
- }
- async _getAppearance(evaluator, task, intent, annotationStorage) {
- if (this.data.combo) {
- return super._getAppearance(evaluator, task, intent, annotationStorage);
- }
- let exportedValue, rotation;
- const storageEntry = annotationStorage
- ? annotationStorage.get(this.data.id)
- : undefined;
- if (storageEntry) {
- rotation = storageEntry.rotation;
- exportedValue = storageEntry.value;
- }
- if (
- rotation === undefined &&
- exportedValue === undefined &&
- !this._needAppearances
- ) {
- // The annotation hasn't been rendered so use the appearance
- return null;
- }
- if (exportedValue === undefined) {
- exportedValue = this.data.fieldValue;
- } else if (!Array.isArray(exportedValue)) {
- exportedValue = [exportedValue];
- }
- const defaultPadding = 1;
- const defaultHPadding = 2;
- let totalHeight = this.data.rect[3] - this.data.rect[1];
- let totalWidth = this.data.rect[2] - this.data.rect[0];
- if (rotation === 90 || rotation === 270) {
- [totalWidth, totalHeight] = [totalHeight, totalWidth];
- }
- const lineCount = this.data.options.length;
- const valueIndices = [];
- for (let i = 0; i < lineCount; i++) {
- const { exportValue } = this.data.options[i];
- if (exportedValue.includes(exportValue)) {
- valueIndices.push(i);
- }
- }
- if (!this._defaultAppearance) {
- // The DA is required and must be a string.
- // If there is no font named Helvetica in the resource dictionary,
- // the evaluator will fall back to a default font.
- // Doing so prevents exceptions and allows saving/printing
- // the file as expected.
- this.data.defaultAppearanceData = parseDefaultAppearance(
- (this._defaultAppearance = "/Helvetica 0 Tf 0 g")
- );
- }
- const font = await WidgetAnnotation._getFontData(
- evaluator,
- task,
- this.data.defaultAppearanceData,
- this._fieldResources.mergedResources
- );
- let defaultAppearance;
- let { fontSize } = this.data.defaultAppearanceData;
- if (!fontSize) {
- const lineHeight = (totalHeight - defaultPadding) / lineCount;
- let lineWidth = -1;
- let value;
- for (const { displayValue } of this.data.options) {
- const width = this._getTextWidth(displayValue, font);
- if (width > lineWidth) {
- lineWidth = width;
- value = displayValue;
- }
- }
- [defaultAppearance, fontSize] = this._computeFontSize(
- lineHeight,
- totalWidth - 2 * defaultHPadding,
- value,
- font,
- -1
- );
- } else {
- defaultAppearance = this._defaultAppearance;
- }
- const lineHeight = fontSize * LINE_FACTOR;
- const vPadding = (lineHeight - fontSize) / 2;
- const numberOfVisibleLines = Math.floor(totalHeight / lineHeight);
- let firstIndex;
- if (valueIndices.length === 1) {
- const valuePosition = valueIndices[0];
- const indexInPage = valuePosition % numberOfVisibleLines;
- firstIndex = valuePosition - indexInPage;
- } else {
- // If nothing is selected (valueIndice.length === 0), we render
- // from the first element.
- firstIndex = valueIndices.length ? valueIndices[0] : 0;
- }
- const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount);
- const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`];
- if (valueIndices.length) {
- // This value has been copied/pasted from annotation-choice-widget.pdf.
- // It corresponds to rgb(153, 193, 218).
- buf.push("0.600006 0.756866 0.854904 rg");
- // Highlight the lines in filling a blue rectangle at the selected
- // positions.
- for (const index of valueIndices) {
- if (firstIndex <= index && index < end) {
- buf.push(
- `1 ${
- totalHeight - (index - firstIndex + 1) * lineHeight
- } ${totalWidth} ${lineHeight} re f`
- );
- }
- }
- }
- buf.push("BT", defaultAppearance, `1 0 0 1 0 ${totalHeight} Tm`);
- const prevInfo = { shift: 0 };
- for (let i = firstIndex; i < end; i++) {
- const { displayValue } = this.data.options[i];
- const vpadding = i === firstIndex ? vPadding : 0;
- buf.push(
- this._renderText(
- displayValue,
- font,
- fontSize,
- totalWidth,
- 0,
- prevInfo,
- defaultHPadding,
- -lineHeight + vpadding
- )
- );
- }
- buf.push("ET Q EMC");
- return buf.join("\n");
- }
- }
- class SignatureWidgetAnnotation extends WidgetAnnotation {
- constructor(params) {
- super(params);
- // Unset the fieldValue since it's (most likely) a `Dict` which is
- // non-serializable and will thus cause errors when sending annotations
- // to the main-thread (issue 10347).
- this.data.fieldValue = null;
- }
- getFieldObject() {
- return {
- id: this.data.id,
- value: null,
- page: this.data.pageIndex,
- type: "signature",
- };
- }
- }
- class TextAnnotation extends MarkupAnnotation {
- constructor(params) {
- const DEFAULT_ICON_SIZE = 22; // px
- super(params);
- const { dict } = params;
- this.data.annotationType = AnnotationType.TEXT;
- if (this.data.hasAppearance) {
- this.data.name = "NoIcon";
- } else {
- this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
- this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
- this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
- }
- if (dict.has("State")) {
- this.data.state = dict.get("State") || null;
- this.data.stateModel = dict.get("StateModel") || null;
- } else {
- this.data.state = null;
- this.data.stateModel = null;
- }
- }
- }
- class LinkAnnotation extends Annotation {
- constructor(params) {
- super(params);
- this.data.annotationType = AnnotationType.LINK;
- const quadPoints = getQuadPoints(params.dict, this.rectangle);
- if (quadPoints) {
- this.data.quadPoints = quadPoints;
- }
- // The color entry for a link annotation is the color of the border.
- this.data.borderColor = this.data.borderColor || this.data.color;
- Catalog.parseDestDictionary({
- destDict: params.dict,
- resultObj: this.data,
- docBaseUrl: params.pdfManager.docBaseUrl,
- docAttachments: params.attachments,
- });
- }
- }
- class PopupAnnotation extends Annotation {
- constructor(params) {
- super(params);
- const { dict } = params;
- this.data.annotationType = AnnotationType.POPUP;
- let parentItem = dict.get("Parent");
- if (!parentItem) {
- warn("Popup annotation has a missing or invalid parent annotation.");
- return;
- }
- const parentSubtype = parentItem.get("Subtype");
- this.data.parentType =
- parentSubtype instanceof Name ? parentSubtype.name : null;
- const rawParent = dict.getRaw("Parent");
- this.data.parentId = rawParent instanceof Ref ? rawParent.toString() : null;
- const parentRect = parentItem.getArray("Rect");
- if (Array.isArray(parentRect) && parentRect.length === 4) {
- this.data.parentRect = Util.normalizeRect(parentRect);
- } else {
- this.data.parentRect = [0, 0, 0, 0];
- }
- const rt = parentItem.get("RT");
- if (isName(rt, AnnotationReplyType.GROUP)) {
- // Subordinate annotations in a group should inherit
- // the group attributes from the primary annotation.
- parentItem = parentItem.get("IRT");
- }
- if (!parentItem.has("M")) {
- this.data.modificationDate = null;
- } else {
- this.setModificationDate(parentItem.get("M"));
- this.data.modificationDate = this.modificationDate;
- }
- if (!parentItem.has("C")) {
- // Fall back to the default background color.
- this.data.color = null;
- } else {
- this.setColor(parentItem.getArray("C"));
- this.data.color = this.color;
- }
- // If the Popup annotation is not viewable, but the parent annotation is,
- // that is most likely a bug. Fallback to inherit the flags from the parent
- // annotation (this is consistent with the behaviour in Adobe Reader).
- if (!this.viewable) {
- const parentFlags = parentItem.get("F");
- if (this._isViewable(parentFlags)) {
- this.setFlags(parentFlags);
- }
- }
- this.setTitle(parentItem.get("T"));
- this.data.titleObj = this._title;
- this.setContents(parentItem.get("Contents"));
- this.data.contentsObj = this._contents;
- if (parentItem.has("RC")) {
- this.data.richText = XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
- }
- }
- }
- class FreeTextAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { xref } = params;
- this.data.annotationType = AnnotationType.FREETEXT;
- this.setDefaultAppearance(params);
- if (!this.appearance && this._isOffscreenCanvasSupported) {
- const fakeUnicodeFont = new FakeUnicodeFont(xref, "sans-serif");
- const fontData = this.data.defaultAppearanceData;
- this.appearance = fakeUnicodeFont.createAppearance(
- this._contents.str,
- this.rectangle,
- this.rotation,
- fontData.fontSize || 10,
- fontData.fontColor
- );
- this._streams.push(this.appearance, FakeUnicodeFont.toUnicodeStream);
- } else if (!this._isOffscreenCanvasSupported) {
- warn(
- "FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly."
- );
- }
- }
- get hasTextContent() {
- return !!this.appearance;
- }
- static createNewDict(annotation, xref, { apRef, ap }) {
- const { color, fontSize, rect, rotation, user, value } = annotation;
- const freetext = new Dict(xref);
- freetext.set("Type", Name.get("Annot"));
- freetext.set("Subtype", Name.get("FreeText"));
- freetext.set("CreationDate", `D:${getModificationDate()}`);
- freetext.set("Rect", rect);
- const da = `/Helv ${fontSize} Tf ${getPdfColor(color, /* isFill */ true)}`;
- freetext.set("DA", da);
- freetext.set(
- "Contents",
- isAscii(value)
- ? value
- : stringToUTF16String(value, /* bigEndian = */ true)
- );
- freetext.set("F", 4);
- freetext.set("Border", [0, 0, 0]);
- freetext.set("Rotate", rotation);
- if (user) {
- freetext.set(
- "T",
- isAscii(user) ? user : stringToUTF16String(user, /* bigEndian = */ true)
- );
- }
- if (apRef || ap) {
- const n = new Dict(xref);
- freetext.set("AP", n);
- if (apRef) {
- n.set("N", apRef);
- } else {
- n.set("N", ap);
- }
- }
- return freetext;
- }
- static async createNewAppearanceStream(annotation, xref, params) {
- const { baseFontRef, evaluator, task } = params;
- const { color, fontSize, rect, rotation, value } = annotation;
- const resources = new Dict(xref);
- const font = new Dict(xref);
- if (baseFontRef) {
- font.set("Helv", baseFontRef);
- } else {
- const baseFont = new Dict(xref);
- baseFont.set("BaseFont", Name.get("Helvetica"));
- baseFont.set("Type", Name.get("Font"));
- baseFont.set("Subtype", Name.get("Type1"));
- baseFont.set("Encoding", Name.get("WinAnsiEncoding"));
- font.set("Helv", baseFont);
- }
- resources.set("Font", font);
- const helv = await WidgetAnnotation._getFontData(
- evaluator,
- task,
- {
- fontName: "Helvetica",
- fontSize,
- },
- resources
- );
- const [x1, y1, x2, y2] = rect;
- let w = x2 - x1;
- let h = y2 - y1;
- if (rotation % 180 !== 0) {
- [w, h] = [h, w];
- }
- const lines = value.split("\n");
- const scale = fontSize / 1000;
- let totalWidth = -Infinity;
- const encodedLines = [];
- for (let line of lines) {
- const encoded = helv.encodeString(line);
- if (encoded.length > 1) {
- // The font doesn't contain all the chars.
- return null;
- }
- line = encoded.join("");
- encodedLines.push(line);
- let lineWidth = 0;
- const glyphs = helv.charsToGlyphs(line);
- for (const glyph of glyphs) {
- lineWidth += glyph.width * scale;
- }
- totalWidth = Math.max(totalWidth, lineWidth);
- }
- let hscale = 1;
- if (totalWidth > w) {
- hscale = w / totalWidth;
- }
- let vscale = 1;
- const lineHeight = LINE_FACTOR * fontSize;
- const lineDescent = LINE_DESCENT_FACTOR * fontSize;
- const totalHeight = lineHeight * lines.length;
- if (totalHeight > h) {
- vscale = h / totalHeight;
- }
- const fscale = Math.min(hscale, vscale);
- const newFontSize = fontSize * fscale;
- const buffer = [
- "q",
- `0 0 ${numberToString(w)} ${numberToString(h)} re W n`,
- `BT`,
- `1 0 0 1 0 ${numberToString(h + lineDescent)} Tm 0 Tc ${getPdfColor(
- color,
- /* isFill */ true
- )}`,
- `/Helv ${numberToString(newFontSize)} Tf`,
- ];
- const vShift = numberToString(lineHeight);
- for (const line of encodedLines) {
- buffer.push(`0 -${vShift} Td (${escapeString(line)}) Tj`);
- }
- buffer.push("ET", "Q");
- const appearance = buffer.join("\n");
- const appearanceStreamDict = new Dict(xref);
- appearanceStreamDict.set("FormType", 1);
- appearanceStreamDict.set("Subtype", Name.get("Form"));
- appearanceStreamDict.set("Type", Name.get("XObject"));
- appearanceStreamDict.set("BBox", [0, 0, w, h]);
- appearanceStreamDict.set("Length", appearance.length);
- appearanceStreamDict.set("Resources", resources);
- if (rotation) {
- const matrix = getRotationMatrix(rotation, w, h);
- appearanceStreamDict.set("Matrix", matrix);
- }
- const ap = new StringStream(appearance);
- ap.dict = appearanceStreamDict;
- return ap;
- }
- }
- class LineAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.LINE;
- const lineCoordinates = dict.getArray("L");
- this.data.lineCoordinates = Util.normalizeRect(lineCoordinates);
- this.setLineEndings(dict.getArray("LE"));
- this.data.lineEndings = this.lineEndings;
- if (!this.appearance) {
- // The default stroke color is black.
- const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- const interiorColor = getRgbColor(dict.getArray("IC"), null);
- // The default fill color is transparent. Setting the fill colour is
- // necessary if/when we want to add support for non-default line endings.
- const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
- const fillAlpha = fillColor ? strokeAlpha : null;
- const borderWidth = this.borderStyle.width || 1,
- borderAdjust = 2 * borderWidth;
- // If the /Rect-entry is empty/wrong, create a fallback rectangle so that
- // we get similar rendering/highlighting behaviour as in Adobe Reader.
- const bbox = [
- this.data.lineCoordinates[0] - borderAdjust,
- this.data.lineCoordinates[1] - borderAdjust,
- this.data.lineCoordinates[2] + borderAdjust,
- this.data.lineCoordinates[3] + borderAdjust,
- ];
- if (!Util.intersect(this.rectangle, bbox)) {
- this.rectangle = bbox;
- }
- this._setDefaultAppearance({
- xref,
- extra: `${borderWidth} w`,
- strokeColor,
- fillColor,
- strokeAlpha,
- fillAlpha,
- pointsCallback: (buffer, points) => {
- buffer.push(
- `${lineCoordinates[0]} ${lineCoordinates[1]} m`,
- `${lineCoordinates[2]} ${lineCoordinates[3]} l`,
- "S"
- );
- return [
- points[0].x - borderWidth,
- points[1].x + borderWidth,
- points[3].y - borderWidth,
- points[1].y + borderWidth,
- ];
- },
- });
- }
- }
- }
- class SquareAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.SQUARE;
- if (!this.appearance) {
- // The default stroke color is black.
- const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- const interiorColor = getRgbColor(dict.getArray("IC"), null);
- // The default fill color is transparent.
- const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
- const fillAlpha = fillColor ? strokeAlpha : null;
- if (this.borderStyle.width === 0 && !fillColor) {
- // Prevent rendering a "hairline" border (fixes issue14164.pdf).
- return;
- }
- this._setDefaultAppearance({
- xref,
- extra: `${this.borderStyle.width} w`,
- strokeColor,
- fillColor,
- strokeAlpha,
- fillAlpha,
- pointsCallback: (buffer, points) => {
- const x = points[2].x + this.borderStyle.width / 2;
- const y = points[2].y + this.borderStyle.width / 2;
- const width = points[3].x - points[2].x - this.borderStyle.width;
- const height = points[1].y - points[3].y - this.borderStyle.width;
- buffer.push(`${x} ${y} ${width} ${height} re`);
- if (fillColor) {
- buffer.push("B");
- } else {
- buffer.push("S");
- }
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- }
- }
- class CircleAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.CIRCLE;
- if (!this.appearance) {
- // The default stroke color is black.
- const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- const interiorColor = getRgbColor(dict.getArray("IC"), null);
- // The default fill color is transparent.
- const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
- const fillAlpha = fillColor ? strokeAlpha : null;
- if (this.borderStyle.width === 0 && !fillColor) {
- // Prevent rendering a "hairline" border (fixes issue14164.pdf).
- return;
- }
- // Circles are approximated by Bézier curves with four segments since
- // there is no circle primitive in the PDF specification. For the control
- // points distance, see https://stackoverflow.com/a/27863181.
- const controlPointsDistance = (4 / 3) * Math.tan(Math.PI / (2 * 4));
- this._setDefaultAppearance({
- xref,
- extra: `${this.borderStyle.width} w`,
- strokeColor,
- fillColor,
- strokeAlpha,
- fillAlpha,
- pointsCallback: (buffer, points) => {
- const x0 = points[0].x + this.borderStyle.width / 2;
- const y0 = points[0].y - this.borderStyle.width / 2;
- const x1 = points[3].x - this.borderStyle.width / 2;
- const y1 = points[3].y + this.borderStyle.width / 2;
- const xMid = x0 + (x1 - x0) / 2;
- const yMid = y0 + (y1 - y0) / 2;
- const xOffset = ((x1 - x0) / 2) * controlPointsDistance;
- const yOffset = ((y1 - y0) / 2) * controlPointsDistance;
- buffer.push(
- `${xMid} ${y1} m`,
- `${xMid + xOffset} ${y1} ${x1} ${yMid + yOffset} ${x1} ${yMid} c`,
- `${x1} ${yMid - yOffset} ${xMid + xOffset} ${y0} ${xMid} ${y0} c`,
- `${xMid - xOffset} ${y0} ${x0} ${yMid - yOffset} ${x0} ${yMid} c`,
- `${x0} ${yMid + yOffset} ${xMid - xOffset} ${y1} ${xMid} ${y1} c`,
- "h"
- );
- if (fillColor) {
- buffer.push("B");
- } else {
- buffer.push("S");
- }
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- }
- }
- class PolylineAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.POLYLINE;
- this.data.vertices = [];
- if (!(this instanceof PolygonAnnotation)) {
- // Only meaningful for polyline annotations.
- this.setLineEndings(dict.getArray("LE"));
- this.data.lineEndings = this.lineEndings;
- }
- // The vertices array is an array of numbers representing the alternating
- // horizontal and vertical coordinates, respectively, of each vertex.
- // Convert this to an array of objects with x and y coordinates.
- const rawVertices = dict.getArray("Vertices");
- if (!Array.isArray(rawVertices)) {
- return;
- }
- for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
- this.data.vertices.push({
- x: rawVertices[i],
- y: rawVertices[i + 1],
- });
- }
- if (!this.appearance) {
- // The default stroke color is black.
- const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- const borderWidth = this.borderStyle.width || 1,
- borderAdjust = 2 * borderWidth;
- // If the /Rect-entry is empty/wrong, create a fallback rectangle so that
- // we get similar rendering/highlighting behaviour as in Adobe Reader.
- const bbox = [Infinity, Infinity, -Infinity, -Infinity];
- for (const vertex of this.data.vertices) {
- bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
- bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
- bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
- bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
- }
- if (!Util.intersect(this.rectangle, bbox)) {
- this.rectangle = bbox;
- }
- this._setDefaultAppearance({
- xref,
- extra: `${borderWidth} w`,
- strokeColor,
- strokeAlpha,
- pointsCallback: (buffer, points) => {
- const vertices = this.data.vertices;
- for (let i = 0, ii = vertices.length; i < ii; i++) {
- buffer.push(
- `${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`
- );
- }
- buffer.push("S");
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- }
- }
- class PolygonAnnotation extends PolylineAnnotation {
- constructor(params) {
- // Polygons are specific forms of polylines, so reuse their logic.
- super(params);
- this.data.annotationType = AnnotationType.POLYGON;
- }
- }
- class CaretAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- this.data.annotationType = AnnotationType.CARET;
- }
- }
- class InkAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.INK;
- this.data.inkLists = [];
- const rawInkLists = dict.getArray("InkList");
- if (!Array.isArray(rawInkLists)) {
- return;
- }
- for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
- // The raw ink lists array contains arrays of numbers representing
- // the alternating horizontal and vertical coordinates, respectively,
- // of each vertex. Convert this to an array of objects with x and y
- // coordinates.
- this.data.inkLists.push([]);
- for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
- this.data.inkLists[i].push({
- x: xref.fetchIfRef(rawInkLists[i][j]),
- y: xref.fetchIfRef(rawInkLists[i][j + 1]),
- });
- }
- }
- if (!this.appearance) {
- // The default stroke color is black.
- const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- const borderWidth = this.borderStyle.width || 1,
- borderAdjust = 2 * borderWidth;
- // If the /Rect-entry is empty/wrong, create a fallback rectangle so that
- // we get similar rendering/highlighting behaviour as in Adobe Reader.
- const bbox = [Infinity, Infinity, -Infinity, -Infinity];
- for (const inkLists of this.data.inkLists) {
- for (const vertex of inkLists) {
- bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
- bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
- bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
- bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
- }
- }
- if (!Util.intersect(this.rectangle, bbox)) {
- this.rectangle = bbox;
- }
- this._setDefaultAppearance({
- xref,
- extra: `${borderWidth} w`,
- strokeColor,
- strokeAlpha,
- pointsCallback: (buffer, points) => {
- // According to the specification, see "12.5.6.13 Ink Annotations":
- // When drawn, the points shall be connected by straight lines or
- // curves in an implementation-dependent way.
- // In order to simplify things, we utilize straight lines for now.
- for (const inkList of this.data.inkLists) {
- for (let i = 0, ii = inkList.length; i < ii; i++) {
- buffer.push(
- `${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`
- );
- }
- buffer.push("S");
- }
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- }
- static createNewDict(annotation, xref, { apRef, ap }) {
- const { paths, rect, rotation } = annotation;
- const ink = new Dict(xref);
- ink.set("Type", Name.get("Annot"));
- ink.set("Subtype", Name.get("Ink"));
- ink.set("CreationDate", `D:${getModificationDate()}`);
- ink.set("Rect", rect);
- ink.set(
- "InkList",
- paths.map(p => p.points)
- );
- ink.set("F", 4);
- ink.set("Border", [0, 0, 0]);
- ink.set("Rotate", rotation);
- const n = new Dict(xref);
- ink.set("AP", n);
- if (apRef) {
- n.set("N", apRef);
- } else {
- n.set("N", ap);
- }
- return ink;
- }
- static async createNewAppearanceStream(annotation, xref, params) {
- const { color, rect, rotation, paths, thickness, opacity } = annotation;
- const [x1, y1, x2, y2] = rect;
- let w = x2 - x1;
- let h = y2 - y1;
- if (rotation % 180 !== 0) {
- [w, h] = [h, w];
- }
- const appearanceBuffer = [
- `${thickness} w 1 J 1 j`,
- `${getPdfColor(color, /* isFill */ false)}`,
- ];
- if (opacity !== 1) {
- appearanceBuffer.push("/R0 gs");
- }
- const buffer = [];
- for (const { bezier } of paths) {
- buffer.length = 0;
- buffer.push(
- `${numberToString(bezier[0])} ${numberToString(bezier[1])} m`
- );
- for (let i = 2, ii = bezier.length; i < ii; i += 6) {
- const curve = bezier
- .slice(i, i + 6)
- .map(numberToString)
- .join(" ");
- buffer.push(`${curve} c`);
- }
- buffer.push("S");
- appearanceBuffer.push(buffer.join("\n"));
- }
- const appearance = appearanceBuffer.join("\n");
- const appearanceStreamDict = new Dict(xref);
- appearanceStreamDict.set("FormType", 1);
- appearanceStreamDict.set("Subtype", Name.get("Form"));
- appearanceStreamDict.set("Type", Name.get("XObject"));
- appearanceStreamDict.set("BBox", [0, 0, w, h]);
- appearanceStreamDict.set("Length", appearance.length);
- if (rotation) {
- const matrix = getRotationMatrix(rotation, w, h);
- appearanceStreamDict.set("Matrix", matrix);
- }
- if (opacity !== 1) {
- const resources = new Dict(xref);
- const extGState = new Dict(xref);
- const r0 = new Dict(xref);
- r0.set("CA", opacity);
- r0.set("Type", Name.get("ExtGState"));
- extGState.set("R0", r0);
- resources.set("ExtGState", extGState);
- appearanceStreamDict.set("Resources", resources);
- }
- const ap = new StringStream(appearance);
- ap.dict = appearanceStreamDict;
- return ap;
- }
- }
- class HighlightAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.HIGHLIGHT;
- const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
- if (quadPoints) {
- const resources =
- this.appearance && this.appearance.dict.get("Resources");
- if (!this.appearance || !(resources && resources.has("ExtGState"))) {
- if (this.appearance) {
- // Workaround for cases where there's no /ExtGState-entry directly
- // available, e.g. when the appearance stream contains a /XObject of
- // the /Form-type, since that causes the highlighting to completely
- // obscure the PDF content below it (fixes issue13242.pdf).
- warn("HighlightAnnotation - ignoring built-in appearance stream.");
- }
- // Default color is yellow in Acrobat Reader
- const fillColor = this.color ? getPdfColorArray(this.color) : [1, 1, 0];
- const fillAlpha = dict.get("CA");
- this._setDefaultAppearance({
- xref,
- fillColor,
- blendMode: "Multiply",
- fillAlpha,
- pointsCallback: (buffer, points) => {
- buffer.push(
- `${points[0].x} ${points[0].y} m`,
- `${points[1].x} ${points[1].y} l`,
- `${points[3].x} ${points[3].y} l`,
- `${points[2].x} ${points[2].y} l`,
- "f"
- );
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- } else {
- this.data.hasPopup = false;
- }
- }
- }
- class UnderlineAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.UNDERLINE;
- const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
- if (quadPoints) {
- if (!this.appearance) {
- // Default color is black
- const strokeColor = this.color
- ? getPdfColorArray(this.color)
- : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- this._setDefaultAppearance({
- xref,
- extra: "[] 0 d 1 w",
- strokeColor,
- strokeAlpha,
- pointsCallback: (buffer, points) => {
- buffer.push(
- `${points[2].x} ${points[2].y} m`,
- `${points[3].x} ${points[3].y} l`,
- "S"
- );
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- } else {
- this.data.hasPopup = false;
- }
- }
- }
- class SquigglyAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.SQUIGGLY;
- const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
- if (quadPoints) {
- if (!this.appearance) {
- // Default color is black
- const strokeColor = this.color
- ? getPdfColorArray(this.color)
- : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- this._setDefaultAppearance({
- xref,
- extra: "[] 0 d 1 w",
- strokeColor,
- strokeAlpha,
- pointsCallback: (buffer, points) => {
- const dy = (points[0].y - points[2].y) / 6;
- let shift = dy;
- let x = points[2].x;
- const y = points[2].y;
- const xEnd = points[3].x;
- buffer.push(`${x} ${y + shift} m`);
- do {
- x += 2;
- shift = shift === 0 ? dy : 0;
- buffer.push(`${x} ${y + shift} l`);
- } while (x < xEnd);
- buffer.push("S");
- return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
- },
- });
- }
- } else {
- this.data.hasPopup = false;
- }
- }
- }
- class StrikeOutAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- this.data.annotationType = AnnotationType.STRIKEOUT;
- const quadPoints = (this.data.quadPoints = getQuadPoints(dict, null));
- if (quadPoints) {
- if (!this.appearance) {
- // Default color is black
- const strokeColor = this.color
- ? getPdfColorArray(this.color)
- : [0, 0, 0];
- const strokeAlpha = dict.get("CA");
- this._setDefaultAppearance({
- xref,
- extra: "[] 0 d 1 w",
- strokeColor,
- strokeAlpha,
- pointsCallback: (buffer, points) => {
- buffer.push(
- `${(points[0].x + points[2].x) / 2} ` +
- `${(points[0].y + points[2].y) / 2} m`,
- `${(points[1].x + points[3].x) / 2} ` +
- `${(points[1].y + points[3].y) / 2} l`,
- "S"
- );
- return [points[0].x, points[1].x, points[3].y, points[1].y];
- },
- });
- }
- } else {
- this.data.hasPopup = false;
- }
- }
- }
- class StampAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- this.data.annotationType = AnnotationType.STAMP;
- }
- }
- class FileAttachmentAnnotation extends MarkupAnnotation {
- constructor(params) {
- super(params);
- const { dict, xref } = params;
- const file = new FileSpec(dict.get("FS"), xref);
- this.data.annotationType = AnnotationType.FILEATTACHMENT;
- this.data.file = file.serializable;
- const name = dict.get("Name");
- this.data.name =
- name instanceof Name ? stringToPDFString(name.name) : "PushPin";
- }
- }
- export {
- Annotation,
- AnnotationBorderStyle,
- AnnotationFactory,
- getQuadPoints,
- MarkupAnnotation,
- PopupAnnotation,
- };
|