*/}}

pdfgen.c 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167
  1. /**
  2. * Simple engine for creating PDF files.
  3. * It supports text, shapes, images etc...
  4. * Capable of handling millions of objects without too much performance
  5. * penalty.
  6. * Public domain license - no warranty implied; use at your own risk.
  7. */
  8. /**
  9. * PDF HINTS & TIPS
  10. * The specification can be found at
  11. * https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/pdf_reference_archives/PDFReference.pdf
  12. * The following sites have various bits & pieces about PDF document
  13. * generation
  14. * http://www.mactech.com/articles/mactech/Vol.15/15.09/PDFIntro/index.html
  15. * http://gnupdf.org/Introduction_to_PDF
  16. * http://www.planetpdf.com/mainpage.asp?WebPageID=63
  17. * http://archive.vector.org.uk/art10008970
  18. * http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
  19. * https://blog.idrsolutions.com/2013/01/understanding-the-pdf-file-format-overview/
  20. *
  21. * To validate the PDF output, there are several online validators:
  22. * http://www.validatepdfa.com/online.htm
  23. * http://www.datalogics.com/products/callas/callaspdfA-onlinedemo.asp
  24. * http://www.pdf-tools.com/pdf/validate-pdfa-online.aspx
  25. *
  26. * In addition the 'pdftk' server can be used to analyse the output:
  27. * https://www.pdflabs.com/docs/pdftk-cli-examples/
  28. *
  29. * PDF page markup operators:
  30. * b closepath, fill,and stroke path.
  31. * B fill and stroke path.
  32. * b* closepath, eofill,and stroke path.
  33. * B* eofill and stroke path.
  34. * BI begin image.
  35. * BMC begin marked content.
  36. * BT begin text object.
  37. * BX begin section allowing undefined operators.
  38. * c curveto.
  39. * cm concat. Concatenates the matrix to the current transform.
  40. * cs setcolorspace for fill.
  41. * CS setcolorspace for stroke.
  42. * d setdash.
  43. * Do execute the named XObject.
  44. * DP mark a place in the content stream, with a dictionary.
  45. * EI end image.
  46. * EMC end marked content.
  47. * ET end text object.
  48. * EX end section that allows undefined operators.
  49. * f fill path.
  50. * f* eofill Even/odd fill path.
  51. * g setgray (fill).
  52. * G setgray (stroke).
  53. * gs set parameters in the extended graphics state.
  54. * h closepath.
  55. * i setflat.
  56. * ID begin image data.
  57. * j setlinejoin.
  58. * J setlinecap.
  59. * k setcmykcolor (fill).
  60. * K setcmykcolor (stroke).
  61. * l lineto.
  62. * m moveto.
  63. * M setmiterlimit.
  64. * n end path without fill or stroke.
  65. * q save graphics state.
  66. * Q restore graphics state.
  67. * re rectangle.
  68. * rg setrgbcolor (fill).
  69. * RG setrgbcolor (stroke).
  70. * s closepath and stroke path.
  71. * S stroke path.
  72. * sc setcolor (fill).
  73. * SC setcolor (stroke).
  74. * sh shfill (shaded fill).
  75. * Tc set character spacing.
  76. * Td move text current point.
  77. * TD move text current point and set leading.
  78. * Tf set font name and size.
  79. * Tj show text.
  80. * TJ show text, allowing individual character positioning.
  81. * TL set leading.
  82. * Tm set text matrix.
  83. * Tr set text rendering mode.
  84. * Ts set super/subscripting text rise.
  85. * Tw set word spacing.
  86. * Tz set horizontal scaling.
  87. * T* move to start of next line.
  88. * v curveto.
  89. * w setlinewidth.
  90. * W clip.
  91. * y curveto.
  92. */
  93. #if defined(_MSC_VER)
  94. #define _CRT_SECURE_NO_WARNINGS 1 // Drop the MSVC complaints about snprintf
  95. #define _USE_MATH_DEFINES
  96. #include <BaseTsd.h>
  97. typedef SSIZE_T ssize_t;
  98. #else
  99. #ifndef _POSIX_SOURCE
  100. #define _POSIX_SOURCE /* For localtime_r */
  101. #endif
  102. #ifndef _XOPEN_SOURCE
  103. #define _XOPEN_SOURCE 600 /* for M_SQRT2 */
  104. #endif
  105. #include <sys/types.h> /* for ssize_t */
  106. #endif
  107. #include <ctype.h>
  108. #include <errno.h>
  109. #include <inttypes.h>
  110. #include <limits.h>
  111. #include <locale.h>
  112. #include <math.h>
  113. #include <stdarg.h>
  114. #include <stdbool.h>
  115. #include <stddef.h>
  116. #include <stdio.h>
  117. #include <stdlib.h>
  118. #include <string.h>
  119. #include <sys/stat.h>
  120. #include <time.h>
  121. #include "pdfgen.h"
  122. #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  123. #define PDF_RGB_R(c) (float)((((c) >> 16) & 0xff) / 255.0)
  124. #define PDF_RGB_G(c) (float)((((c) >> 8) & 0xff) / 255.0)
  125. #define PDF_RGB_B(c) (float)((((c) >> 0) & 0xff) / 255.0)
  126. #define PDF_IS_TRANSPARENT(c) (((c) >> 24) == 0xff)
  127. #if defined(_MSC_VER)
  128. #define inline __inline
  129. #define snprintf _snprintf
  130. #define strcasecmp _stricmp
  131. #define strncasecmp _strnicmp
  132. #define fileno _fileno
  133. #define fstat _fstat
  134. #ifdef stat
  135. #undef stat
  136. #endif
  137. #define stat _stat
  138. #define SKIP_ATTRIBUTE
  139. #else
  140. #include <strings.h> // strcasecmp
  141. #endif
  142. /**
  143. * Try and support big & little endian machines
  144. */
  145. static inline uint32_t bswap32(uint32_t x)
  146. {
  147. return (((x & 0xff000000u) >> 24) | ((x & 0x00ff0000u) >> 8) |
  148. ((x & 0x0000ff00u) << 8) | ((x & 0x000000ffu) << 24));
  149. }
  150. #ifdef __has_include // C++17, supported as extension to C++11 in clang, GCC
  151. // 5+, vs2015
  152. #if __has_include(<endian.h>)
  153. #include <endian.h> // gnu libc normally provides, linux
  154. #elif __has_include(<machine/endian.h>)
  155. #include <machine/endian.h> //open bsd, macos
  156. #elif __has_include(<sys/param.h>)
  157. #include <sys/param.h> // mingw, some bsd (not open/macos)
  158. #elif __has_include(<sys/isadefs.h>)
  159. #include <sys/isadefs.h> // solaris
  160. #endif
  161. #endif
  162. #if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
  163. #ifndef __BYTE_ORDER__
  164. /* Fall back to little endian by default */
  165. #define __LITTLE_ENDIAN__
  166. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ || __BYTE_ORDER == __BIG_ENDIAN
  167. #define __BIG_ENDIAN__
  168. #else
  169. #define __LITTLE_ENDIAN__
  170. #endif
  171. #endif
  172. #if defined(__LITTLE_ENDIAN__)
  173. #define ntoh32(x) bswap32((x))
  174. #elif defined(__BIG_ENDIAN__)
  175. #define ntoh32(x) (x)
  176. #endif
  177. // Limits on image sizes for sanity checking & to avoid plausible overflow
  178. // issues
  179. #define MAX_IMAGE_WIDTH (16 * 1024)
  180. #define MAX_IMAGE_HEIGHT (16 * 1024)
  181. // Signatures for various image formats
  182. static const uint8_t bmp_signature[] = {'B', 'M'};
  183. static const uint8_t png_signature[] = {0x89, 0x50, 0x4E, 0x47,
  184. 0x0D, 0x0A, 0x1A, 0x0A};
  185. static const uint8_t jpeg_signature[] = {0xff, 0xd8};
  186. static const uint8_t ppm_signature[] = {'P', '6'};
  187. static const uint8_t pgm_signature[] = {'P', '5'};
  188. // Special signatures for PNG chunks
  189. static const char png_chunk_header[] = "IHDR";
  190. static const char png_chunk_palette[] = "PLTE";
  191. static const char png_chunk_data[] = "IDAT";
  192. static const char png_chunk_end[] = "IEND";
  193. typedef struct pdf_object pdf_object;
  194. enum {
  195. OBJ_none, /* skipped */
  196. OBJ_info,
  197. OBJ_stream,
  198. OBJ_font,
  199. OBJ_page,
  200. OBJ_bookmark,
  201. OBJ_outline,
  202. OBJ_catalog,
  203. OBJ_pages,
  204. OBJ_image,
  205. OBJ_link,
  206. OBJ_count,
  207. };
  208. struct flexarray {
  209. void ***bins;
  210. int item_count;
  211. int bin_count;
  212. };
  213. /**
  214. * Simple dynamic string object. Tries to store a reasonable amount on the
  215. * stack before falling back to malloc once things get large
  216. */
  217. struct dstr {
  218. char static_data[128];
  219. char *data;
  220. size_t alloc_len;
  221. size_t used_len;
  222. };
  223. struct pdf_object {
  224. int type; /* See OBJ_xxxx */
  225. int index; /* PDF output index */
  226. int offset; /* Byte position within the output file */
  227. struct pdf_object *prev; /* Previous of this type */
  228. struct pdf_object *next; /* Next of this type */
  229. union {
  230. struct {
  231. struct pdf_object *page;
  232. char name[64];
  233. struct pdf_object *parent;
  234. struct flexarray children;
  235. } bookmark;
  236. struct {
  237. struct pdf_object *page;
  238. struct dstr stream;
  239. } stream;
  240. struct {
  241. float width;
  242. float height;
  243. struct flexarray children;
  244. struct flexarray annotations;
  245. } page;
  246. struct pdf_info *info;
  247. struct {
  248. char name[64];
  249. int index;
  250. } font;
  251. struct {
  252. struct pdf_object *page; /* Page containing link */
  253. float llx; /* Clickable rectangle */
  254. float lly;
  255. float urx;
  256. float ury;
  257. struct pdf_object *target_page; /* Target page */
  258. float target_x; /* Target location */
  259. float target_y;
  260. } link;
  261. };
  262. };
  263. struct pdf_doc {
  264. char errstr[128];
  265. int errval;
  266. struct flexarray objects;
  267. float width;
  268. float height;
  269. struct pdf_object *current_font;
  270. struct pdf_object *last_objects[OBJ_count];
  271. struct pdf_object *first_objects[OBJ_count];
  272. };
  273. /**
  274. * Since we're casting random areas of memory to these, make sure
  275. * they're packed properly to match the image format requirements
  276. */
  277. #pragma pack(push, 1)
  278. struct png_chunk {
  279. uint32_t length;
  280. // chunk type, see png_chunk_header, png_chunk_data, png_chunk_end
  281. char type[4];
  282. };
  283. #pragma pack(pop)
  284. // Simple data container to store a single 24 Bit RGB value, used for
  285. // processing PNG images
  286. struct rgb_value {
  287. uint8_t red;
  288. uint8_t blue;
  289. uint8_t green;
  290. };
  291. /**
  292. * Simple flexible resizing array implementation
  293. * The bins get larger in powers of two
  294. * bin 0 = 1024 items
  295. * 1 = 2048 items
  296. * 2 = 4096 items
  297. * etc...
  298. */
  299. /* What is the first index that will be in the given bin? */
  300. #define MIN_SHIFT 10
  301. #define MIN_OFFSET ((1 << MIN_SHIFT) - 1)
  302. static int bin_offset[] = {
  303. (1 << (MIN_SHIFT + 0)) - 1 - MIN_OFFSET,
  304. (1 << (MIN_SHIFT + 1)) - 1 - MIN_OFFSET,
  305. (1 << (MIN_SHIFT + 2)) - 1 - MIN_OFFSET,
  306. (1 << (MIN_SHIFT + 3)) - 1 - MIN_OFFSET,
  307. (1 << (MIN_SHIFT + 4)) - 1 - MIN_OFFSET,
  308. (1 << (MIN_SHIFT + 5)) - 1 - MIN_OFFSET,
  309. (1 << (MIN_SHIFT + 6)) - 1 - MIN_OFFSET,
  310. (1 << (MIN_SHIFT + 7)) - 1 - MIN_OFFSET,
  311. (1 << (MIN_SHIFT + 8)) - 1 - MIN_OFFSET,
  312. (1 << (MIN_SHIFT + 9)) - 1 - MIN_OFFSET,
  313. (1 << (MIN_SHIFT + 10)) - 1 - MIN_OFFSET,
  314. (1 << (MIN_SHIFT + 11)) - 1 - MIN_OFFSET,
  315. (1 << (MIN_SHIFT + 12)) - 1 - MIN_OFFSET,
  316. (1 << (MIN_SHIFT + 13)) - 1 - MIN_OFFSET,
  317. (1 << (MIN_SHIFT + 14)) - 1 - MIN_OFFSET,
  318. (1 << (MIN_SHIFT + 15)) - 1 - MIN_OFFSET,
  319. };
  320. static inline int flexarray_get_bin(const struct flexarray *flex, int index)
  321. {
  322. (void)flex;
  323. for (size_t i = 0; i < ARRAY_SIZE(bin_offset); i++)
  324. if (index < bin_offset[i])
  325. return i - 1;
  326. return -1;
  327. }
  328. static inline int flexarray_get_bin_size(const struct flexarray *flex,
  329. int bin)
  330. {
  331. (void)flex;
  332. if (bin >= (int)ARRAY_SIZE(bin_offset) - 1)
  333. return -1;
  334. int next = bin_offset[bin + 1];
  335. return next - bin_offset[bin];
  336. }
  337. static inline int flexarray_get_bin_offset(const struct flexarray *flex,
  338. int bin, int index)
  339. {
  340. (void)flex;
  341. return index - bin_offset[bin];
  342. }
  343. static void flexarray_clear(struct flexarray *flex)
  344. {
  345. for (int i = 0; i < flex->bin_count; i++)
  346. free(flex->bins[i]);
  347. free(flex->bins);
  348. flex->bin_count = 0;
  349. flex->item_count = 0;
  350. }
  351. static inline int flexarray_size(const struct flexarray *flex)
  352. {
  353. return flex->item_count;
  354. }
  355. static int flexarray_set(struct flexarray *flex, int index, void *data)
  356. {
  357. int bin = flexarray_get_bin(flex, index);
  358. if (bin < 0)
  359. return -EINVAL;
  360. if (bin >= flex->bin_count) {
  361. void ***bins = (void ***)realloc(flex->bins, (flex->bin_count + 1) *
  362. sizeof(*flex->bins));
  363. if (!bins)
  364. return -ENOMEM;
  365. flex->bin_count++;
  366. flex->bins = bins;
  367. flex->bins[flex->bin_count - 1] =
  368. (void **)calloc(flexarray_get_bin_size(flex, flex->bin_count - 1),
  369. sizeof(void *));
  370. if (!flex->bins[flex->bin_count - 1]) {
  371. flex->bin_count--;
  372. return -ENOMEM;
  373. }
  374. }
  375. flex->item_count++;
  376. flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)] = data;
  377. return flex->item_count - 1;
  378. }
  379. static inline int flexarray_append(struct flexarray *flex, void *data)
  380. {
  381. return flexarray_set(flex, flexarray_size(flex), data);
  382. }
  383. static inline void *flexarray_get(const struct flexarray *flex, int index)
  384. {
  385. int bin;
  386. if (index >= flex->item_count)
  387. return NULL;
  388. bin = flexarray_get_bin(flex, index);
  389. if (bin < 0 || bin >= flex->bin_count)
  390. return NULL;
  391. return flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)];
  392. }
  393. /**
  394. * Simple dynamic string object. Tries to store a reasonable amount on the
  395. * stack before falling back to malloc once things get large
  396. */
  397. #define INIT_DSTR \
  398. (struct dstr) \
  399. { \
  400. .static_data = {0}, .data = NULL, .alloc_len = 0, .used_len = 0 \
  401. }
  402. static char *dstr_data(struct dstr *str)
  403. {
  404. return str->data ? str->data : str->static_data;
  405. }
  406. static size_t dstr_len(const struct dstr *str)
  407. {
  408. return str->used_len;
  409. }
  410. static ssize_t dstr_ensure(struct dstr *str, size_t len)
  411. {
  412. if (len <= str->alloc_len)
  413. return 0;
  414. if (!str->data && len <= sizeof(str->static_data))
  415. str->alloc_len = len;
  416. else if (str->alloc_len < len) {
  417. size_t new_len;
  418. new_len = len + 4096;
  419. if (str->data) {
  420. char *new_data = (char *)realloc((void *)str->data, new_len);
  421. if (!new_data)
  422. return -ENOMEM;
  423. str->data = new_data;
  424. } else {
  425. str->data = (char *)malloc(new_len);
  426. if (!str->data)
  427. return -ENOMEM;
  428. if (str->used_len)
  429. memcpy(str->data, str->static_data, str->used_len + 1);
  430. }
  431. str->alloc_len = new_len;
  432. }
  433. return 0;
  434. }
  435. // Locales can replace the decimal character with a ','.
  436. // This breaks the PDF output, so we force a 'safe' locale.
  437. static void force_locale(char *buf, int len)
  438. {
  439. char *saved_locale = setlocale(LC_ALL, NULL);
  440. if (!saved_locale) {
  441. *buf = '\0';
  442. } else {
  443. strncpy(buf, saved_locale, len - 1);
  444. buf[len - 1] = '\0';
  445. }
  446. setlocale(LC_NUMERIC, "POSIX");
  447. }
  448. static void restore_locale(char *buf)
  449. {
  450. setlocale(LC_ALL, buf);
  451. }
  452. #ifndef SKIP_ATTRIBUTE
  453. static int dstr_printf(struct dstr *str, const char *fmt, ...)
  454. __attribute__((format(printf, 2, 3)));
  455. #endif
  456. static int dstr_printf(struct dstr *str, const char *fmt, ...)
  457. {
  458. va_list ap, aq;
  459. int len;
  460. char saved_locale[32];
  461. force_locale(saved_locale, sizeof(saved_locale));
  462. va_start(ap, fmt);
  463. va_copy(aq, ap);
  464. len = vsnprintf(NULL, 0, fmt, ap);
  465. if (dstr_ensure(str, str->used_len + len + 1) < 0) {
  466. va_end(ap);
  467. va_end(aq);
  468. restore_locale(saved_locale);
  469. return -ENOMEM;
  470. }
  471. vsprintf(dstr_data(str) + str->used_len, fmt, aq);
  472. str->used_len += len;
  473. va_end(ap);
  474. va_end(aq);
  475. restore_locale(saved_locale);
  476. return len;
  477. }
  478. static ssize_t dstr_append_data(struct dstr *str, const void *extend,
  479. size_t len)
  480. {
  481. if (dstr_ensure(str, str->used_len + len + 1) < 0)
  482. return -ENOMEM;
  483. memcpy(dstr_data(str) + str->used_len, extend, len);
  484. str->used_len += len;
  485. dstr_data(str)[str->used_len] = '\0';
  486. return len;
  487. }
  488. static ssize_t dstr_append(struct dstr *str, const char *extend)
  489. {
  490. return dstr_append_data(str, extend, strlen(extend));
  491. }
  492. static void dstr_free(struct dstr *str)
  493. {
  494. if (str->data)
  495. free(str->data);
  496. *str = INIT_DSTR;
  497. }
  498. /**
  499. * PDF Implementation
  500. */
  501. #ifndef SKIP_ATTRIBUTE
  502. static int pdf_set_err(struct pdf_doc *doc, int errval, const char *buffer,
  503. ...) __attribute__((format(printf, 3, 4)));
  504. #endif
  505. static int pdf_set_err(struct pdf_doc *doc, int errval, const char *buffer,
  506. ...)
  507. {
  508. va_list ap;
  509. int len;
  510. va_start(ap, buffer);
  511. len = vsnprintf(doc->errstr, sizeof(doc->errstr) - 1, buffer, ap);
  512. va_end(ap);
  513. if (len < 0) {
  514. doc->errstr[0] = '\0';
  515. return errval;
  516. }
  517. if (len >= (int)(sizeof(doc->errstr) - 1))
  518. len = (int)(sizeof(doc->errstr) - 1);
  519. doc->errstr[len] = '\0';
  520. doc->errval = errval;
  521. return errval;
  522. }
  523. const char *pdf_get_err(const struct pdf_doc *pdf, int *errval)
  524. {
  525. if (!pdf)
  526. return NULL;
  527. if (pdf->errstr[0] == '\0')
  528. return NULL;
  529. if (errval)
  530. *errval = pdf->errval;
  531. return pdf->errstr;
  532. }
  533. void pdf_clear_err(struct pdf_doc *pdf)
  534. {
  535. if (!pdf)
  536. return;
  537. pdf->errstr[0] = '\0';
  538. pdf->errval = 0;
  539. }
  540. static int pdf_get_errval(struct pdf_doc *pdf)
  541. {
  542. if (!pdf)
  543. return 0;
  544. return pdf->errval;
  545. }
  546. static struct pdf_object *pdf_get_object(const struct pdf_doc *pdf, int index)
  547. {
  548. return (struct pdf_object *)flexarray_get(&pdf->objects, index);
  549. }
  550. static int pdf_append_object(struct pdf_doc *pdf, struct pdf_object *obj)
  551. {
  552. int index = flexarray_append(&pdf->objects, obj);
  553. if (index < 0)
  554. return index;
  555. obj->index = index;
  556. if (pdf->last_objects[obj->type]) {
  557. obj->prev = pdf->last_objects[obj->type];
  558. pdf->last_objects[obj->type]->next = obj;
  559. }
  560. pdf->last_objects[obj->type] = obj;
  561. if (!pdf->first_objects[obj->type])
  562. pdf->first_objects[obj->type] = obj;
  563. return 0;
  564. }
  565. static void pdf_object_destroy(struct pdf_object *object)
  566. {
  567. switch (object->type) {
  568. case OBJ_stream:
  569. case OBJ_image:
  570. dstr_free(&object->stream.stream);
  571. break;
  572. case OBJ_page:
  573. flexarray_clear(&object->page.children);
  574. flexarray_clear(&object->page.annotations);
  575. break;
  576. case OBJ_info:
  577. free(object->info);
  578. break;
  579. case OBJ_bookmark:
  580. flexarray_clear(&object->bookmark.children);
  581. break;
  582. }
  583. free(object);
  584. }
  585. static struct pdf_object *pdf_add_object(struct pdf_doc *pdf, int type)
  586. {
  587. struct pdf_object *obj;
  588. if (!pdf)
  589. return NULL;
  590. obj = (struct pdf_object *)calloc(1, sizeof(*obj));
  591. if (!obj) {
  592. pdf_set_err(pdf, -errno,
  593. "Unable to allocate object %d of type %d: %s",
  594. flexarray_size(&pdf->objects) + 1, type, strerror(errno));
  595. return NULL;
  596. }
  597. obj->type = type;
  598. if (pdf_append_object(pdf, obj) < 0) {
  599. free(obj);
  600. return NULL;
  601. }
  602. return obj;
  603. }
  604. static void pdf_del_object(struct pdf_doc *pdf, struct pdf_object *obj)
  605. {
  606. int type = obj->type;
  607. flexarray_set(&pdf->objects, obj->index, NULL);
  608. if (pdf->last_objects[type] == obj) {
  609. pdf->last_objects[type] = NULL;
  610. for (int i = 0; i < flexarray_size(&pdf->objects); i++) {
  611. struct pdf_object *o = pdf_get_object(pdf, i);
  612. if (o && o->type == type)
  613. pdf->last_objects[type] = o;
  614. }
  615. }
  616. if (pdf->first_objects[type] == obj) {
  617. pdf->first_objects[type] = NULL;
  618. for (int i = 0; i < flexarray_size(&pdf->objects); i++) {
  619. struct pdf_object *o = pdf_get_object(pdf, i);
  620. if (o && o->type == type) {
  621. pdf->first_objects[type] = o;
  622. break;
  623. }
  624. }
  625. }
  626. pdf_object_destroy(obj);
  627. }
  628. struct pdf_doc *pdf_create(float width, float height,
  629. const struct pdf_info *info)
  630. {
  631. struct pdf_doc *pdf;
  632. struct pdf_object *obj;
  633. pdf = (struct pdf_doc *)calloc(1, sizeof(*pdf));
  634. if (!pdf)
  635. return NULL;
  636. pdf->width = width;
  637. pdf->height = height;
  638. /* We don't want to use ID 0 */
  639. pdf_add_object(pdf, OBJ_none);
  640. /* Create the 'info' object */
  641. obj = pdf_add_object(pdf, OBJ_info);
  642. if (!obj) {
  643. pdf_destroy(pdf);
  644. return NULL;
  645. }
  646. obj->info = (struct pdf_info *)calloc(sizeof(*obj->info), 1);
  647. if (!obj->info) {
  648. pdf_destroy(pdf);
  649. return NULL;
  650. }
  651. if (info) {
  652. *obj->info = *info;
  653. obj->info->creator[sizeof(obj->info->creator) - 1] = '\0';
  654. obj->info->producer[sizeof(obj->info->producer) - 1] = '\0';
  655. obj->info->title[sizeof(obj->info->title) - 1] = '\0';
  656. obj->info->author[sizeof(obj->info->author) - 1] = '\0';
  657. obj->info->subject[sizeof(obj->info->subject) - 1] = '\0';
  658. obj->info->date[sizeof(obj->info->date) - 1] = '\0';
  659. }
  660. /* FIXME: Should be quoting PDF strings? */
  661. if (!obj->info->date[0]) {
  662. time_t now = time(NULL);
  663. struct tm tm;
  664. #ifdef _WIN32
  665. struct tm *tmp;
  666. tmp = localtime(&now);
  667. tm = *tmp;
  668. #else
  669. localtime_r(&now, &tm);
  670. #endif
  671. strftime(obj->info->date, sizeof(obj->info->date), "%Y%m%d%H%M%SZ",
  672. &tm);
  673. }
  674. if (!pdf_add_object(pdf, OBJ_pages)) {
  675. pdf_destroy(pdf);
  676. return NULL;
  677. }
  678. if (!pdf_add_object(pdf, OBJ_catalog)) {
  679. pdf_destroy(pdf);
  680. return NULL;
  681. }
  682. if (pdf_set_font(pdf, "Times-Roman") < 0) {
  683. pdf_destroy(pdf);
  684. return NULL;
  685. }
  686. return pdf;
  687. }
  688. float pdf_width(const struct pdf_doc *pdf)
  689. {
  690. return pdf->width;
  691. }
  692. float pdf_height(const struct pdf_doc *pdf)
  693. {
  694. return pdf->height;
  695. }
  696. float pdf_page_width(const struct pdf_object *page)
  697. {
  698. return page->page.width;
  699. }
  700. float pdf_page_height(const struct pdf_object *page)
  701. {
  702. return page->page.height;
  703. }
  704. void pdf_destroy(struct pdf_doc *pdf)
  705. {
  706. if (pdf) {
  707. for (int i = 0; i < flexarray_size(&pdf->objects); i++)
  708. pdf_object_destroy(pdf_get_object(pdf, i));
  709. flexarray_clear(&pdf->objects);
  710. free(pdf);
  711. }
  712. }
  713. static struct pdf_object *pdf_find_first_object(const struct pdf_doc *pdf,
  714. int type)
  715. {
  716. if (!pdf)
  717. return NULL;
  718. return pdf->first_objects[type];
  719. }
  720. static struct pdf_object *pdf_find_last_object(const struct pdf_doc *pdf,
  721. int type)
  722. {
  723. if (!pdf)
  724. return NULL;
  725. return pdf->last_objects[type];
  726. }
  727. int pdf_set_font(struct pdf_doc *pdf, const char *font)
  728. {
  729. struct pdf_object *obj;
  730. int last_index = 0;
  731. /* See if we've used this font before */
  732. for (obj = pdf_find_first_object(pdf, OBJ_font); obj; obj = obj->next) {
  733. if (strcmp(obj->font.name, font) == 0)
  734. break;
  735. last_index = obj->font.index;
  736. }
  737. /* Create a new font object if we need it */
  738. if (!obj) {
  739. obj = pdf_add_object(pdf, OBJ_font);
  740. if (!obj)
  741. return pdf->errval;
  742. strncpy(obj->font.name, font, sizeof(obj->font.name) - 1);
  743. obj->font.name[sizeof(obj->font.name) - 1] = '\0';
  744. obj->font.index = last_index + 1;
  745. }
  746. pdf->current_font = obj;
  747. return 0;
  748. }
  749. struct pdf_object *pdf_append_page(struct pdf_doc *pdf)
  750. {
  751. struct pdf_object *page;
  752. page = pdf_add_object(pdf, OBJ_page);
  753. if (!page)
  754. return NULL;
  755. page->page.width = pdf->width;
  756. page->page.height = pdf->height;
  757. return page;
  758. }
  759. struct pdf_object *pdf_get_page(struct pdf_doc *pdf, int page_number)
  760. {
  761. if (page_number <= 0) {
  762. pdf_set_err(pdf, -EINVAL, "page number must be >= 1");
  763. return NULL;
  764. }
  765. for (struct pdf_object *obj = pdf_find_first_object(pdf, OBJ_page); obj;
  766. obj = obj->next, page_number--) {
  767. if (page_number == 1) {
  768. return obj;
  769. }
  770. }
  771. pdf_set_err(pdf, -EINVAL, "no such page");
  772. return NULL;
  773. }
  774. int pdf_page_set_size(struct pdf_doc *pdf, struct pdf_object *page,
  775. float width, float height)
  776. {
  777. if (!page)
  778. page = pdf_find_last_object(pdf, OBJ_page);
  779. if (!page || page->type != OBJ_page)
  780. return pdf_set_err(pdf, -EINVAL, "Invalid PDF page");
  781. page->page.width = width;
  782. page->page.height = height;
  783. return 0;
  784. }
  785. // Recursively scan for the number of children
  786. static int pdf_get_bookmark_count(const struct pdf_object *obj)
  787. {
  788. int count = 0;
  789. if (obj->type == OBJ_bookmark) {
  790. int nchildren = flexarray_size(&obj->bookmark.children);
  791. count += nchildren;
  792. for (int i = 0; i < nchildren; i++) {
  793. count += pdf_get_bookmark_count(
  794. (const struct pdf_object *)flexarray_get(
  795. &obj->bookmark.children, i));
  796. }
  797. }
  798. return count;
  799. }
  800. static int pdf_save_object(struct pdf_doc *pdf, FILE *fp, int index)
  801. {
  802. struct pdf_object *object = pdf_get_object(pdf, index);
  803. if (!object)
  804. return -ENOENT;
  805. if (object->type == OBJ_none)
  806. return -ENOENT;
  807. object->offset = ftell(fp);
  808. fprintf(fp, "%d 0 obj\r\n", index);
  809. switch (object->type) {
  810. case OBJ_stream:
  811. case OBJ_image: {
  812. fwrite(dstr_data(&object->stream.stream),
  813. dstr_len(&object->stream.stream), 1, fp);
  814. break;
  815. }
  816. case OBJ_info: {
  817. struct pdf_info *info = object->info;
  818. fprintf(fp, "<<\r\n");
  819. if (info->creator[0])
  820. fprintf(fp, " /Creator (%s)\r\n", info->creator);
  821. if (info->producer[0])
  822. fprintf(fp, " /Producer (%s)\r\n", info->producer);
  823. if (info->title[0])
  824. fprintf(fp, " /Title (%s)\r\n", info->title);
  825. if (info->author[0])
  826. fprintf(fp, " /Author (%s)\r\n", info->author);
  827. if (info->subject[0])
  828. fprintf(fp, " /Subject (%s)\r\n", info->subject);
  829. if (info->date[0])
  830. fprintf(fp, " /CreationDate (D:%s)\r\n", info->date);
  831. fprintf(fp, ">>\r\n");
  832. break;
  833. }
  834. case OBJ_page: {
  835. struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);
  836. bool printed_xobjects = false;
  837. fprintf(fp,
  838. "<<\r\n"
  839. " /Type /Page\r\n"
  840. " /Parent %d 0 R\r\n",
  841. pages->index);
  842. fprintf(fp, " /MediaBox [0 0 %f %f]\r\n", object->page.width,
  843. object->page.height);
  844. fprintf(fp, " /Resources <<\r\n");
  845. fprintf(fp, " /Font <<\r\n");
  846. for (struct pdf_object *font = pdf_find_first_object(pdf, OBJ_font);
  847. font; font = font->next)
  848. fprintf(fp, " /F%d %d 0 R\r\n", font->font.index,
  849. font->index);
  850. fprintf(fp, " >>\r\n");
  851. // We trim transparency to just 4-bits
  852. fprintf(fp, " /ExtGState <<\r\n");
  853. for (int i = 0; i < 16; i++) {
  854. fprintf(fp, " /GS%d <</ca %f>>\r\n", i,
  855. (float)(15 - i) / 15);
  856. }
  857. fprintf(fp, " >>\r\n");
  858. for (struct pdf_object *image = pdf_find_first_object(pdf, OBJ_image);
  859. image; image = image->next) {
  860. if (image->stream.page == object) {
  861. if (!printed_xobjects) {
  862. fprintf(fp, " /XObject <<");
  863. printed_xobjects = true;
  864. }
  865. fprintf(fp, " /Image%d %d 0 R ", image->index,
  866. image->index);
  867. }
  868. }
  869. if (printed_xobjects)
  870. fprintf(fp, " >>\r\n");
  871. fprintf(fp, " >>\r\n");
  872. fprintf(fp, " /Contents [\r\n");
  873. for (int i = 0; i < flexarray_size(&object->page.children); i++) {
  874. struct pdf_object *child =
  875. (struct pdf_object *)flexarray_get(&object->page.children, i);
  876. fprintf(fp, "%d 0 R\r\n", child->index);
  877. }
  878. fprintf(fp, "]\r\n");
  879. if (flexarray_size(&object->page.annotations)) {
  880. fprintf(fp, " /Annots [\r\n");
  881. for (int i = 0; i < flexarray_size(&object->page.annotations);
  882. i++) {
  883. struct pdf_object *child = (struct pdf_object *)flexarray_get(
  884. &object->page.annotations, i);
  885. fprintf(fp, "%d 0 R\r\n", child->index);
  886. }
  887. fprintf(fp, "]\r\n");
  888. }
  889. fprintf(fp, ">>\r\n");
  890. break;
  891. }
  892. case OBJ_bookmark: {
  893. struct pdf_object *parent, *other;
  894. parent = object->bookmark.parent;
  895. if (!parent)
  896. parent = pdf_find_first_object(pdf, OBJ_outline);
  897. if (!object->bookmark.page)
  898. break;
  899. fprintf(fp,
  900. "<<\r\n"
  901. " /Dest [%d 0 R /XYZ 0 %f null]\r\n"
  902. " /Parent %d 0 R\r\n"
  903. " /Title (%s)\r\n",
  904. object->bookmark.page->index, pdf->height, parent->index,
  905. object->bookmark.name);
  906. int nchildren = flexarray_size(&object->bookmark.children);
  907. if (nchildren > 0) {
  908. struct pdf_object *f, *l;
  909. f = (struct pdf_object *)flexarray_get(&object->bookmark.children,
  910. 0);
  911. l = (struct pdf_object *)flexarray_get(&object->bookmark.children,
  912. nchildren - 1);
  913. fprintf(fp, " /First %d 0 R\r\n", f->index);
  914. fprintf(fp, " /Last %d 0 R\r\n", l->index);
  915. fprintf(fp, " /Count %d\r\n", pdf_get_bookmark_count(object));
  916. }
  917. // Find the previous bookmark with the same parent
  918. for (other = object->prev;
  919. other && other->bookmark.parent != object->bookmark.parent;
  920. other = other->prev)
  921. ;
  922. if (other)
  923. fprintf(fp, " /Prev %d 0 R\r\n", other->index);
  924. // Find the next bookmark with the same parent
  925. for (other = object->next;
  926. other && other->bookmark.parent != object->bookmark.parent;
  927. other = other->next)
  928. ;
  929. if (other)
  930. fprintf(fp, " /Next %d 0 R\r\n", other->index);
  931. fprintf(fp, ">>\r\n");
  932. break;
  933. }
  934. case OBJ_outline: {
  935. struct pdf_object *first, *last, *cur;
  936. first = pdf_find_first_object(pdf, OBJ_bookmark);
  937. last = pdf_find_last_object(pdf, OBJ_bookmark);
  938. if (first && last) {
  939. int count = 0;
  940. cur = first;
  941. while (cur) {
  942. if (!cur->bookmark.parent)
  943. count += pdf_get_bookmark_count(cur) + 1;
  944. cur = cur->next;
  945. }
  946. /* Bookmark outline */
  947. fprintf(fp,
  948. "<<\r\n"
  949. " /Count %d\r\n"
  950. " /Type /Outlines\r\n"
  951. " /First %d 0 R\r\n"
  952. " /Last %d 0 R\r\n"
  953. ">>\r\n",
  954. count, first->index, last->index);
  955. }
  956. break;
  957. }
  958. case OBJ_font:
  959. fprintf(fp,
  960. "<<\r\n"
  961. " /Type /Font\r\n"
  962. " /Subtype /Type1\r\n"
  963. " /BaseFont /%s\r\n"
  964. " /Encoding /WinAnsiEncoding\r\n"
  965. ">>\r\n",
  966. object->font.name);
  967. break;
  968. case OBJ_pages: {
  969. int npages = 0;
  970. fprintf(fp, "<<\r\n"
  971. " /Type /Pages\r\n"
  972. " /Kids [ ");
  973. for (struct pdf_object *page = pdf_find_first_object(pdf, OBJ_page);
  974. page; page = page->next) {
  975. npages++;
  976. fprintf(fp, "%d 0 R ", page->index);
  977. }
  978. fprintf(fp, "]\r\n");
  979. fprintf(fp, " /Count %d\r\n", npages);
  980. fprintf(fp, ">>\r\n");
  981. break;
  982. }
  983. case OBJ_catalog: {
  984. struct pdf_object *outline = pdf_find_first_object(pdf, OBJ_outline);
  985. struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);
  986. fprintf(fp, "<<\r\n"
  987. " /Type /Catalog\r\n");
  988. if (outline)
  989. fprintf(fp,
  990. " /Outlines %d 0 R\r\n"
  991. " /PageMode /UseOutlines\r\n",
  992. outline->index);
  993. fprintf(fp,
  994. " /Pages %d 0 R\r\n"
  995. ">>\r\n",
  996. pages->index);
  997. break;
  998. }
  999. case OBJ_link: {
  1000. fprintf(fp,
  1001. "<<\r\n"
  1002. " /Type /Annot\r\n"
  1003. " /Subtype /Link\r\n"
  1004. " /Rect [%f %f %f %f]\r\n"
  1005. " /Dest [%u 0 R /XYZ %f %f null]\r\n"
  1006. " /Border [0 0 0]\r\n"
  1007. ">>\r\n",
  1008. object->link.llx, object->link.lly, object->link.urx,
  1009. object->link.ury, object->link.target_page->index,
  1010. object->link.target_x, object->link.target_y);
  1011. break;
  1012. }
  1013. default:
  1014. return pdf_set_err(pdf, -EINVAL, "Invalid PDF object type %d",
  1015. object->type);
  1016. }
  1017. fprintf(fp, "endobj\r\n");
  1018. return 0;
  1019. }
  1020. // Slightly modified djb2 hash algorithm to get pseudo-random ID
  1021. static uint64_t hash(uint64_t hash, const void *data, size_t len)
  1022. {
  1023. const uint8_t *d8 = (const uint8_t *)data;
  1024. for (; len; len--) {
  1025. hash = (((hash & 0x03ffffffffffffff) << 5) +
  1026. (hash & 0x7fffffffffffffff)) +
  1027. *d8++;
  1028. }
  1029. return hash;
  1030. }
  1031. int pdf_save_file(struct pdf_doc *pdf, FILE *fp)
  1032. {
  1033. struct pdf_object *obj;
  1034. int xref_offset;
  1035. int xref_count = 0;
  1036. uint64_t id1, id2;
  1037. time_t now = time(NULL);
  1038. char saved_locale[32];
  1039. force_locale(saved_locale, sizeof(saved_locale));
  1040. fprintf(fp, "%%PDF-1.3\r\n");
  1041. /* Hibit bytes */
  1042. fprintf(fp, "%c%c%c%c%c\r\n", 0x25, 0xc7, 0xec, 0x8f, 0xa2);
  1043. /* Dump all the objects & get their file offsets */
  1044. for (int i = 0; i < flexarray_size(&pdf->objects); i++)
  1045. if (pdf_save_object(pdf, fp, i) >= 0)
  1046. xref_count++;
  1047. /* xref */
  1048. xref_offset = ftell(fp);
  1049. fprintf(fp, "xref\r\n");
  1050. fprintf(fp, "0 %d\r\n", xref_count + 1);
  1051. fprintf(fp, "0000000000 65535 f\r\n");
  1052. for (int i = 0; i < flexarray_size(&pdf->objects); i++) {
  1053. obj = pdf_get_object(pdf, i);
  1054. if (obj->type != OBJ_none)
  1055. fprintf(fp, "%10.10d 00000 n\r\n", obj->offset);
  1056. }
  1057. fprintf(fp,
  1058. "trailer\r\n"
  1059. "<<\r\n"
  1060. "/Size %d\r\n",
  1061. xref_count + 1);
  1062. obj = pdf_find_first_object(pdf, OBJ_catalog);
  1063. fprintf(fp, "/Root %d 0 R\r\n", obj->index);
  1064. obj = pdf_find_first_object(pdf, OBJ_info);
  1065. fprintf(fp, "/Info %d 0 R\r\n", obj->index);
  1066. /* Generate document unique IDs */
  1067. id1 = hash(5381, obj->info, sizeof(struct pdf_info));
  1068. id1 = hash(id1, &xref_count, sizeof(xref_count));
  1069. id2 = hash(5381, &now, sizeof(now));
  1070. fprintf(fp, "/ID [<%16.16" PRIx64 "> <%16.16" PRIx64 ">]\r\n", id1, id2);
  1071. fprintf(fp, ">>\r\n"
  1072. "startxref\r\n");
  1073. fprintf(fp, "%d\r\n", xref_offset);
  1074. fprintf(fp, "%%%%EOF\r\n");
  1075. restore_locale(saved_locale);
  1076. return 0;
  1077. }
  1078. int pdf_save(struct pdf_doc *pdf, const char *filename)
  1079. {
  1080. FILE *fp;
  1081. int e;
  1082. if (filename == NULL)
  1083. fp = stdout;
  1084. else if ((fp = fopen(filename, "wb")) == NULL)
  1085. return pdf_set_err(pdf, -errno, "Unable to open '%s': %s", filename,
  1086. strerror(errno));
  1087. e = pdf_save_file(pdf, fp);
  1088. if (fp != stdout)
  1089. if (fclose(fp) != 0 && e >= 0)
  1090. return pdf_set_err(pdf, -errno, "Unable to close '%s': %s",
  1091. filename, strerror(errno));
  1092. return e;
  1093. }
  1094. static int pdf_add_stream(struct pdf_doc *pdf, struct pdf_object *page,
  1095. const char *buffer)
  1096. {
  1097. struct pdf_object *obj;
  1098. size_t len;
  1099. if (!page)
  1100. page = pdf_find_last_object(pdf, OBJ_page);
  1101. if (!page)
  1102. return pdf_set_err(pdf, -EINVAL, "Invalid pdf page");
  1103. len = strlen(buffer);
  1104. /* We don't want any trailing whitespace in the stream */
  1105. while (len >= 1 && (buffer[len - 1] == '\r' || buffer[len - 1] == '\n'))
  1106. len--;
  1107. obj = pdf_add_object(pdf, OBJ_stream);
  1108. if (!obj)
  1109. return pdf->errval;
  1110. dstr_printf(&obj->stream.stream, "<< /Length %zu >>stream\r\n", len);
  1111. dstr_append_data(&obj->stream.stream, buffer, len);
  1112. dstr_append(&obj->stream.stream, "\r\nendstream\r\n");
  1113. return flexarray_append(&page->page.children, obj);
  1114. }
  1115. int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page, int parent,
  1116. const char *name)
  1117. {
  1118. struct pdf_object *obj, *outline = NULL;
  1119. if (!page)
  1120. page = pdf_find_last_object(pdf, OBJ_page);
  1121. if (!page)
  1122. return pdf_set_err(pdf, -EINVAL,
  1123. "Unable to add bookmark, no pages available");
  1124. if (!pdf_find_first_object(pdf, OBJ_outline)) {
  1125. outline = pdf_add_object(pdf, OBJ_outline);
  1126. if (!outline)
  1127. return pdf->errval;
  1128. }
  1129. obj = pdf_add_object(pdf, OBJ_bookmark);
  1130. if (!obj) {
  1131. if (outline)
  1132. pdf_del_object(pdf, outline);
  1133. return pdf->errval;
  1134. }
  1135. strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name) - 1);
  1136. obj->bookmark.name[sizeof(obj->bookmark.name) - 1] = '\0';
  1137. obj->bookmark.page = page;
  1138. if (parent >= 0) {
  1139. struct pdf_object *parent_obj = pdf_get_object(pdf, parent);
  1140. if (!parent_obj)
  1141. return pdf_set_err(pdf, -EINVAL, "Invalid parent ID %d supplied",
  1142. parent);
  1143. obj->bookmark.parent = parent_obj;
  1144. flexarray_append(&parent_obj->bookmark.children, obj);
  1145. }
  1146. return obj->index;
  1147. }
  1148. int pdf_add_link(struct pdf_doc *pdf, struct pdf_object *page, float x,
  1149. float y, float width, float height,
  1150. struct pdf_object *target_page, float target_x,
  1151. float target_y)
  1152. {
  1153. struct pdf_object *obj;
  1154. if (!page)
  1155. page = pdf_find_last_object(pdf, OBJ_page);
  1156. if (!page)
  1157. return pdf_set_err(pdf, -EINVAL,
  1158. "Unable to add link, no pages available");
  1159. if (!target_page)
  1160. return pdf_set_err(pdf, -EINVAL, "Unable to link, no target page");
  1161. obj = pdf_add_object(pdf, OBJ_link);
  1162. if (!obj) {
  1163. return pdf->errval;
  1164. }
  1165. obj->link.target_page = target_page;
  1166. obj->link.target_x = target_x;
  1167. obj->link.target_y = target_y;
  1168. obj->link.llx = x;
  1169. obj->link.lly = y;
  1170. obj->link.urx = x + width;
  1171. obj->link.ury = y + height;
  1172. flexarray_append(&page->page.annotations, obj);
  1173. return obj->index;
  1174. }
  1175. static int utf8_to_utf32(const char *utf8, int len, uint32_t *utf32)
  1176. {
  1177. uint32_t ch;
  1178. uint8_t mask;
  1179. if (len <= 0 || !utf8 || !utf32)
  1180. return -EINVAL;
  1181. ch = *(uint8_t *)utf8;
  1182. if ((ch & 0x80) == 0) {
  1183. len = 1;
  1184. mask = 0x7f;
  1185. } else if ((ch & 0xe0) == 0xc0 && len >= 2) {
  1186. len = 2;
  1187. mask = 0x1f;
  1188. } else if ((ch & 0xf0) == 0xe0 && len >= 3) {
  1189. len = 3;
  1190. mask = 0xf;
  1191. } else if ((ch & 0xf8) == 0xf0 && len >= 4) {
  1192. len = 4;
  1193. mask = 0x7;
  1194. } else
  1195. return -EINVAL;
  1196. ch = 0;
  1197. for (int i = 0; i < len; i++) {
  1198. int shift = (len - i - 1) * 6;
  1199. if (!*utf8)
  1200. return -EINVAL;
  1201. if (i == 0)
  1202. ch |= ((uint32_t)(*utf8++) & mask) << shift;
  1203. else
  1204. ch |= ((uint32_t)(*utf8++) & 0x3f) << shift;
  1205. }
  1206. *utf32 = ch;
  1207. return len;
  1208. }
  1209. static int utf8_to_pdfencoding(struct pdf_doc *pdf, const char *utf8, int len,
  1210. uint8_t *res)
  1211. {
  1212. uint32_t code;
  1213. int code_len;
  1214. *res = 0;
  1215. code_len = utf8_to_utf32(utf8, len, &code);
  1216. if (code_len < 0) {
  1217. return pdf_set_err(pdf, -EINVAL, "Invalid UTF-8 encoding");
  1218. }
  1219. if (code > 255) {
  1220. /* We support *some* minimal UTF-8 characters */
  1221. // See Appendix D of
  1222. // https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.7old.pdf
  1223. // These are all in WinAnsiEncoding
  1224. switch (code) {
  1225. case 0x152: // Latin Capital Ligature OE
  1226. *res = 0214;
  1227. break;
  1228. case 0x153: // Latin Small Ligature oe
  1229. *res = 0234;
  1230. break;
  1231. case 0x160: // Latin Capital Letter S with caron
  1232. *res = 0212;
  1233. break;
  1234. case 0x161: // Latin Small Letter S with caron
  1235. *res = 0232;
  1236. break;
  1237. case 0x178: // Latin Capital Letter y with diaeresis
  1238. *res = 0237;
  1239. break;
  1240. case 0x17d: // Latin Capital Letter Z with caron
  1241. *res = 0216;
  1242. break;
  1243. case 0x17e: // Latin Small Letter Z with caron
  1244. *res = 0236;
  1245. break;
  1246. case 0x192: // Latin Small Letter F with hook
  1247. *res = 0203;
  1248. break;
  1249. case 0x2c6: // Modifier Letter Circumflex Accent
  1250. *res = 0210;
  1251. break;
  1252. case 0x2dc: // Small Tilde
  1253. *res = 0230;
  1254. break;
  1255. case 0x2013: // Endash
  1256. *res = 0226;
  1257. break;
  1258. case 0x2014: // Emdash
  1259. *res = 0227;
  1260. break;
  1261. case 0x2018: // Left Single Quote
  1262. *res = 0221;
  1263. break;
  1264. case 0x2019: // Right Single Quote
  1265. *res = 0222;
  1266. break;
  1267. case 0x201a: // Single low-9 Quotation Mark
  1268. *res = 0202;
  1269. break;
  1270. case 0x201c: // Left Double Quote
  1271. *res = 0223;
  1272. break;
  1273. case 0x201d: // Right Double Quote
  1274. *res = 0224;
  1275. break;
  1276. case 0x201e: // Double low-9 Quotation Mark
  1277. *res = 0204;
  1278. break;
  1279. case 0x2020: // Dagger
  1280. *res = 0206;
  1281. break;
  1282. case 0x2021: // Double Dagger
  1283. *res = 0207;
  1284. break;
  1285. case 0x2022: // Bullet
  1286. *res = 0225;
  1287. break;
  1288. case 0x2026: // Horizontal Ellipsis
  1289. *res = 0205;
  1290. break;
  1291. case 0x2030: // Per Mille Sign
  1292. *res = 0211;
  1293. break;
  1294. case 0x2039: // Single Left-pointing Angle Quotation Mark
  1295. *res = 0213;
  1296. break;
  1297. case 0x203a: // Single Right-pointing Angle Quotation Mark
  1298. *res = 0233;
  1299. break;
  1300. case 0x20ac: // Euro
  1301. *res = 0200;
  1302. break;
  1303. case 0x2122: // Trade Mark Sign
  1304. *res = 0231;
  1305. break;
  1306. default:
  1307. return pdf_set_err(pdf, -EINVAL,
  1308. "Unsupported UTF-8 character: 0x%x 0o%o %s",
  1309. code, code, utf8);
  1310. }
  1311. } else {
  1312. *res = code;
  1313. }
  1314. return code_len;
  1315. }
  1316. static int pdf_add_text_spacing(struct pdf_doc *pdf, struct pdf_object *page,
  1317. const char *text, float size, float xoff,
  1318. float yoff, uint32_t colour, float spacing,
  1319. float angle)
  1320. {
  1321. int ret;
  1322. size_t len = text ? strlen(text) : 0;
  1323. struct dstr str = INIT_DSTR;
  1324. int alpha = (colour >> 24) >> 4;
  1325. /* Don't bother adding empty/null strings */
  1326. if (!len)
  1327. return 0;
  1328. dstr_append(&str, "BT ");
  1329. dstr_printf(&str, "/GS%d gs ", alpha);
  1330. if (angle != 0) {
  1331. dstr_printf(&str, "%f %f %f %f %f %f Tm ", cosf(angle), sinf(angle),
  1332. -sinf(angle), cosf(angle), xoff, yoff);
  1333. } else {
  1334. dstr_printf(&str, "%f %f TD ", xoff, yoff);
  1335. }
  1336. dstr_printf(&str, "/F%d %f Tf ", pdf->current_font->font.index, size);
  1337. dstr_printf(&str, "%f %f %f rg ", PDF_RGB_R(colour), PDF_RGB_G(colour),
  1338. PDF_RGB_B(colour));
  1339. dstr_printf(&str, "%f Tc ", spacing);
  1340. dstr_append(&str, "(");
  1341. /* Escape magic characters properly */
  1342. for (size_t i = 0; i < len;) {
  1343. int code_len;
  1344. uint8_t pdf_char;
  1345. code_len = utf8_to_pdfencoding(pdf, &text[i], len - i, &pdf_char);
  1346. if (code_len < 0) {
  1347. dstr_free(&str);
  1348. return code_len;
  1349. }
  1350. if (strchr("()\\", pdf_char)) {
  1351. char buf[3];
  1352. /* Escape some characters */
  1353. buf[0] = '\\';
  1354. buf[1] = pdf_char;
  1355. buf[2] = '\0';
  1356. dstr_append(&str, buf);
  1357. } else if (strrchr("\n\r\t\b\f", pdf_char)) {
  1358. /* Skip over these characters */
  1359. ;
  1360. } else {
  1361. dstr_append_data(&str, &pdf_char, 1);
  1362. }
  1363. i += code_len;
  1364. }
  1365. dstr_append(&str, ") Tj ");
  1366. dstr_append(&str, "ET");
  1367. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1368. dstr_free(&str);
  1369. return ret;
  1370. }
  1371. int pdf_add_text(struct pdf_doc *pdf, struct pdf_object *page,
  1372. const char *text, float size, float xoff, float yoff,
  1373. uint32_t colour)
  1374. {
  1375. return pdf_add_text_spacing(pdf, page, text, size, xoff, yoff, colour, 0,
  1376. 0);
  1377. }
  1378. int pdf_add_text_rotate(struct pdf_doc *pdf, struct pdf_object *page,
  1379. const char *text, float size, float xoff, float yoff,
  1380. float angle, uint32_t colour)
  1381. {
  1382. return pdf_add_text_spacing(pdf, page, text, size, xoff, yoff, colour, 0,
  1383. angle);
  1384. }
  1385. /* How wide is each character, in points, at size 14 */
  1386. static const uint16_t helvetica_widths[256] = {
  1387. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1388. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1389. 280, 280, 280, 280, 280, 280, 280, 280, 357, 560, 560, 896, 672,
  1390. 192, 335, 335, 392, 588, 280, 335, 280, 280, 560, 560, 560, 560,
  1391. 560, 560, 560, 560, 560, 560, 280, 280, 588, 588, 588, 560, 1023,
  1392. 672, 672, 727, 727, 672, 615, 784, 727, 280, 504, 672, 560, 839,
  1393. 727, 784, 672, 784, 727, 672, 615, 727, 672, 951, 672, 672, 615,
  1394. 280, 280, 280, 472, 560, 335, 560, 560, 504, 560, 560, 280, 560,
  1395. 560, 223, 223, 504, 223, 839, 560, 560, 560, 560, 335, 504, 280,
  1396. 560, 504, 727, 504, 504, 504, 336, 262, 336, 588, 352, 560, 352,
  1397. 223, 560, 335, 1008, 560, 560, 335, 1008, 672, 335, 1008, 352, 615,
  1398. 352, 352, 223, 223, 335, 335, 352, 560, 1008, 335, 1008, 504, 335,
  1399. 951, 352, 504, 672, 280, 335, 560, 560, 560, 560, 262, 560, 335,
  1400. 742, 372, 560, 588, 335, 742, 335, 403, 588, 335, 335, 335, 560,
  1401. 541, 280, 335, 335, 367, 560, 840, 840, 840, 615, 672, 672, 672,
  1402. 672, 672, 672, 1008, 727, 672, 672, 672, 672, 280, 280, 280, 280,
  1403. 727, 727, 784, 784, 784, 784, 784, 588, 784, 727, 727, 727, 727,
  1404. 672, 672, 615, 560, 560, 560, 560, 560, 560, 896, 504, 560, 560,
  1405. 560, 560, 280, 280, 280, 280, 560, 560, 560, 560, 560, 560, 560,
  1406. 588, 615, 560, 560, 560, 560, 504, 560, 504,
  1407. };
  1408. static const uint16_t helvetica_bold_widths[256] = {
  1409. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1410. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1411. 280, 280, 280, 280, 280, 335, 477, 560, 560, 896, 727, 239, 335, 335,
  1412. 392, 588, 280, 335, 280, 280, 560, 560, 560, 560, 560, 560, 560, 560,
  1413. 560, 560, 335, 335, 588, 588, 588, 615, 982, 727, 727, 727, 727, 672,
  1414. 615, 784, 727, 280, 560, 727, 615, 839, 727, 784, 672, 784, 727, 672,
  1415. 615, 727, 672, 951, 672, 672, 615, 335, 280, 335, 588, 560, 335, 560,
  1416. 615, 560, 615, 560, 335, 615, 615, 280, 280, 560, 280, 896, 615, 615,
  1417. 615, 615, 392, 560, 335, 615, 560, 784, 560, 560, 504, 392, 282, 392,
  1418. 588, 352, 560, 352, 280, 560, 504, 1008, 560, 560, 335, 1008, 672, 335,
  1419. 1008, 352, 615, 352, 352, 280, 280, 504, 504, 352, 560, 1008, 335, 1008,
  1420. 560, 335, 951, 352, 504, 672, 280, 335, 560, 560, 560, 560, 282, 560,
  1421. 335, 742, 372, 560, 588, 335, 742, 335, 403, 588, 335, 335, 335, 615,
  1422. 560, 280, 335, 335, 367, 560, 840, 840, 840, 615, 727, 727, 727, 727,
  1423. 727, 727, 1008, 727, 672, 672, 672, 672, 280, 280, 280, 280, 727, 727,
  1424. 784, 784, 784, 784, 784, 588, 784, 727, 727, 727, 727, 672, 672, 615,
  1425. 560, 560, 560, 560, 560, 560, 896, 560, 560, 560, 560, 560, 280, 280,
  1426. 280, 280, 615, 615, 615, 615, 615, 615, 615, 588, 615, 615, 615, 615,
  1427. 615, 560, 615, 560,
  1428. };
  1429. static const uint16_t helvetica_bold_oblique_widths[256] = {
  1430. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1431. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1432. 280, 280, 280, 280, 280, 335, 477, 560, 560, 896, 727, 239, 335, 335,
  1433. 392, 588, 280, 335, 280, 280, 560, 560, 560, 560, 560, 560, 560, 560,
  1434. 560, 560, 335, 335, 588, 588, 588, 615, 982, 727, 727, 727, 727, 672,
  1435. 615, 784, 727, 280, 560, 727, 615, 839, 727, 784, 672, 784, 727, 672,
  1436. 615, 727, 672, 951, 672, 672, 615, 335, 280, 335, 588, 560, 335, 560,
  1437. 615, 560, 615, 560, 335, 615, 615, 280, 280, 560, 280, 896, 615, 615,
  1438. 615, 615, 392, 560, 335, 615, 560, 784, 560, 560, 504, 392, 282, 392,
  1439. 588, 352, 560, 352, 280, 560, 504, 1008, 560, 560, 335, 1008, 672, 335,
  1440. 1008, 352, 615, 352, 352, 280, 280, 504, 504, 352, 560, 1008, 335, 1008,
  1441. 560, 335, 951, 352, 504, 672, 280, 335, 560, 560, 560, 560, 282, 560,
  1442. 335, 742, 372, 560, 588, 335, 742, 335, 403, 588, 335, 335, 335, 615,
  1443. 560, 280, 335, 335, 367, 560, 840, 840, 840, 615, 727, 727, 727, 727,
  1444. 727, 727, 1008, 727, 672, 672, 672, 672, 280, 280, 280, 280, 727, 727,
  1445. 784, 784, 784, 784, 784, 588, 784, 727, 727, 727, 727, 672, 672, 615,
  1446. 560, 560, 560, 560, 560, 560, 896, 560, 560, 560, 560, 560, 280, 280,
  1447. 280, 280, 615, 615, 615, 615, 615, 615, 615, 588, 615, 615, 615, 615,
  1448. 615, 560, 615, 560,
  1449. };
  1450. static const uint16_t helvetica_oblique_widths[256] = {
  1451. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1452. 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  1453. 280, 280, 280, 280, 280, 280, 280, 280, 357, 560, 560, 896, 672,
  1454. 192, 335, 335, 392, 588, 280, 335, 280, 280, 560, 560, 560, 560,
  1455. 560, 560, 560, 560, 560, 560, 280, 280, 588, 588, 588, 560, 1023,
  1456. 672, 672, 727, 727, 672, 615, 784, 727, 280, 504, 672, 560, 839,
  1457. 727, 784, 672, 784, 727, 672, 615, 727, 672, 951, 672, 672, 615,
  1458. 280, 280, 280, 472, 560, 335, 560, 560, 504, 560, 560, 280, 560,
  1459. 560, 223, 223, 504, 223, 839, 560, 560, 560, 560, 335, 504, 280,
  1460. 560, 504, 727, 504, 504, 504, 336, 262, 336, 588, 352, 560, 352,
  1461. 223, 560, 335, 1008, 560, 560, 335, 1008, 672, 335, 1008, 352, 615,
  1462. 352, 352, 223, 223, 335, 335, 352, 560, 1008, 335, 1008, 504, 335,
  1463. 951, 352, 504, 672, 280, 335, 560, 560, 560, 560, 262, 560, 335,
  1464. 742, 372, 560, 588, 335, 742, 335, 403, 588, 335, 335, 335, 560,
  1465. 541, 280, 335, 335, 367, 560, 840, 840, 840, 615, 672, 672, 672,
  1466. 672, 672, 672, 1008, 727, 672, 672, 672, 672, 280, 280, 280, 280,
  1467. 727, 727, 784, 784, 784, 784, 784, 588, 784, 727, 727, 727, 727,
  1468. 672, 672, 615, 560, 560, 560, 560, 560, 560, 896, 504, 560, 560,
  1469. 560, 560, 280, 280, 280, 280, 560, 560, 560, 560, 560, 560, 560,
  1470. 588, 615, 560, 560, 560, 560, 504, 560, 504,
  1471. };
  1472. static const uint16_t symbol_widths[256] = {
  1473. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1474. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1475. 252, 252, 252, 252, 252, 335, 718, 504, 553, 839, 784, 442, 335, 335,
  1476. 504, 553, 252, 553, 252, 280, 504, 504, 504, 504, 504, 504, 504, 504,
  1477. 504, 504, 280, 280, 553, 553, 553, 447, 553, 727, 672, 727, 616, 615,
  1478. 769, 607, 727, 335, 636, 727, 691, 896, 727, 727, 774, 746, 560, 596,
  1479. 615, 695, 442, 774, 650, 801, 615, 335, 869, 335, 663, 504, 504, 636,
  1480. 553, 553, 497, 442, 525, 414, 607, 331, 607, 553, 553, 580, 525, 553,
  1481. 553, 525, 553, 607, 442, 580, 718, 691, 496, 691, 497, 483, 201, 483,
  1482. 553, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1484. 0, 0, 0, 0, 0, 0, 756, 624, 248, 553, 168, 718, 504, 759,
  1485. 759, 759, 759, 1050, 994, 607, 994, 607, 403, 553, 414, 553, 553, 718,
  1486. 497, 463, 553, 553, 553, 553, 1008, 607, 1008, 663, 829, 691, 801, 994,
  1487. 774, 774, 829, 774, 774, 718, 718, 718, 718, 718, 718, 718, 774, 718,
  1488. 796, 796, 897, 829, 553, 252, 718, 607, 607, 1050, 994, 607, 994, 607,
  1489. 497, 331, 796, 796, 792, 718, 387, 387, 387, 387, 387, 387, 497, 497,
  1490. 497, 497, 0, 331, 276, 691, 691, 691, 387, 387, 387, 387, 387, 387,
  1491. 497, 497, 497, 0,
  1492. };
  1493. static const uint16_t times_widths[256] = {
  1494. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1495. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1496. 252, 252, 252, 252, 252, 335, 411, 504, 504, 839, 784, 181, 335, 335,
  1497. 504, 568, 252, 335, 252, 280, 504, 504, 504, 504, 504, 504, 504, 504,
  1498. 504, 504, 280, 280, 568, 568, 568, 447, 928, 727, 672, 672, 727, 615,
  1499. 560, 727, 727, 335, 392, 727, 615, 896, 727, 727, 560, 727, 672, 560,
  1500. 615, 727, 727, 951, 727, 727, 615, 335, 280, 335, 472, 504, 335, 447,
  1501. 504, 447, 504, 447, 335, 504, 504, 280, 280, 504, 280, 784, 504, 504,
  1502. 504, 504, 335, 392, 280, 504, 504, 727, 504, 504, 447, 483, 201, 483,
  1503. 545, 352, 504, 352, 335, 504, 447, 1008, 504, 504, 335, 1008, 560, 335,
  1504. 896, 352, 615, 352, 352, 335, 335, 447, 447, 352, 504, 1008, 335, 987,
  1505. 392, 335, 727, 352, 447, 727, 252, 335, 504, 504, 504, 504, 201, 504,
  1506. 335, 766, 278, 504, 568, 335, 766, 335, 403, 568, 302, 302, 335, 504,
  1507. 456, 252, 335, 302, 312, 504, 756, 756, 756, 447, 727, 727, 727, 727,
  1508. 727, 727, 896, 672, 615, 615, 615, 615, 335, 335, 335, 335, 727, 727,
  1509. 727, 727, 727, 727, 727, 568, 727, 727, 727, 727, 727, 727, 560, 504,
  1510. 447, 447, 447, 447, 447, 447, 672, 447, 447, 447, 447, 447, 280, 280,
  1511. 280, 280, 504, 504, 504, 504, 504, 504, 504, 568, 504, 504, 504, 504,
  1512. 504, 504, 504, 504,
  1513. };
  1514. static const uint16_t times_bold_widths[256] = {
  1515. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1516. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1517. 252, 252, 252, 252, 252, 252, 252, 335, 559, 504, 504, 1008, 839,
  1518. 280, 335, 335, 504, 574, 252, 335, 252, 280, 504, 504, 504, 504,
  1519. 504, 504, 504, 504, 504, 504, 335, 335, 574, 574, 574, 504, 937,
  1520. 727, 672, 727, 727, 672, 615, 784, 784, 392, 504, 784, 672, 951,
  1521. 727, 784, 615, 784, 727, 560, 672, 727, 727, 1008, 727, 727, 672,
  1522. 335, 280, 335, 585, 504, 335, 504, 560, 447, 560, 447, 335, 504,
  1523. 560, 280, 335, 560, 280, 839, 560, 504, 560, 560, 447, 392, 335,
  1524. 560, 504, 727, 504, 504, 447, 397, 221, 397, 524, 352, 504, 352,
  1525. 335, 504, 504, 1008, 504, 504, 335, 1008, 560, 335, 1008, 352, 672,
  1526. 352, 352, 335, 335, 504, 504, 352, 504, 1008, 335, 1008, 392, 335,
  1527. 727, 352, 447, 727, 252, 335, 504, 504, 504, 504, 221, 504, 335,
  1528. 752, 302, 504, 574, 335, 752, 335, 403, 574, 302, 302, 335, 560,
  1529. 544, 252, 335, 302, 332, 504, 756, 756, 756, 504, 727, 727, 727,
  1530. 727, 727, 727, 1008, 727, 672, 672, 672, 672, 392, 392, 392, 392,
  1531. 727, 727, 784, 784, 784, 784, 784, 574, 784, 727, 727, 727, 727,
  1532. 727, 615, 560, 504, 504, 504, 504, 504, 504, 727, 447, 447, 447,
  1533. 447, 447, 280, 280, 280, 280, 504, 560, 504, 504, 504, 504, 504,
  1534. 574, 504, 560, 560, 560, 560, 504, 560, 504,
  1535. };
  1536. static const uint16_t times_bold_italic_widths[256] = {
  1537. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1538. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1539. 252, 252, 252, 252, 252, 392, 559, 504, 504, 839, 784, 280, 335, 335,
  1540. 504, 574, 252, 335, 252, 280, 504, 504, 504, 504, 504, 504, 504, 504,
  1541. 504, 504, 335, 335, 574, 574, 574, 504, 838, 672, 672, 672, 727, 672,
  1542. 672, 727, 784, 392, 504, 672, 615, 896, 727, 727, 615, 727, 672, 560,
  1543. 615, 727, 672, 896, 672, 615, 615, 335, 280, 335, 574, 504, 335, 504,
  1544. 504, 447, 504, 447, 335, 504, 560, 280, 280, 504, 280, 784, 560, 504,
  1545. 504, 504, 392, 392, 280, 560, 447, 672, 504, 447, 392, 350, 221, 350,
  1546. 574, 352, 504, 352, 335, 504, 504, 1008, 504, 504, 335, 1008, 560, 335,
  1547. 951, 352, 615, 352, 352, 335, 335, 504, 504, 352, 504, 1008, 335, 1008,
  1548. 392, 335, 727, 352, 392, 615, 252, 392, 504, 504, 504, 504, 221, 504,
  1549. 335, 752, 268, 504, 610, 335, 752, 335, 403, 574, 302, 302, 335, 580,
  1550. 504, 252, 335, 302, 302, 504, 756, 756, 756, 504, 672, 672, 672, 672,
  1551. 672, 672, 951, 672, 672, 672, 672, 672, 392, 392, 392, 392, 727, 727,
  1552. 727, 727, 727, 727, 727, 574, 727, 727, 727, 727, 727, 615, 615, 504,
  1553. 504, 504, 504, 504, 504, 504, 727, 447, 447, 447, 447, 447, 280, 280,
  1554. 280, 280, 504, 560, 504, 504, 504, 504, 504, 574, 504, 560, 560, 560,
  1555. 560, 447, 504, 447,
  1556. };
  1557. static const uint16_t times_italic_widths[256] = {
  1558. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1559. 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  1560. 252, 252, 252, 252, 252, 335, 423, 504, 504, 839, 784, 215, 335, 335,
  1561. 504, 680, 252, 335, 252, 280, 504, 504, 504, 504, 504, 504, 504, 504,
  1562. 504, 504, 335, 335, 680, 680, 680, 504, 927, 615, 615, 672, 727, 615,
  1563. 615, 727, 727, 335, 447, 672, 560, 839, 672, 727, 615, 727, 615, 504,
  1564. 560, 727, 615, 839, 615, 560, 560, 392, 280, 392, 425, 504, 335, 504,
  1565. 504, 447, 504, 447, 280, 504, 504, 280, 280, 447, 280, 727, 504, 504,
  1566. 504, 504, 392, 392, 280, 504, 447, 672, 447, 447, 392, 403, 277, 403,
  1567. 545, 352, 504, 352, 335, 504, 560, 896, 504, 504, 335, 1008, 504, 335,
  1568. 951, 352, 560, 352, 352, 335, 335, 560, 560, 352, 504, 896, 335, 987,
  1569. 392, 335, 672, 352, 392, 560, 252, 392, 504, 504, 504, 504, 277, 504,
  1570. 335, 766, 278, 504, 680, 335, 766, 335, 403, 680, 302, 302, 335, 504,
  1571. 527, 252, 335, 302, 312, 504, 756, 756, 756, 504, 615, 615, 615, 615,
  1572. 615, 615, 896, 672, 615, 615, 615, 615, 335, 335, 335, 335, 727, 672,
  1573. 727, 727, 727, 727, 727, 680, 727, 727, 727, 727, 727, 560, 615, 504,
  1574. 504, 504, 504, 504, 504, 504, 672, 447, 447, 447, 447, 447, 280, 280,
  1575. 280, 280, 504, 504, 504, 504, 504, 504, 504, 680, 504, 504, 504, 504,
  1576. 504, 447, 504, 447,
  1577. };
  1578. static const uint16_t zapfdingbats_widths[256] = {
  1579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1581. 0, 0, 0, 0, 280, 981, 968, 981, 987, 724, 795, 796, 797, 695,
  1582. 967, 946, 553, 861, 918, 940, 918, 952, 981, 761, 852, 768, 767, 575,
  1583. 682, 769, 766, 765, 760, 497, 556, 541, 581, 697, 792, 794, 794, 796,
  1584. 799, 800, 822, 829, 795, 847, 829, 839, 822, 837, 930, 749, 728, 754,
  1585. 796, 798, 700, 782, 774, 798, 765, 712, 713, 687, 706, 832, 821, 795,
  1586. 795, 712, 692, 701, 694, 792, 793, 718, 797, 791, 797, 879, 767, 768,
  1587. 768, 765, 765, 899, 899, 794, 790, 441, 139, 279, 418, 395, 395, 673,
  1588. 673, 0, 393, 393, 319, 319, 278, 278, 513, 513, 413, 413, 235, 235,
  1589. 336, 336, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1590. 0, 0, 0, 0, 0, 0, 0, 737, 548, 548, 917, 672, 766, 766,
  1591. 782, 599, 699, 631, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794,
  1592. 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794,
  1593. 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794, 794,
  1594. 794, 794, 901, 844, 1024, 461, 753, 931, 753, 925, 934, 935, 935, 840,
  1595. 879, 834, 931, 931, 924, 937, 938, 466, 890, 842, 842, 873, 873, 701,
  1596. 701, 880, 0, 880, 766, 953, 777, 871, 777, 895, 974, 895, 837, 879,
  1597. 934, 977, 925, 0,
  1598. };
  1599. static const uint16_t courier_widths[256] = {
  1600. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1601. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1602. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1603. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1604. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1605. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1606. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1607. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1608. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1609. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1610. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1611. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1612. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1613. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1614. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1615. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1616. 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604,
  1617. 604,
  1618. };
  1619. static int pdf_text_point_width(struct pdf_doc *pdf, const char *text,
  1620. ptrdiff_t text_len, float size,
  1621. const uint16_t *widths, float *point_width)
  1622. {
  1623. uint32_t len = 0;
  1624. if (text_len < 0)
  1625. text_len = strlen(text);
  1626. *point_width = 0.0f;
  1627. for (int i = 0; i < (int)text_len;) {
  1628. uint8_t pdf_char = 0;
  1629. int code_len;
  1630. code_len =
  1631. utf8_to_pdfencoding(pdf, &text[i], text_len - i, &pdf_char);
  1632. if (code_len < 0)
  1633. return pdf_set_err(pdf, code_len,
  1634. "Invalid unicode string at position %d in %s",
  1635. i, text);
  1636. i += code_len;
  1637. if (pdf_char != '\n' && pdf_char != '\r')
  1638. len += widths[pdf_char];
  1639. }
  1640. /* Our widths arrays are for 14pt fonts */
  1641. *point_width = len * size / (14.0f * 72.0f);
  1642. return 0;
  1643. }
  1644. static const uint16_t *find_font_widths(const char *font_name)
  1645. {
  1646. if (strcasecmp(font_name, "Helvetica") == 0)
  1647. return helvetica_widths;
  1648. if (strcasecmp(font_name, "Helvetica-Bold") == 0)
  1649. return helvetica_bold_widths;
  1650. if (strcasecmp(font_name, "Helvetica-BoldOblique") == 0)
  1651. return helvetica_bold_oblique_widths;
  1652. if (strcasecmp(font_name, "Helvetica-Oblique") == 0)
  1653. return helvetica_oblique_widths;
  1654. if (strcasecmp(font_name, "Courier") == 0 ||
  1655. strcasecmp(font_name, "Courier-Bold") == 0 ||
  1656. strcasecmp(font_name, "Courier-BoldOblique") == 0 ||
  1657. strcasecmp(font_name, "Courier-Oblique") == 0)
  1658. return courier_widths;
  1659. if (strcasecmp(font_name, "Times-Roman") == 0)
  1660. return times_widths;
  1661. if (strcasecmp(font_name, "Times-Bold") == 0)
  1662. return times_bold_widths;
  1663. if (strcasecmp(font_name, "Times-Italic") == 0)
  1664. return times_italic_widths;
  1665. if (strcasecmp(font_name, "Times-BoldItalic") == 0)
  1666. return times_bold_italic_widths;
  1667. if (strcasecmp(font_name, "Symbol") == 0)
  1668. return symbol_widths;
  1669. if (strcasecmp(font_name, "ZapfDingbats") == 0)
  1670. return zapfdingbats_widths;
  1671. return NULL;
  1672. }
  1673. int pdf_get_font_text_width(struct pdf_doc *pdf, const char *font_name,
  1674. const char *text, float size, float *text_width)
  1675. {
  1676. if (!font_name)
  1677. font_name = pdf->current_font->font.name;
  1678. const uint16_t *widths = find_font_widths(font_name);
  1679. if (!widths)
  1680. return pdf_set_err(pdf, -EINVAL,
  1681. "Unable to determine width for font '%s'",
  1682. pdf->current_font->font.name);
  1683. return pdf_text_point_width(pdf, text, -1, size, widths, text_width);
  1684. }
  1685. static const char *find_word_break(const char *string)
  1686. {
  1687. if (!string)
  1688. return NULL;
  1689. /* Skip over the actual word */
  1690. while (*string && !isspace(*string))
  1691. string++;
  1692. return string;
  1693. }
  1694. int pdf_add_text_wrap(struct pdf_doc *pdf, struct pdf_object *page,
  1695. const char *text, float size, float xoff, float yoff,
  1696. float angle, uint32_t colour, float wrap_width,
  1697. int align, float *height)
  1698. {
  1699. /* Move through the text string, stopping at word boundaries,
  1700. * trying to find the longest text string we can fit in the given width
  1701. */
  1702. const char *start = text;
  1703. const char *last_best = text;
  1704. const char *end = text;
  1705. char line[512];
  1706. const uint16_t *widths;
  1707. float orig_yoff = yoff;
  1708. widths = find_font_widths(pdf->current_font->font.name);
  1709. if (!widths)
  1710. return pdf_set_err(pdf, -EINVAL,
  1711. "Unable to determine width for font '%s'",
  1712. pdf->current_font->font.name);
  1713. while (start && *start) {
  1714. const char *new_end = find_word_break(end + 1);
  1715. float line_width;
  1716. int output = 0;
  1717. float xoff_align = xoff;
  1718. int e;
  1719. end = new_end;
  1720. e = pdf_text_point_width(pdf, start, end - start, size, widths,
  1721. &line_width);
  1722. if (e < 0)
  1723. return e;
  1724. if (line_width >= wrap_width) {
  1725. if (last_best == start) {
  1726. /* There is a single word that is too long for the line */
  1727. ptrdiff_t i;
  1728. /* Find the best character to chop it at */
  1729. for (i = end - start - 1; i > 0; i--) {
  1730. float this_width;
  1731. // Don't look at places that are in the middle of a utf-8
  1732. // sequence
  1733. if ((start[i - 1] & 0xc0) == 0xc0 ||
  1734. ((start[i - 1] & 0xc0) == 0x80 &&
  1735. (start[i] & 0xc0) == 0x80))
  1736. continue;
  1737. e = pdf_text_point_width(pdf, start, i, size, widths,
  1738. &this_width);
  1739. if (e < 0)
  1740. return e;
  1741. if (this_width < wrap_width)
  1742. break;
  1743. }
  1744. if (i == 0)
  1745. return pdf_set_err(pdf, -EINVAL,
  1746. "Unable to find suitable line break");
  1747. end = start + i;
  1748. } else
  1749. end = last_best;
  1750. output = 1;
  1751. }
  1752. if (*end == '\0')
  1753. output = 1;
  1754. if (*end == '\n' || *end == '\r')
  1755. output = 1;
  1756. if (output) {
  1757. int len = end - start;
  1758. float char_spacing = 0;
  1759. if (len >= (int)sizeof(line))
  1760. len = (int)sizeof(line) - 1;
  1761. strncpy(line, start, len);
  1762. line[len] = '\0';
  1763. e = pdf_text_point_width(pdf, start, len, size, widths,
  1764. &line_width);
  1765. if (e < 0)
  1766. return e;
  1767. switch (align) {
  1768. case PDF_ALIGN_RIGHT:
  1769. xoff_align += wrap_width - line_width;
  1770. break;
  1771. case PDF_ALIGN_CENTER:
  1772. xoff_align += (wrap_width - line_width) / 2;
  1773. break;
  1774. case PDF_ALIGN_JUSTIFY:
  1775. if ((len - 1) > 0 && *end != '\r' && *end != '\n' &&
  1776. *end != '\0')
  1777. char_spacing = (wrap_width - line_width) / (len - 2);
  1778. break;
  1779. case PDF_ALIGN_JUSTIFY_ALL:
  1780. if ((len - 1) > 0)
  1781. char_spacing = (wrap_width - line_width) / (len - 2);
  1782. break;
  1783. }
  1784. if (align != PDF_ALIGN_NO_WRITE) {
  1785. pdf_add_text_spacing(pdf, page, line, size, xoff_align, yoff,
  1786. colour, char_spacing, angle);
  1787. }
  1788. if (*end == ' ')
  1789. end++;
  1790. start = last_best = end;
  1791. yoff -= size;
  1792. } else
  1793. last_best = end;
  1794. }
  1795. if (height)
  1796. *height = orig_yoff - yoff;
  1797. return 0;
  1798. }
  1799. int pdf_add_line(struct pdf_doc *pdf, struct pdf_object *page, float x1,
  1800. float y1, float x2, float y2, float width, uint32_t colour)
  1801. {
  1802. int ret;
  1803. struct dstr str = INIT_DSTR;
  1804. dstr_printf(&str, "%f w\r\n", width);
  1805. dstr_printf(&str, "%f %f m\r\n", x1, y1);
  1806. dstr_printf(&str, "/DeviceRGB CS\r\n");
  1807. dstr_printf(&str, "%f %f %f RG\r\n", PDF_RGB_R(colour), PDF_RGB_G(colour),
  1808. PDF_RGB_B(colour));
  1809. dstr_printf(&str, "%f %f l S\r\n", x2, y2);
  1810. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1811. dstr_free(&str);
  1812. return ret;
  1813. }
  1814. int pdf_add_cubic_bezier(struct pdf_doc *pdf, struct pdf_object *page,
  1815. float x1, float y1, float x2, float y2, float xq1,
  1816. float yq1, float xq2, float yq2, float width,
  1817. uint32_t colour)
  1818. {
  1819. int ret;
  1820. struct dstr str = INIT_DSTR;
  1821. dstr_printf(&str, "%f w\r\n", width);
  1822. dstr_printf(&str, "%f %f m\r\n", x1, y1);
  1823. dstr_printf(&str, "/DeviceRGB CS\r\n");
  1824. dstr_printf(&str, "%f %f %f RG\r\n", PDF_RGB_R(colour), PDF_RGB_G(colour),
  1825. PDF_RGB_B(colour));
  1826. dstr_printf(&str, "%f %f %f %f %f %f c S\r\n", xq1, yq1, xq2, yq2, x2,
  1827. y2);
  1828. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1829. dstr_free(&str);
  1830. return ret;
  1831. }
  1832. int pdf_add_quadratic_bezier(struct pdf_doc *pdf, struct pdf_object *page,
  1833. float x1, float y1, float x2, float y2,
  1834. float xq1, float yq1, float width,
  1835. uint32_t colour)
  1836. {
  1837. float xc1 = x1 + (xq1 - x1) * (2.0f / 3.0f);
  1838. float yc1 = y1 + (yq1 - y1) * (2.0f / 3.0f);
  1839. float xc2 = x2 + (xq1 - x2) * (2.0f / 3.0f);
  1840. float yc2 = y2 + (yq1 - y2) * (2.0f / 3.0f);
  1841. return pdf_add_cubic_bezier(pdf, page, x1, y1, x2, y2, xc1, yc1, xc2, yc2,
  1842. width, colour);
  1843. }
  1844. int pdf_add_custom_path(struct pdf_doc *pdf, struct pdf_object *page,
  1845. const struct pdf_path_operation *operations,
  1846. int operation_count, float stroke_width,
  1847. uint32_t stroke_colour, uint32_t fill_colour)
  1848. {
  1849. int ret;
  1850. struct dstr str = INIT_DSTR;
  1851. if (!PDF_IS_TRANSPARENT(fill_colour)) {
  1852. dstr_printf(&str, "/DeviceRGB CS\r\n");
  1853. dstr_printf(&str, "%f %f %f rg\r\n", PDF_RGB_R(fill_colour),
  1854. PDF_RGB_G(fill_colour), PDF_RGB_B(fill_colour));
  1855. }
  1856. dstr_printf(&str, "%f w\r\n", stroke_width);
  1857. dstr_printf(&str, "/DeviceRGB CS\r\n");
  1858. dstr_printf(&str, "%f %f %f RG\r\n", PDF_RGB_R(stroke_colour),
  1859. PDF_RGB_G(stroke_colour), PDF_RGB_B(stroke_colour));
  1860. for (int i = 0; i < operation_count; i++) {
  1861. struct pdf_path_operation operation = operations[i];
  1862. switch (operation.op) {
  1863. case 'm':
  1864. dstr_printf(&str, "%f %f m\r\n", operation.x1, operation.y1);
  1865. break;
  1866. case 'l':
  1867. dstr_printf(&str, "%f %f l\r\n", operation.x1, operation.y1);
  1868. break;
  1869. case 'c':
  1870. dstr_printf(&str, "%f %f %f %f %f %f c\r\n", operation.x1,
  1871. operation.y1, operation.x2, operation.y2,
  1872. operation.x3, operation.y3);
  1873. break;
  1874. case 'v':
  1875. dstr_printf(&str, "%f %f %f %f v\r\n", operation.x1, operation.y1,
  1876. operation.x2, operation.y2);
  1877. break;
  1878. case 'y':
  1879. dstr_printf(&str, "%f %f %f %f y\r\n", operation.x1, operation.y1,
  1880. operation.x2, operation.y2);
  1881. break;
  1882. case 'h':
  1883. dstr_printf(&str, "h\r\n");
  1884. break;
  1885. default:
  1886. return pdf_set_err(pdf, -errno, "Invalid operation");
  1887. break;
  1888. }
  1889. }
  1890. if (PDF_IS_TRANSPARENT(fill_colour))
  1891. dstr_printf(&str, "%s", "S ");
  1892. else
  1893. dstr_printf(&str, "%s", "B ");
  1894. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1895. dstr_free(&str);
  1896. return ret;
  1897. }
  1898. int pdf_add_ellipse(struct pdf_doc *pdf, struct pdf_object *page, float x,
  1899. float y, float xradius, float yradius, float width,
  1900. uint32_t colour, uint32_t fill_colour)
  1901. {
  1902. int ret;
  1903. struct dstr str = INIT_DSTR;
  1904. float lx, ly;
  1905. lx = (4.0f / 3.0f) * (float)(M_SQRT2 - 1) * xradius;
  1906. ly = (4.0f / 3.0f) * (float)(M_SQRT2 - 1) * yradius;
  1907. if (!PDF_IS_TRANSPARENT(fill_colour)) {
  1908. dstr_printf(&str, "/DeviceRGB CS\r\n");
  1909. dstr_printf(&str, "%f %f %f rg\r\n", PDF_RGB_R(fill_colour),
  1910. PDF_RGB_G(fill_colour), PDF_RGB_B(fill_colour));
  1911. }
  1912. /* stroke color */
  1913. dstr_printf(&str, "/DeviceRGB CS\r\n");
  1914. dstr_printf(&str, "%f %f %f RG\r\n", PDF_RGB_R(colour), PDF_RGB_G(colour),
  1915. PDF_RGB_B(colour));
  1916. dstr_printf(&str, "%f w ", width);
  1917. dstr_printf(&str, "%.2f %.2f m ", (x + xradius), (y));
  1918. dstr_printf(&str, "%.2f %.2f %.2f %.2f %.2f %.2f c ", (x + xradius),
  1919. (y - ly), (x + lx), (y - yradius), x, (y - yradius));
  1920. dstr_printf(&str, "%.2f %.2f %.2f %.2f %.2f %.2f c ", (x - lx),
  1921. (y - yradius), (x - xradius), (y - ly), (x - xradius), y);
  1922. dstr_printf(&str, "%.2f %.2f %.2f %.2f %.2f %.2f c ", (x - xradius),
  1923. (y + ly), (x - lx), (y + yradius), x, (y + yradius));
  1924. dstr_printf(&str, "%.2f %.2f %.2f %.2f %.2f %.2f c ", (x + lx),
  1925. (y + yradius), (x + xradius), (y + ly), (x + xradius), y);
  1926. if (PDF_IS_TRANSPARENT(fill_colour))
  1927. dstr_printf(&str, "%s", "S ");
  1928. else
  1929. dstr_printf(&str, "%s", "B ");
  1930. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1931. dstr_free(&str);
  1932. return ret;
  1933. }
  1934. int pdf_add_circle(struct pdf_doc *pdf, struct pdf_object *page, float xr,
  1935. float yr, float radius, float width, uint32_t colour,
  1936. uint32_t fill_colour)
  1937. {
  1938. return pdf_add_ellipse(pdf, page, xr, yr, radius, radius, width, colour,
  1939. fill_colour);
  1940. }
  1941. int pdf_add_rectangle(struct pdf_doc *pdf, struct pdf_object *page, float x,
  1942. float y, float width, float height, float border_width,
  1943. uint32_t colour)
  1944. {
  1945. int ret;
  1946. struct dstr str = INIT_DSTR;
  1947. dstr_printf(&str, "%f %f %f RG ", PDF_RGB_R(colour), PDF_RGB_G(colour),
  1948. PDF_RGB_B(colour));
  1949. dstr_printf(&str, "%f w ", border_width);
  1950. dstr_printf(&str, "%f %f %f %f re S ", x, y, width, height);
  1951. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1952. dstr_free(&str);
  1953. return ret;
  1954. }
  1955. int pdf_add_filled_rectangle(struct pdf_doc *pdf, struct pdf_object *page,
  1956. float x, float y, float width, float height,
  1957. float border_width, uint32_t colour_fill,
  1958. uint32_t colour_border)
  1959. {
  1960. int ret;
  1961. struct dstr str = INIT_DSTR;
  1962. dstr_printf(&str, "%f %f %f rg ", PDF_RGB_R(colour_fill),
  1963. PDF_RGB_G(colour_fill), PDF_RGB_B(colour_fill));
  1964. if (border_width > 0) {
  1965. dstr_printf(&str, "%f %f %f RG ", PDF_RGB_R(colour_border),
  1966. PDF_RGB_G(colour_border), PDF_RGB_B(colour_border));
  1967. dstr_printf(&str, "%f w ", border_width);
  1968. dstr_printf(&str, "%f %f %f %f re B ", x, y, width, height);
  1969. } else {
  1970. dstr_printf(&str, "%f %f %f %f re f ", x, y, width, height);
  1971. }
  1972. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1973. dstr_free(&str);
  1974. return ret;
  1975. }
  1976. int pdf_add_polygon(struct pdf_doc *pdf, struct pdf_object *page, float x[],
  1977. float y[], int count, float border_width, uint32_t colour)
  1978. {
  1979. int ret;
  1980. struct dstr str = INIT_DSTR;
  1981. dstr_printf(&str, "%f %f %f RG ", PDF_RGB_R(colour), PDF_RGB_G(colour),
  1982. PDF_RGB_B(colour));
  1983. dstr_printf(&str, "%f w ", border_width);
  1984. dstr_printf(&str, "%f %f m ", x[0], y[0]);
  1985. for (int i = 1; i < count; i++) {
  1986. dstr_printf(&str, "%f %f l ", x[i], y[i]);
  1987. }
  1988. dstr_printf(&str, "h S ");
  1989. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  1990. dstr_free(&str);
  1991. return ret;
  1992. }
  1993. int pdf_add_filled_polygon(struct pdf_doc *pdf, struct pdf_object *page,
  1994. float x[], float y[], int count,
  1995. float border_width, uint32_t colour)
  1996. {
  1997. int ret;
  1998. struct dstr str = INIT_DSTR;
  1999. dstr_printf(&str, "%f %f %f RG ", PDF_RGB_R(colour), PDF_RGB_G(colour),
  2000. PDF_RGB_B(colour));
  2001. dstr_printf(&str, "%f %f %f rg ", PDF_RGB_R(colour), PDF_RGB_G(colour),
  2002. PDF_RGB_B(colour));
  2003. dstr_printf(&str, "%f w ", border_width);
  2004. dstr_printf(&str, "%f %f m ", x[0], y[0]);
  2005. for (int i = 1; i < count; i++) {
  2006. dstr_printf(&str, "%f %f l ", x[i], y[i]);
  2007. }
  2008. dstr_printf(&str, "h f ");
  2009. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  2010. dstr_free(&str);
  2011. return ret;
  2012. }
  2013. static const struct {
  2014. uint32_t code;
  2015. char ch;
  2016. } code_128a_encoding[] = {
  2017. {0x212222, ' '}, {0x222122, '!'}, {0x222221, '"'}, {0x121223, '#'},
  2018. {0x121322, '$'}, {0x131222, '%'}, {0x122213, '&'}, {0x122312, '\''},
  2019. {0x132212, '('}, {0x221213, ')'}, {0x221312, '*'}, {0x231212, '+'},
  2020. {0x112232, ','}, {0x122132, '-'}, {0x122231, '.'}, {0x113222, '/'},
  2021. {0x123122, '0'}, {0x123221, '1'}, {0x223211, '2'}, {0x221132, '3'},
  2022. {0x221231, '4'}, {0x213212, '5'}, {0x223112, '6'}, {0x312131, '7'},
  2023. {0x311222, '8'}, {0x321122, '9'}, {0x321221, ':'}, {0x312212, ';'},
  2024. {0x322112, '<'}, {0x322211, '='}, {0x212123, '>'}, {0x212321, '?'},
  2025. {0x232121, '@'}, {0x111323, 'A'}, {0x131123, 'B'}, {0x131321, 'C'},
  2026. {0x112313, 'D'}, {0x132113, 'E'}, {0x132311, 'F'}, {0x211313, 'G'},
  2027. {0x231113, 'H'}, {0x231311, 'I'}, {0x112133, 'J'}, {0x112331, 'K'},
  2028. {0x132131, 'L'}, {0x113123, 'M'}, {0x113321, 'N'}, {0x133121, 'O'},
  2029. {0x313121, 'P'}, {0x211331, 'Q'}, {0x231131, 'R'}, {0x213113, 'S'},
  2030. {0x213311, 'T'}, {0x213131, 'U'}, {0x311123, 'V'}, {0x311321, 'W'},
  2031. {0x331121, 'X'}, {0x312113, 'Y'}, {0x312311, 'Z'}, {0x332111, '['},
  2032. {0x314111, '\\'}, {0x221411, ']'}, {0x431111, '^'}, {0x111224, '_'},
  2033. {0x111422, '`'}, {0x121124, 'a'}, {0x121421, 'b'}, {0x141122, 'c'},
  2034. {0x141221, 'd'}, {0x112214, 'e'}, {0x112412, 'f'}, {0x122114, 'g'},
  2035. {0x122411, 'h'}, {0x142112, 'i'}, {0x142211, 'j'}, {0x241211, 'k'},
  2036. {0x221114, 'l'}, {0x413111, 'm'}, {0x241112, 'n'}, {0x134111, 'o'},
  2037. {0x111242, 'p'}, {0x121142, 'q'}, {0x121241, 'r'}, {0x114212, 's'},
  2038. {0x124112, 't'}, {0x124211, 'u'}, {0x411212, 'v'}, {0x421112, 'w'},
  2039. {0x421211, 'x'}, {0x212141, 'y'}, {0x214121, 'z'}, {0x412121, '{'},
  2040. {0x111143, '|'}, {0x111341, '}'}, {0x131141, '~'}, {0x114113, '\0'},
  2041. {0x114311, '\0'}, {0x411113, '\0'}, {0x411311, '\0'}, {0x113141, '\0'},
  2042. {0x114131, '\0'}, {0x311141, '\0'}, {0x411131, '\0'}, {0x211412, '\0'},
  2043. {0x211214, '\0'}, {0x211232, '\0'}, {0x2331112, '\0'},
  2044. };
  2045. static int find_128_encoding(char ch)
  2046. {
  2047. for (int i = 0; i < (int)ARRAY_SIZE(code_128a_encoding); i++) {
  2048. if (code_128a_encoding[i].ch == ch)
  2049. return i;
  2050. }
  2051. return -1;
  2052. }
  2053. static float pdf_barcode_128a_ch(struct pdf_doc *pdf, struct pdf_object *page,
  2054. float x, float y, float width, float height,
  2055. uint32_t colour, int index, int code_len)
  2056. {
  2057. uint32_t code = code_128a_encoding[index].code;
  2058. float line_width = width / 11.0f;
  2059. for (int i = 0; i < code_len; i++) {
  2060. uint8_t shift = (code_len - 1 - i) * 4;
  2061. uint8_t mask = (code >> shift) & 0xf;
  2062. if (!(i % 2))
  2063. pdf_add_filled_rectangle(pdf, page, x, y, line_width * mask,
  2064. height, 0, colour, PDF_TRANSPARENT);
  2065. x += line_width * mask;
  2066. }
  2067. return x;
  2068. }
  2069. static int pdf_add_barcode_128a(struct pdf_doc *pdf, struct pdf_object *page,
  2070. float x, float y, float width, float height,
  2071. const char *string, uint32_t colour)
  2072. {
  2073. const char *s;
  2074. size_t len = strlen(string) + 3;
  2075. float char_width = width / len;
  2076. int checksum, i;
  2077. if (char_width / 11.0f <= 0)
  2078. return pdf_set_err(pdf, -EINVAL,
  2079. "Insufficient width to draw barcode");
  2080. for (s = string; *s; s++)
  2081. if (find_128_encoding(*s) < 0)
  2082. return pdf_set_err(pdf, -EINVAL, "Invalid barcode character 0x%x",
  2083. *s);
  2084. x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 104,
  2085. 6);
  2086. checksum = 104;
  2087. for (i = 1, s = string; *s; s++, i++) {
  2088. int index = find_128_encoding(*s);
  2089. // This should be impossible, due to the checks above, but confirm
  2090. // here anyway to stop coverity complaining
  2091. if (index < 0)
  2092. return pdf_set_err(pdf, -EINVAL,
  2093. "Invalid 128a barcode character 0x%x", *s);
  2094. x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour,
  2095. index, 6);
  2096. checksum += index * i;
  2097. }
  2098. x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour,
  2099. checksum % 103, 6);
  2100. pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 106, 7);
  2101. return 0;
  2102. }
  2103. /* Code 39 character encoding. Each 4-bit value indicates:
  2104. * 0 => wide bar
  2105. * 1 => narrow bar
  2106. * 2 => wide space
  2107. */
  2108. static const struct {
  2109. int code;
  2110. char ch;
  2111. } code_39_encoding[] = {
  2112. {0x012110, '1'}, {0x102110, '2'}, {0x002111, '3'},
  2113. {0x112010, '4'}, {0x012011, '5'}, {0x102011, '6'},
  2114. {0x112100, '7'}, {0x012101, '8'}, {0x102101, '9'},
  2115. {0x112001, '0'}, {0x011210, 'A'}, {0x101210, 'B'},
  2116. {0x001211, 'C'}, {0x110210, 'D'}, {0x010211, 'E'},
  2117. {0x100211, 'F'}, {0x111200, 'G'}, {0x011201, 'H'},
  2118. {0x101201, 'I'}, {0x110201, 'J'}, {0x011120, 'K'},
  2119. {0x101120, 'L'}, {0x001121, 'M'}, {0x110120, 'N'},
  2120. {0x010121, 'O'}, {0x100121, 'P'}, {0x111020, 'Q'},
  2121. {0x011021, 'R'}, {0x101021, 'S'}, {0x110021, 'T'},
  2122. {0x021110, 'U'}, {0x120110, 'V'}, {0x020111, 'W'},
  2123. {0x121010, 'X'}, {0x021011, 'Y'}, {0x120011, 'Z'},
  2124. {0x121100, '-'}, {0x021101, '.'}, {0x120101, ' '},
  2125. {0x121001, '*'}, // 'stop' character
  2126. };
  2127. static int find_39_encoding(char ch)
  2128. {
  2129. for (int i = 0; i < (int)ARRAY_SIZE(code_39_encoding); i++) {
  2130. if (code_39_encoding[i].ch == ch) {
  2131. return code_39_encoding[i].code;
  2132. }
  2133. }
  2134. return -1;
  2135. }
  2136. static int pdf_barcode_39_ch(struct pdf_doc *pdf, struct pdf_object *page,
  2137. float x, float y, float char_width, float height,
  2138. uint32_t colour, char ch, float *new_x)
  2139. {
  2140. float nw = char_width / 12.0f;
  2141. float ww = char_width / 4.0f;
  2142. int code = 0;
  2143. code = find_39_encoding(ch);
  2144. if (code < 0)
  2145. return pdf_set_err(pdf, -EINVAL, "Invalid Code 39 character %c 0x%x",
  2146. ch, ch);
  2147. for (int i = 5; i >= 0; i--) {
  2148. int pattern = (code >> i * 4) & 0xf;
  2149. if (pattern == 0) { // wide
  2150. if (pdf_add_filled_rectangle(pdf, page, x, y, ww - 1, height, 0,
  2151. colour, PDF_TRANSPARENT) < 0)
  2152. return pdf->errval;
  2153. x += ww;
  2154. }
  2155. if (pattern == 1) { // narrow
  2156. if (pdf_add_filled_rectangle(pdf, page, x, y, nw - 1, height, 0,
  2157. colour, PDF_TRANSPARENT) < 0)
  2158. return pdf->errval;
  2159. x += nw;
  2160. }
  2161. if (pattern == 2) { // space
  2162. x += nw;
  2163. }
  2164. }
  2165. if (new_x)
  2166. *new_x = x;
  2167. return 0;
  2168. }
  2169. static int pdf_add_barcode_39(struct pdf_doc *pdf, struct pdf_object *page,
  2170. float x, float y, float width, float height,
  2171. const char *string, uint32_t colour)
  2172. {
  2173. size_t len = strlen(string);
  2174. float char_width = width / (len + 2);
  2175. int e;
  2176. e = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*',
  2177. &x);
  2178. if (e < 0)
  2179. return e;
  2180. while (string && *string) {
  2181. e = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour,
  2182. *string, &x);
  2183. if (e < 0)
  2184. return e;
  2185. string++;
  2186. }
  2187. e = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*',
  2188. NULL);
  2189. if (e < 0)
  2190. return e;
  2191. return 0;
  2192. }
  2193. /* EAN/UPC character encoding. Each 4-bit value indicates width in x units.
  2194. * Elements are SBSB (Space, Bar, Space, Bar) for LHS digits
  2195. * Elements are inverted for RHS digits
  2196. */
  2197. static const int code_eanupc_encoding[] = {
  2198. 0x3211, // 0
  2199. 0x2221, // 1
  2200. 0x2122, // 2
  2201. 0x1411, // 3
  2202. 0x1132, // 4
  2203. 0x1231, // 5
  2204. 0x1114, // 6
  2205. 0x1312, // 7
  2206. 0x1213, // 8
  2207. 0x3112, // 9
  2208. };
  2209. /**
  2210. * List of different barcode guard patterns that are supported
  2211. */
  2212. enum {
  2213. GUARD_NORMAL, //!< Produce normal guard pattern
  2214. GUARD_CENTRE, //!< Produce centre guard pattern
  2215. GUARD_SPECIAL, //!< Produce special guard pattern
  2216. GUARD_ADDON,
  2217. GUARD_ADDON_DELIN,
  2218. };
  2219. static const int code_eanupc_aux_encoding[] = {
  2220. 0x150, // Normal guard
  2221. 0x554, // Centre guard
  2222. 0x555, // Special guard
  2223. 0x160, // Add-on guard
  2224. 0x500, // Add-on delineator
  2225. };
  2226. static const int set_ean13_encoding[] = {
  2227. 0x00, // 0
  2228. 0x34, // 1
  2229. 0x2c, // 2
  2230. 0x1c, // 3
  2231. 0x32, // 4
  2232. 0x26, // 5
  2233. 0x0e, // 6
  2234. 0x2a, // 7
  2235. 0x1a, // 8
  2236. 0x16, // 9
  2237. };
  2238. static const int set_upce_encoding[] = {
  2239. 0x07, // 0
  2240. 0x0b, // 1
  2241. 0x13, // 2
  2242. 0x23, // 3
  2243. 0x0d, // 4
  2244. 0x19, // 5
  2245. 0x31, // 6
  2246. 0x15, // 7
  2247. 0x25, // 8
  2248. 0x29, // 9
  2249. };
  2250. #define EANUPC_X PDF_MM_TO_POINT(0.330f)
  2251. static const struct {
  2252. unsigned modules;
  2253. float height_bar;
  2254. float height_outer;
  2255. unsigned quiet_left;
  2256. unsigned quiet_right;
  2257. } eanupc_dimensions[] = {
  2258. {113, PDF_MM_TO_POINT(22.85), PDF_MM_TO_POINT(25.93), 11, 7}, // EAN-13
  2259. {113, PDF_MM_TO_POINT(22.85), PDF_MM_TO_POINT(25.93), 9, 9}, // UPC-A
  2260. {81, PDF_MM_TO_POINT(18.23), PDF_MM_TO_POINT(21.31), 7, 7}, // EAN-8
  2261. {67, PDF_MM_TO_POINT(22.85), PDF_MM_TO_POINT(25.93), 9, 7}, // UPC-E
  2262. };
  2263. static void pdf_barcode_eanupc_calc_dims(int type, float width, float height,
  2264. float *x_off, float *y_off,
  2265. float *new_width, float *new_height,
  2266. float *x, float *bar_height,
  2267. float *bar_ext, float *font_size)
  2268. {
  2269. float aspectBarcode, aspectRect, scale;
  2270. aspectRect = width / height;
  2271. aspectBarcode = eanupc_dimensions[type - PDF_BARCODE_EAN13].modules *
  2272. EANUPC_X /
  2273. eanupc_dimensions[type - PDF_BARCODE_EAN13].height_outer;
  2274. if (aspectRect > aspectBarcode) {
  2275. *new_height = height;
  2276. *new_width = height * aspectBarcode;
  2277. } else if (aspectRect < aspectBarcode) {
  2278. *new_width = width;
  2279. *new_height = width / aspectBarcode;
  2280. } else {
  2281. *new_width = width;
  2282. *new_height = height;
  2283. }
  2284. scale = *new_height /
  2285. eanupc_dimensions[type - PDF_BARCODE_EAN13].height_outer;
  2286. *x = *new_width / eanupc_dimensions[type - PDF_BARCODE_EAN13].modules;
  2287. *bar_ext = *x * 5;
  2288. *bar_height =
  2289. eanupc_dimensions[type - PDF_BARCODE_EAN13].height_bar * scale;
  2290. *font_size = 8.0f * scale;
  2291. *x_off = (width - *new_width) / 2.0f;
  2292. *y_off = (height - *new_height) / 2.0f;
  2293. }
  2294. static int pdf_barcode_eanupc_ch(struct pdf_doc *pdf, struct pdf_object *page,
  2295. float x, float y, float x_width,
  2296. float height, uint32_t colour, char ch,
  2297. int set, float *new_x)
  2298. {
  2299. if ('0' > ch || ch > '9')
  2300. return pdf_set_err(pdf, -EINVAL, "Invalid EAN/UPC character %c 0x%x",
  2301. ch, ch);
  2302. int code;
  2303. code = code_eanupc_encoding[ch - '0'];
  2304. for (int i = 3; i >= 0; i--) {
  2305. int shift = (set == 1 ? 3 - i : i) * 4;
  2306. int bar = (set == 2 && i & 0x1) || (set != 2 && (i & 0x1) == 0);
  2307. float width = (float)((code >> shift) & 0xf);
  2308. switch (ch) {
  2309. case '1':
  2310. case '2':
  2311. if ((set == 0 && bar) || (set != 0 && !bar)) {
  2312. width -= 1.0f / 13.0f;
  2313. } else {
  2314. width += 1.0f / 13.0f;
  2315. }
  2316. break;
  2317. case '7':
  2318. case '8':
  2319. if ((set == 0 && bar) || (set != 0 && !bar)) {
  2320. width += 1.0f / 13.0f;
  2321. } else {
  2322. width -= 1.0f / 13.0f;
  2323. }
  2324. break;
  2325. }
  2326. width *= x_width;
  2327. if (bar) {
  2328. if (pdf_add_filled_rectangle(pdf, page, x, y, width, height, 0,
  2329. colour, PDF_TRANSPARENT) < 0)
  2330. return pdf->errval;
  2331. }
  2332. x += width;
  2333. }
  2334. if (new_x)
  2335. *new_x = x;
  2336. return 0;
  2337. }
  2338. static int pdf_barcode_eanupc_aux(struct pdf_doc *pdf,
  2339. struct pdf_object *page, float x, float y,
  2340. float x_width, float height,
  2341. uint32_t colour, int guard_type,
  2342. float *new_x)
  2343. {
  2344. int code = code_eanupc_aux_encoding[guard_type];
  2345. for (int i = 5; i >= 0; i--) {
  2346. int value = code >> i * 2 & 0x3;
  2347. if (value) {
  2348. if ((i & 0x1) == 0) {
  2349. if (pdf_add_filled_rectangle(pdf, page, x, y, x_width * value,
  2350. height, 0, colour,
  2351. PDF_TRANSPARENT) < 0)
  2352. return pdf->errval;
  2353. }
  2354. x += x_width * value;
  2355. }
  2356. }
  2357. if (new_x)
  2358. *new_x = x;
  2359. return 0;
  2360. }
  2361. static int pdf_add_barcode_ean13(struct pdf_doc *pdf, struct pdf_object *page,
  2362. float x, float y, float width, float height,
  2363. const char *string, uint32_t colour)
  2364. {
  2365. if (!string)
  2366. return 0;
  2367. size_t len = strlen(string);
  2368. int lead = 0;
  2369. if (len == 13) {
  2370. char ch = string[0];
  2371. if (!isdigit(*string))
  2372. return pdf_set_err(pdf, -EINVAL,
  2373. "Invalid EAN13 character %c 0x%x", ch, ch);
  2374. lead = ch - '0';
  2375. ++string;
  2376. } else if (len != 12)
  2377. return pdf_set_err(pdf, -EINVAL, "Invalid EAN13 string length %lu",
  2378. len);
  2379. /* Scale and calculate dimensions */
  2380. float x_off, y_off, new_width, new_height, x_width, bar_height, bar_ext,
  2381. font;
  2382. pdf_barcode_eanupc_calc_dims(PDF_BARCODE_EAN13, width, height, &x_off,
  2383. &y_off, &new_width, &new_height, &x_width,
  2384. &bar_height, &bar_ext, &font);
  2385. x += x_off;
  2386. y += y_off;
  2387. float bar_y = y + new_height - bar_height;
  2388. int e;
  2389. const char *save_font = pdf->current_font->font.name;
  2390. e = pdf_set_font(pdf, "Courier"); /* Built-in monospace font */
  2391. if (e < 0)
  2392. return e;
  2393. char text[2];
  2394. text[1] = 0;
  2395. text[0] = lead + '0';
  2396. e = pdf_add_text(pdf, page, text, font, x, y, colour);
  2397. if (e < 0) {
  2398. pdf_set_font(pdf, save_font);
  2399. return e;
  2400. }
  2401. x += eanupc_dimensions[0].quiet_left * x_width;
  2402. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2403. bar_height + bar_ext, colour, GUARD_NORMAL,
  2404. &x);
  2405. if (e < 0) {
  2406. pdf_set_font(pdf, save_font);
  2407. return e;
  2408. }
  2409. for (int i = 0; i != 6; i++) {
  2410. text[0] = *string;
  2411. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2412. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2413. if (e < 0) {
  2414. pdf_set_font(pdf, save_font);
  2415. return e;
  2416. }
  2417. int set = (set_ean13_encoding[lead] & 1 << i) ? 1 : 0;
  2418. e = pdf_barcode_eanupc_ch(pdf, page, x, bar_y, x_width, bar_height,
  2419. colour, *string, set, &x);
  2420. if (e < 0) {
  2421. pdf_set_font(pdf, save_font);
  2422. return e;
  2423. }
  2424. string++;
  2425. }
  2426. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2427. bar_height + bar_ext, colour, GUARD_CENTRE,
  2428. &x);
  2429. if (e < 0) {
  2430. pdf_set_font(pdf, save_font);
  2431. return e;
  2432. }
  2433. for (int i = 0; i != 6; i++) {
  2434. text[0] = *string;
  2435. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2436. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2437. if (e < 0) {
  2438. pdf_set_font(pdf, save_font);
  2439. return e;
  2440. }
  2441. e = pdf_barcode_eanupc_ch(pdf, page, x, bar_y, x_width, bar_height,
  2442. colour, *string, 2, &x);
  2443. if (e < 0) {
  2444. pdf_set_font(pdf, save_font);
  2445. return e;
  2446. }
  2447. string++;
  2448. }
  2449. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2450. bar_height + bar_ext, colour, GUARD_NORMAL,
  2451. &x);
  2452. if (e < 0) {
  2453. pdf_set_font(pdf, save_font);
  2454. return e;
  2455. }
  2456. text[0] = '>';
  2457. x += eanupc_dimensions[0].quiet_right * x_width -
  2458. 604.0f * font / (14.0f * 72.0f);
  2459. e = pdf_add_text(pdf, page, text, font, x, y, colour);
  2460. if (e < 0) {
  2461. pdf_set_font(pdf, save_font);
  2462. return e;
  2463. }
  2464. pdf_set_font(pdf, save_font);
  2465. return 0;
  2466. }
  2467. static int pdf_add_barcode_upca(struct pdf_doc *pdf, struct pdf_object *page,
  2468. float x, float y, float width, float height,
  2469. const char *string, uint32_t colour)
  2470. {
  2471. if (!string)
  2472. return 0;
  2473. size_t len = strlen(string);
  2474. if (len != 12)
  2475. return pdf_set_err(pdf, -EINVAL, "Invalid UPCA string length %lu",
  2476. len);
  2477. /* Scale and calculate dimensions */
  2478. float x_off, y_off, new_width, new_height;
  2479. float x_width, bar_height, bar_ext, font;
  2480. pdf_barcode_eanupc_calc_dims(PDF_BARCODE_UPCA, width, height, &x_off,
  2481. &y_off, &new_width, &new_height, &x_width,
  2482. &bar_height, &bar_ext, &font);
  2483. x += x_off;
  2484. y += y_off;
  2485. float bar_y = y + new_height - bar_height;
  2486. int e;
  2487. const char *save_font = pdf->current_font->font.name;
  2488. e = pdf_set_font(pdf, "Courier");
  2489. if (e < 0)
  2490. return e;
  2491. char text[2];
  2492. text[1] = 0;
  2493. text[0] = *string;
  2494. e = pdf_add_text(pdf, page, text, font * 4.0f / 7.0f, x, y, colour);
  2495. if (e < 0) {
  2496. pdf_set_font(pdf, save_font);
  2497. return e;
  2498. }
  2499. x += eanupc_dimensions[1].quiet_left * x_width;
  2500. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2501. bar_height + bar_ext, colour, GUARD_NORMAL,
  2502. &x);
  2503. if (e < 0) {
  2504. pdf_set_font(pdf, save_font);
  2505. return e;
  2506. }
  2507. for (int i = 0; i != 6; i++) {
  2508. text[0] = *string;
  2509. if (i) {
  2510. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2511. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2512. if (e < 0) {
  2513. pdf_set_font(pdf, save_font);
  2514. return e;
  2515. }
  2516. }
  2517. e = pdf_barcode_eanupc_ch(pdf, page, x, bar_y - (i ? 0 : bar_ext),
  2518. x_width, bar_height + (i ? 0 : bar_ext),
  2519. colour, *string, 0, &x);
  2520. if (e < 0) {
  2521. pdf_set_font(pdf, save_font);
  2522. return e;
  2523. }
  2524. string++;
  2525. }
  2526. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2527. bar_height + bar_ext, colour, GUARD_CENTRE,
  2528. &x);
  2529. if (e < 0) {
  2530. pdf_set_font(pdf, save_font);
  2531. return e;
  2532. }
  2533. for (int i = 0; i != 6; i++) {
  2534. text[0] = *string;
  2535. if (i != 5) {
  2536. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2537. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2538. if (e < 0) {
  2539. pdf_set_font(pdf, save_font);
  2540. return e;
  2541. }
  2542. }
  2543. e = pdf_barcode_eanupc_ch(
  2544. pdf, page, x, bar_y - (i != 5 ? 0 : bar_ext), x_width,
  2545. bar_height + (i != 5 ? 0 : bar_ext), colour, *string, 2, &x);
  2546. if (e < 0) {
  2547. pdf_set_font(pdf, save_font);
  2548. return e;
  2549. }
  2550. string++;
  2551. }
  2552. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2553. bar_height + bar_ext, colour, GUARD_NORMAL,
  2554. &x);
  2555. if (e < 0) {
  2556. pdf_set_font(pdf, save_font);
  2557. return e;
  2558. }
  2559. text[0] = *--string;
  2560. x += eanupc_dimensions[1].quiet_right * x_width -
  2561. 604.0f * font * 4.0f / 7.0f / (14.0f * 72.0f);
  2562. e = pdf_add_text(pdf, page, text, font * 4.0f / 7.0f, x, y, colour);
  2563. if (e < 0) {
  2564. pdf_set_font(pdf, save_font);
  2565. return e;
  2566. }
  2567. pdf_set_font(pdf, save_font);
  2568. return 0;
  2569. }
  2570. static int pdf_add_barcode_ean8(struct pdf_doc *pdf, struct pdf_object *page,
  2571. float x, float y, float width, float height,
  2572. const char *string, uint32_t colour)
  2573. {
  2574. if (!string)
  2575. return 0;
  2576. size_t len = strlen(string);
  2577. if (len != 8)
  2578. return pdf_set_err(pdf, -EINVAL, "Invalid EAN8 string length %lu",
  2579. len);
  2580. /* Scale and calculate dimensions */
  2581. float x_off, y_off, new_width, new_height, x_width, bar_height, bar_ext,
  2582. font;
  2583. pdf_barcode_eanupc_calc_dims(PDF_BARCODE_EAN8, width, height, &x_off,
  2584. &y_off, &new_width, &new_height, &x_width,
  2585. &bar_height, &bar_ext, &font);
  2586. x += x_off;
  2587. y += y_off;
  2588. float bar_y = y + new_height - bar_height;
  2589. int e;
  2590. const char *save_font = pdf->current_font->font.name;
  2591. e = pdf_set_font(pdf, "Courier"); /* Built-in monospace font */
  2592. if (e < 0)
  2593. return e;
  2594. char text[2];
  2595. text[1] = 0;
  2596. text[0] = '<';
  2597. e = pdf_add_text(pdf, page, text, font, x, y, colour);
  2598. if (e < 0) {
  2599. pdf_set_font(pdf, save_font);
  2600. return e;
  2601. }
  2602. x += eanupc_dimensions[2].quiet_left * x_width;
  2603. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2604. bar_height + bar_ext, colour, GUARD_NORMAL,
  2605. &x);
  2606. if (e < 0) {
  2607. pdf_set_font(pdf, save_font);
  2608. return e;
  2609. }
  2610. for (int i = 0; i != 4; i++) {
  2611. text[0] = *string;
  2612. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2613. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2614. if (e < 0) {
  2615. pdf_set_font(pdf, save_font);
  2616. return e;
  2617. }
  2618. e = pdf_barcode_eanupc_ch(pdf, page, x, bar_y, x_width, bar_height,
  2619. colour, *string, 0, &x);
  2620. if (e < 0) {
  2621. pdf_set_font(pdf, save_font);
  2622. return e;
  2623. }
  2624. string++;
  2625. }
  2626. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2627. bar_height + bar_ext, colour, GUARD_CENTRE,
  2628. &x);
  2629. if (e < 0) {
  2630. pdf_set_font(pdf, save_font);
  2631. return e;
  2632. }
  2633. for (int i = 0; i != 4; i++) {
  2634. text[0] = *string;
  2635. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2636. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2637. if (e < 0) {
  2638. pdf_set_font(pdf, save_font);
  2639. return e;
  2640. }
  2641. e = pdf_barcode_eanupc_ch(pdf, page, x, bar_y, x_width, bar_height,
  2642. colour, *string, 2, &x);
  2643. if (e < 0) {
  2644. pdf_set_font(pdf, save_font);
  2645. return e;
  2646. }
  2647. string++;
  2648. }
  2649. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y - bar_ext, x_width,
  2650. bar_height + bar_ext, colour, GUARD_NORMAL,
  2651. &x);
  2652. if (e < 0) {
  2653. pdf_set_font(pdf, save_font);
  2654. return e;
  2655. }
  2656. text[0] = '>';
  2657. x += eanupc_dimensions[0].quiet_right * x_width -
  2658. 604.0f * font / (14.0f * 72.0f);
  2659. e = pdf_add_text(pdf, page, text, font, x, y, colour);
  2660. if (e < 0) {
  2661. pdf_set_font(pdf, save_font);
  2662. return e;
  2663. }
  2664. pdf_set_font(pdf, save_font);
  2665. return 0;
  2666. }
  2667. static int pdf_add_barcode_upce(struct pdf_doc *pdf, struct pdf_object *page,
  2668. float x, float y, float width, float height,
  2669. const char *string, uint32_t colour)
  2670. {
  2671. if (!string)
  2672. return 0;
  2673. size_t len = strlen(string);
  2674. if (len != 12)
  2675. return pdf_set_err(pdf, -EINVAL, "Invalid UPCE string length %lu",
  2676. len);
  2677. if (*string != '0')
  2678. return pdf_set_err(pdf, -EINVAL, "Invalid UPCE char %c at start",
  2679. *string);
  2680. for (size_t i = 0; i < len; i++) {
  2681. if (!isdigit(string[i]))
  2682. return pdf_set_err(pdf, -EINVAL, "Invalid UPCE char 0x%x at %zd",
  2683. string[i], i);
  2684. }
  2685. /* Scale and calculate dimensions */
  2686. float x_off, y_off, new_width, new_height;
  2687. float x_width, bar_height, bar_ext, font;
  2688. pdf_barcode_eanupc_calc_dims(PDF_BARCODE_UPCE, width, height, &x_off,
  2689. &y_off, &new_width, &new_height, &x_width,
  2690. &bar_height, &bar_ext, &font);
  2691. x += x_off;
  2692. y += y_off;
  2693. float bar_y = y + new_height - bar_height;
  2694. int e;
  2695. const char *save_font = pdf->current_font->font.name;
  2696. e = pdf_set_font(pdf, "Courier");
  2697. if (e < 0)
  2698. return e;
  2699. char text[2];
  2700. text[1] = 0;
  2701. text[0] = string[0];
  2702. e = pdf_add_text(pdf, page, text, font * 4.0f / 7.0f, x, y, colour);
  2703. if (e < 0) {
  2704. pdf_set_font(pdf, save_font);
  2705. return e;
  2706. }
  2707. x += eanupc_dimensions[2].quiet_left * x_width;
  2708. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y, x_width, bar_height,
  2709. colour, GUARD_NORMAL, &x);
  2710. if (e < 0) {
  2711. pdf_set_font(pdf, save_font);
  2712. return e;
  2713. }
  2714. char X[6];
  2715. if (string[5] && memcmp(string + 6, "0000", 4) == 0 &&
  2716. '5' <= string[10] && string[10] <= '9') {
  2717. memcpy(X, string + 1, 5);
  2718. X[5] = string[10];
  2719. } else if (string[4] && memcmp(string + 5, "00000", 5) == 0) {
  2720. memcpy(X, string + 1, 4);
  2721. X[4] = string[11];
  2722. X[5] = 4;
  2723. } else if ('0' <= string[3] && string[3] <= '2' &&
  2724. memcmp(string + 4, "0000", 4) == 0) {
  2725. X[0] = string[1];
  2726. X[1] = string[2];
  2727. X[2] = string[8];
  2728. X[3] = string[9];
  2729. X[4] = string[10];
  2730. X[5] = string[3];
  2731. } else if ('3' <= string[3] && string[3] <= '9' &&
  2732. memcmp(string + 4, "00000", 5) == 0) {
  2733. memcpy(X, string + 1, 3);
  2734. X[3] = string[9];
  2735. X[4] = string[10];
  2736. X[5] = 3;
  2737. } else {
  2738. pdf_set_font(pdf, save_font);
  2739. return pdf_set_err(pdf, -EINVAL, "Invalid UPCE string format");
  2740. }
  2741. for (int i = 0; i != 6; i++) {
  2742. text[0] = X[i];
  2743. e = pdf_add_text_wrap(pdf, page, text, font, x, y, 0, colour,
  2744. 7 * x_width, PDF_ALIGN_CENTER, NULL);
  2745. if (e < 0) {
  2746. pdf_set_font(pdf, save_font);
  2747. return e;
  2748. }
  2749. int set = (set_upce_encoding[string[11] - '0'] & 1 << i) ? 1 : 0;
  2750. e = pdf_barcode_eanupc_ch(pdf, page, x, bar_y, x_width, bar_height,
  2751. colour, X[i], set, &x);
  2752. if (e < 0) {
  2753. pdf_set_font(pdf, save_font);
  2754. return e;
  2755. }
  2756. }
  2757. e = pdf_barcode_eanupc_aux(pdf, page, x, bar_y, x_width, bar_height,
  2758. colour, GUARD_SPECIAL, &x);
  2759. if (e < 0) {
  2760. pdf_set_font(pdf, save_font);
  2761. return e;
  2762. }
  2763. text[0] = string[11];
  2764. x += eanupc_dimensions[0].quiet_right * x_width -
  2765. 604.0f * font * 4.0f / 7.0f / (14.0f * 72.0f);
  2766. e = pdf_add_text(pdf, page, text, font * 4.0f / 7.0f, x, y, colour);
  2767. if (e < 0) {
  2768. pdf_set_font(pdf, save_font);
  2769. return e;
  2770. }
  2771. pdf_set_font(pdf, save_font);
  2772. return 0;
  2773. }
  2774. int pdf_add_barcode(struct pdf_doc *pdf, struct pdf_object *page, int code,
  2775. float x, float y, float width, float height,
  2776. const char *string, uint32_t colour)
  2777. {
  2778. if (!string || !*string)
  2779. return 0;
  2780. switch (code) {
  2781. case PDF_BARCODE_128A:
  2782. return pdf_add_barcode_128a(pdf, page, x, y, width, height, string,
  2783. colour);
  2784. case PDF_BARCODE_39:
  2785. return pdf_add_barcode_39(pdf, page, x, y, width, height, string,
  2786. colour);
  2787. case PDF_BARCODE_EAN13:
  2788. return pdf_add_barcode_ean13(pdf, page, x, y, width, height, string,
  2789. colour);
  2790. case PDF_BARCODE_UPCA:
  2791. return pdf_add_barcode_upca(pdf, page, x, y, width, height, string,
  2792. colour);
  2793. case PDF_BARCODE_EAN8:
  2794. return pdf_add_barcode_ean8(pdf, page, x, y, width, height, string,
  2795. colour);
  2796. case PDF_BARCODE_UPCE:
  2797. return pdf_add_barcode_upce(pdf, page, x, y, width, height, string,
  2798. colour);
  2799. default:
  2800. return pdf_set_err(pdf, -EINVAL, "Invalid barcode code %d", code);
  2801. }
  2802. }
  2803. static pdf_object *pdf_add_raw_grayscale8(struct pdf_doc *pdf,
  2804. const uint8_t *data, uint32_t width,
  2805. uint32_t height)
  2806. {
  2807. struct pdf_object *obj;
  2808. size_t len;
  2809. const char *endstream = ">\r\nendstream\r\n";
  2810. struct dstr str = INIT_DSTR;
  2811. size_t data_len = (size_t)width * (size_t)height;
  2812. dstr_printf(&str,
  2813. "<<\r\n"
  2814. " /Type /XObject\r\n"
  2815. " /Name /Image%d\r\n"
  2816. " /Subtype /Image\r\n"
  2817. " /ColorSpace /DeviceGray\r\n"
  2818. " /Height %d\r\n"
  2819. " /Width %d\r\n"
  2820. " /BitsPerComponent 8\r\n"
  2821. " /Length %zu\r\n"
  2822. ">>stream\r\n",
  2823. flexarray_size(&pdf->objects), height, width, data_len + 1);
  2824. len = dstr_len(&str) + data_len + strlen(endstream) + 1;
  2825. if (dstr_ensure(&str, len) < 0) {
  2826. dstr_free(&str);
  2827. pdf_set_err(pdf, -ENOMEM,
  2828. "Unable to allocate %zu bytes memory for image", len);
  2829. return NULL;
  2830. }
  2831. dstr_append_data(&str, data, data_len);
  2832. dstr_append(&str, endstream);
  2833. obj = pdf_add_object(pdf, OBJ_image);
  2834. if (!obj) {
  2835. dstr_free(&str);
  2836. return NULL;
  2837. }
  2838. obj->stream.stream = str;
  2839. return obj;
  2840. }
  2841. static struct pdf_object *pdf_add_raw_rgb24(struct pdf_doc *pdf,
  2842. const uint8_t *data,
  2843. uint32_t width, uint32_t height)
  2844. {
  2845. struct pdf_object *obj;
  2846. size_t len;
  2847. const char *endstream = ">\r\nendstream\r\n";
  2848. struct dstr str = INIT_DSTR;
  2849. size_t data_len = (size_t)width * (size_t)height * 3;
  2850. dstr_printf(&str,
  2851. "<<\r\n"
  2852. " /Type /XObject\r\n"
  2853. " /Name /Image%d\r\n"
  2854. " /Subtype /Image\r\n"
  2855. " /ColorSpace /DeviceRGB\r\n"
  2856. " /Height %d\r\n"
  2857. " /Width %d\r\n"
  2858. " /BitsPerComponent 8\r\n"
  2859. " /Length %zu\r\n"
  2860. ">>stream\r\n",
  2861. flexarray_size(&pdf->objects), height, width, data_len + 1);
  2862. len = dstr_len(&str) + data_len + strlen(endstream) + 1;
  2863. if (dstr_ensure(&str, len) < 0) {
  2864. dstr_free(&str);
  2865. pdf_set_err(pdf, -ENOMEM,
  2866. "Unable to allocate %zu bytes memory for image", len);
  2867. return NULL;
  2868. }
  2869. dstr_append_data(&str, data, data_len);
  2870. dstr_append(&str, endstream);
  2871. obj = pdf_add_object(pdf, OBJ_image);
  2872. if (!obj) {
  2873. dstr_free(&str);
  2874. return NULL;
  2875. }
  2876. obj->stream.stream = str;
  2877. return obj;
  2878. }
  2879. static uint8_t *get_file(struct pdf_doc *pdf, const char *file_name,
  2880. size_t *length)
  2881. {
  2882. FILE *fp;
  2883. uint8_t *file_data;
  2884. struct stat buf;
  2885. off_t len;
  2886. if ((fp = fopen(file_name, "rb")) == NULL) {
  2887. pdf_set_err(pdf, -errno, "Unable to open %s: %s", file_name,
  2888. strerror(errno));
  2889. return NULL;
  2890. }
  2891. if (fstat(fileno(fp), &buf) < 0) {
  2892. pdf_set_err(pdf, -errno, "Unable to access %s: %s", file_name,
  2893. strerror(errno));
  2894. fclose(fp);
  2895. return NULL;
  2896. }
  2897. len = buf.st_size;
  2898. file_data = (uint8_t *)malloc(len);
  2899. if (!file_data) {
  2900. pdf_set_err(pdf, -ENOMEM, "Unable to allocate: %d", (int)len);
  2901. fclose(fp);
  2902. return NULL;
  2903. }
  2904. if (fread(file_data, len, 1, fp) != 1) {
  2905. pdf_set_err(pdf, -errno, "Unable to read full data: %s", file_name);
  2906. free(file_data);
  2907. fclose(fp);
  2908. return NULL;
  2909. }
  2910. fclose(fp);
  2911. *length = len;
  2912. return file_data;
  2913. }
  2914. static struct pdf_object *
  2915. pdf_add_raw_jpeg_data(struct pdf_doc *pdf, const struct pdf_img_info *info,
  2916. const uint8_t *jpeg_data, size_t len)
  2917. {
  2918. struct pdf_object *obj = pdf_add_object(pdf, OBJ_image);
  2919. if (!obj)
  2920. return NULL;
  2921. dstr_printf(&obj->stream.stream,
  2922. "<<\r\n"
  2923. " /Type /XObject\r\n"
  2924. " /Name /Image%d\r\n"
  2925. " /Subtype /Image\r\n"
  2926. " /ColorSpace %s\r\n"
  2927. " /Width %d\r\n"
  2928. " /Height %d\r\n"
  2929. " /BitsPerComponent 8\r\n"
  2930. " /Filter /DCTDecode\r\n"
  2931. " /Length %zu\r\n"
  2932. ">>stream\r\n",
  2933. flexarray_size(&pdf->objects),
  2934. (info->jpeg.ncolours == 1) ? "/DeviceGray" : "/DeviceRGB",
  2935. info->width, info->height, len);
  2936. dstr_append_data(&obj->stream.stream, jpeg_data, len);
  2937. dstr_printf(&obj->stream.stream, "\r\nendstream\r\n");
  2938. return obj;
  2939. }
  2940. /**
  2941. * Get the display dimensions of an image, respecting the images aspect ratio
  2942. * if only one desired display dimension is defined.
  2943. * The pdf parameter is only used for setting the error value.
  2944. */
  2945. static int get_img_display_dimensions(struct pdf_doc *pdf, uint32_t img_width,
  2946. uint32_t img_height,
  2947. float *display_width,
  2948. float *display_height)
  2949. {
  2950. if (!display_height || !display_width) {
  2951. return pdf_set_err(
  2952. pdf, -EINVAL,
  2953. "display_width and display_height may not be null pointers");
  2954. }
  2955. const float display_width_in = *display_width;
  2956. const float display_height_in = *display_height;
  2957. if (display_width_in < 0 && display_height_in < 0) {
  2958. return pdf_set_err(pdf, -EINVAL,
  2959. "Unable to determine image display dimensions, "
  2960. "display_width and display_height are both < 0");
  2961. }
  2962. if (img_width == 0 || img_height == 0) {
  2963. return pdf_set_err(pdf, -EINVAL,
  2964. "Invalid image dimensions received, the loaded "
  2965. "image appears to be empty.");
  2966. }
  2967. if (display_width_in < 0) {
  2968. // Set width, keeping aspect ratio
  2969. *display_width = display_height_in * ((float)img_width / img_height);
  2970. } else if (display_height_in < 0) {
  2971. // Set height, keeping aspect ratio
  2972. *display_height = display_width_in * ((float)img_height / img_width);
  2973. }
  2974. return 0;
  2975. }
  2976. static int pdf_add_image(struct pdf_doc *pdf, struct pdf_object *page,
  2977. struct pdf_object *image, float x, float y,
  2978. float width, float height)
  2979. {
  2980. int ret;
  2981. struct dstr str = INIT_DSTR;
  2982. if (!page)
  2983. page = pdf_find_last_object(pdf, OBJ_page);
  2984. if (!page)
  2985. return pdf_set_err(pdf, -EINVAL, "Invalid pdf page");
  2986. if (image->type != OBJ_image)
  2987. return pdf_set_err(pdf, -EINVAL,
  2988. "adding an image, but wrong object type %d",
  2989. image->type);
  2990. if (image->stream.page != NULL)
  2991. return pdf_set_err(pdf, -EEXIST, "image already on a page");
  2992. image->stream.page = page;
  2993. dstr_append(&str, "q ");
  2994. dstr_printf(&str, "%f 0 0 %f %f %f cm ", width, height, x, y);
  2995. dstr_printf(&str, "/Image%d Do ", image->index);
  2996. dstr_append(&str, "Q");
  2997. ret = pdf_add_stream(pdf, page, dstr_data(&str));
  2998. dstr_free(&str);
  2999. return ret;
  3000. }
  3001. // Works like fgets, except it's for a fixed in-memory buffer of data
  3002. static size_t dgets(const uint8_t *data, size_t *pos, size_t len, char *line,
  3003. size_t line_len)
  3004. {
  3005. size_t line_pos = 0;
  3006. if (*pos >= len)
  3007. return 0;
  3008. while ((*pos) < len) {
  3009. if (line_pos < line_len) {
  3010. // Reject non-ascii data
  3011. if (data[*pos] & 0x80) {
  3012. return 0;
  3013. }
  3014. line[line_pos] = data[*pos];
  3015. line_pos++;
  3016. }
  3017. if (data[*pos] == '\n') {
  3018. (*pos)++;
  3019. break;
  3020. }
  3021. (*pos)++;
  3022. }
  3023. if (line_pos < line_len) {
  3024. line[line_pos] = '\0';
  3025. }
  3026. return *pos;
  3027. }
  3028. static int parse_ppm_header(struct pdf_img_info *info, const uint8_t *data,
  3029. size_t length, char *err_msg,
  3030. size_t err_msg_length)
  3031. {
  3032. char line[1024];
  3033. memset(line, '\0', sizeof(line));
  3034. size_t pos = 0;
  3035. // Load the PPM file
  3036. if (!dgets(data, &pos, length, line, sizeof(line) - 1)) {
  3037. snprintf(err_msg, err_msg_length, "Invalid PPM file");
  3038. return -EINVAL;
  3039. }
  3040. // Determine number of color channels (Also, we only support binary ppms)
  3041. int ncolors;
  3042. if (strncmp(line, "P6", 2) == 0) {
  3043. info->ppm.color_space = PPM_BINARY_COLOR_RGB;
  3044. ncolors = 3;
  3045. } else if (strncmp(line, "P5", 2) == 0) {
  3046. info->ppm.color_space = PPM_BINARY_COLOR_GRAY;
  3047. ncolors = 1;
  3048. } else {
  3049. snprintf(err_msg, err_msg_length,
  3050. "Only binary PPM files (grayscale, RGB) supported");
  3051. return -EINVAL;
  3052. }
  3053. // Skip comments before header
  3054. do {
  3055. if (!dgets(data, &pos, length, line, sizeof(line) - 1)) {
  3056. snprintf(err_msg, err_msg_length, "Unable to find PPM header");
  3057. return -EINVAL;
  3058. }
  3059. } while (line[0] == '#');
  3060. // Read image dimensions
  3061. if (sscanf(line, "%u %u\n", &(info->width), &(info->height)) != 2) {
  3062. snprintf(err_msg, err_msg_length, "Unable to find PPM size");
  3063. return -EINVAL;
  3064. }
  3065. if (info->width > MAX_IMAGE_WIDTH || info->height > MAX_IMAGE_HEIGHT) {
  3066. snprintf(err_msg, err_msg_length, "Invalid width/height: %ux%u",
  3067. info->width, info->height);
  3068. return -EINVAL;
  3069. }
  3070. info->ppm.size = (size_t)(info->width * info->height * ncolors);
  3071. info->ppm.data_begin_pos = pos;
  3072. return 0;
  3073. }
  3074. static int pdf_add_ppm_data(struct pdf_doc *pdf, struct pdf_object *page,
  3075. float x, float y, float display_width,
  3076. float display_height,
  3077. const struct pdf_img_info *info,
  3078. const uint8_t *ppm_data, size_t len)
  3079. {
  3080. char line[1024];
  3081. // We start reading at the position delivered by parse_ppm_header,
  3082. // since we already parsed the header of the file there.
  3083. size_t pos = info->ppm.data_begin_pos;
  3084. /* Skip over the byte-size line */
  3085. if (!dgets(ppm_data, &pos, len, line, sizeof(line) - 1))
  3086. return pdf_set_err(pdf, -EINVAL, "No byte-size line in PPM file");
  3087. /* Try and limit the memory usage to sane images */
  3088. if (info->width > MAX_IMAGE_WIDTH || info->height > MAX_IMAGE_HEIGHT) {
  3089. return pdf_set_err(pdf, -EINVAL,
  3090. "Invalid width/height in PPM file: %ux%u",
  3091. info->width, info->height);
  3092. }
  3093. if (info->ppm.size > len - pos) {
  3094. return pdf_set_err(pdf, -EINVAL, "Insufficient image data available");
  3095. }
  3096. switch (info->ppm.color_space) {
  3097. case PPM_BINARY_COLOR_GRAY:
  3098. return pdf_add_grayscale8(pdf, page, x, y, display_width,
  3099. display_height, &ppm_data[pos], info->width,
  3100. info->height);
  3101. break;
  3102. case PPM_BINARY_COLOR_RGB:
  3103. return pdf_add_rgb24(pdf, page, x, y, display_width, display_height,
  3104. &ppm_data[pos], info->width, info->height);
  3105. break;
  3106. default:
  3107. return pdf_set_err(pdf, -EINVAL,
  3108. "Invalid color space in ppm file: %i",
  3109. info->ppm.color_space);
  3110. break;
  3111. }
  3112. }
  3113. static int parse_jpeg_header(struct pdf_img_info *info, const uint8_t *data,
  3114. size_t length, char *err_msg,
  3115. size_t err_msg_length)
  3116. {
  3117. // See http://www.videotechnology.com/jpeg/j1.html for details
  3118. if (length >= 4 && data[0] == 0xFF && data[1] == 0xD8) {
  3119. for (size_t i = 2; i < length; i++) {
  3120. if (data[i] != 0xff) {
  3121. break;
  3122. }
  3123. while (++i < length && data[i] == 0xff)
  3124. ;
  3125. if (i + 2 >= length) {
  3126. break;
  3127. }
  3128. int len = data[i + 1] * 256 + data[i + 2];
  3129. /* Search for SOFn marker and decode jpeg details */
  3130. if ((data[i] & 0xf4) == 0xc0) {
  3131. if (len >= 9 && i + len + 1 < length) {
  3132. info->height = data[i + 4] * 256 + data[i + 5];
  3133. info->width = data[i + 6] * 256 + data[i + 7];
  3134. info->jpeg.ncolours = data[i + 8];
  3135. return 0;
  3136. }
  3137. break;
  3138. }
  3139. i += len;
  3140. }
  3141. }
  3142. snprintf(err_msg, err_msg_length, "Error parsing JPEG header");
  3143. return -EINVAL;
  3144. }
  3145. static int pdf_add_jpeg_data(struct pdf_doc *pdf, struct pdf_object *page,
  3146. float x, float y, float display_width,
  3147. float display_height, struct pdf_img_info *info,
  3148. const uint8_t *jpeg_data, size_t len)
  3149. {
  3150. struct pdf_object *obj;
  3151. obj = pdf_add_raw_jpeg_data(pdf, info, jpeg_data, len);
  3152. if (!obj)
  3153. return pdf->errval;
  3154. if (get_img_display_dimensions(pdf, info->width, info->height,
  3155. &display_width, &display_height)) {
  3156. return pdf->errval;
  3157. }
  3158. return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
  3159. }
  3160. int pdf_add_rgb24(struct pdf_doc *pdf, struct pdf_object *page, float x,
  3161. float y, float display_width, float display_height,
  3162. const uint8_t *data, uint32_t width, uint32_t height)
  3163. {
  3164. struct pdf_object *obj;
  3165. obj = pdf_add_raw_rgb24(pdf, data, width, height);
  3166. if (!obj)
  3167. return pdf->errval;
  3168. if (get_img_display_dimensions(pdf, width, height, &display_width,
  3169. &display_height)) {
  3170. return pdf->errval;
  3171. }
  3172. return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
  3173. }
  3174. int pdf_add_grayscale8(struct pdf_doc *pdf, struct pdf_object *page, float x,
  3175. float y, float display_width, float display_height,
  3176. const uint8_t *data, uint32_t width, uint32_t height)
  3177. {
  3178. struct pdf_object *obj;
  3179. obj = pdf_add_raw_grayscale8(pdf, data, width, height);
  3180. if (!obj)
  3181. return pdf->errval;
  3182. if (get_img_display_dimensions(pdf, width, height, &display_width,
  3183. &display_height)) {
  3184. return pdf->errval;
  3185. }
  3186. return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
  3187. }
  3188. static int parse_png_header(struct pdf_img_info *info, const uint8_t *data,
  3189. size_t length, char *err_msg,
  3190. size_t err_msg_length)
  3191. {
  3192. if (length <= sizeof(png_signature)) {
  3193. snprintf(err_msg, err_msg_length, "PNG file too short");
  3194. return -EINVAL;
  3195. }
  3196. if (memcmp(data, png_signature, sizeof(png_signature))) {
  3197. snprintf(err_msg, err_msg_length, "File is not correct PNG file");
  3198. return -EINVAL;
  3199. }
  3200. // process first PNG chunk
  3201. uint32_t pos = sizeof(png_signature);
  3202. const struct png_chunk *chunk = (const struct png_chunk *)&data[pos];
  3203. pos += sizeof(struct png_chunk);
  3204. if (pos > length) {
  3205. snprintf(err_msg, err_msg_length, "PNG file too short");
  3206. return -EINVAL;
  3207. }
  3208. if (strncmp(chunk->type, png_chunk_header, 4) == 0) {
  3209. // header found, process width and height, check errors
  3210. struct png_header *header = &info->png;
  3211. if (pos + sizeof(struct png_header) > length) {
  3212. snprintf(err_msg, err_msg_length, "PNG file too short");
  3213. return -EINVAL;
  3214. }
  3215. memcpy(header, &data[pos], sizeof(struct png_header));
  3216. if (header->deflate != 0) {
  3217. snprintf(err_msg, err_msg_length, "Deflate wrong in PNG header");
  3218. return -EINVAL;
  3219. }
  3220. if (header->bitDepth == 0) {
  3221. snprintf(err_msg, err_msg_length, "PNG file has zero bit depth");
  3222. return -EINVAL;
  3223. }
  3224. // ensure the width and height values have the proper byte order
  3225. // and copy them into the info struct.
  3226. header->width = ntoh32(header->width);
  3227. header->height = ntoh32(header->height);
  3228. info->width = header->width;
  3229. info->height = header->height;
  3230. return 0;
  3231. }
  3232. snprintf(err_msg, err_msg_length, "Failed to read PNG file header");
  3233. return -EINVAL;
  3234. }
  3235. static int pdf_add_png_data(struct pdf_doc *pdf, struct pdf_object *page,
  3236. float x, float y, float display_width,
  3237. float display_height,
  3238. const struct pdf_img_info *img_info,
  3239. const uint8_t *png_data, size_t png_data_length)
  3240. {
  3241. // indicates if we return an error or add the img at the
  3242. // end of the function
  3243. bool success = false;
  3244. // string stream used for writing color space (and palette) info
  3245. // into the pdf
  3246. struct dstr colour_space = INIT_DSTR;
  3247. struct pdf_object *obj = NULL;
  3248. uint8_t *final_data = NULL;
  3249. int written = 0;
  3250. uint32_t pos;
  3251. uint8_t *png_data_temp = NULL;
  3252. size_t png_data_total_length = 0;
  3253. uint8_t ncolours;
  3254. // Stores palette information for indexed PNGs
  3255. struct rgb_value *palette_buffer = NULL;
  3256. size_t palette_buffer_length = 0;
  3257. const struct png_header *header = &img_info->png;
  3258. // Father info from png header
  3259. switch (header->colorType) {
  3260. case PNG_COLOR_GREYSCALE:
  3261. ncolours = 1;
  3262. break;
  3263. case PNG_COLOR_RGB:
  3264. ncolours = 3;
  3265. break;
  3266. case PNG_COLOR_INDEXED:
  3267. ncolours = 1;
  3268. break;
  3269. // PNG_COLOR_RGBA and PNG_COLOR_GREYSCALE_A are unsupported
  3270. default:
  3271. pdf_set_err(pdf, -EINVAL, "PNG has unsupported color type: %d",
  3272. header->colorType);
  3273. goto free_buffers;
  3274. break;
  3275. }
  3276. /* process PNG chunks */
  3277. pos = sizeof(png_signature);
  3278. while (1) {
  3279. const struct png_chunk *chunk;
  3280. chunk = (const struct png_chunk *)&png_data[pos];
  3281. pos += sizeof(struct png_chunk);
  3282. if (pos > png_data_length - 4) {
  3283. pdf_set_err(pdf, -EINVAL, "PNG file too short");
  3284. goto free_buffers;
  3285. }
  3286. const uint32_t chunk_length = ntoh32(chunk->length);
  3287. // chunk length + 4-bytes of CRC
  3288. if (chunk_length > png_data_length - pos - 4) {
  3289. pdf_set_err(pdf, -EINVAL, "PNG chunk exceeds file: %d vs %ld",
  3290. chunk_length, png_data_length - pos - 4);
  3291. goto free_buffers;
  3292. }
  3293. if (strncmp(chunk->type, png_chunk_header, 4) == 0) {
  3294. // Ignoring the header, since it was parsed
  3295. // before calling this function.
  3296. } else if (strncmp(chunk->type, png_chunk_palette, 4) == 0) {
  3297. // Palette chunk
  3298. if (header->colorType == PNG_COLOR_INDEXED) {
  3299. // palette chunk is needed for indexed images
  3300. if (palette_buffer) {
  3301. pdf_set_err(pdf, -EINVAL,
  3302. "PNG contains multiple palette chunks");
  3303. goto free_buffers;
  3304. }
  3305. if (chunk_length % 3 != 0) {
  3306. pdf_set_err(pdf, -EINVAL,
  3307. "PNG format error: palette chunk length is "
  3308. "not divisbly by 3!");
  3309. goto free_buffers;
  3310. }
  3311. palette_buffer_length = (size_t)(chunk_length / 3);
  3312. if (palette_buffer_length > 256 ||
  3313. palette_buffer_length == 0) {
  3314. pdf_set_err(pdf, -EINVAL,
  3315. "PNG palette length invalid: %zd",
  3316. palette_buffer_length);
  3317. goto free_buffers;
  3318. }
  3319. palette_buffer = (struct rgb_value *)malloc(
  3320. palette_buffer_length * sizeof(struct rgb_value));
  3321. if (!palette_buffer) {
  3322. pdf_set_err(pdf, -ENOMEM,
  3323. "Could not allocate memory for indexed color "
  3324. "palette (%zu bytes)",
  3325. palette_buffer_length *
  3326. sizeof(struct rgb_value));
  3327. goto free_buffers;
  3328. }
  3329. for (size_t i = 0; i < palette_buffer_length; i++) {
  3330. size_t offset = (i * 3) + pos;
  3331. palette_buffer[i].red = png_data[offset];
  3332. palette_buffer[i].green = png_data[offset + 1];
  3333. palette_buffer[i].blue = png_data[offset + 2];
  3334. }
  3335. } else if (header->colorType == PNG_COLOR_RGB ||
  3336. header->colorType == PNG_COLOR_RGBA) {
  3337. // palette chunk is optional for RGB(A) images
  3338. // but we do not process them
  3339. } else {
  3340. pdf_set_err(pdf, -EINVAL,
  3341. "Unexpected palette chunk for color type %d",
  3342. header->colorType);
  3343. goto free_buffers;
  3344. }
  3345. } else if (strncmp(chunk->type, png_chunk_data, 4) == 0) {
  3346. if (chunk_length > 0 && chunk_length < png_data_length - pos) {
  3347. uint8_t *data = (uint8_t *)realloc(
  3348. png_data_temp, png_data_total_length + chunk_length);
  3349. // (uint8_t *)realloc(info.data, info.length + chunk_length);
  3350. if (!data) {
  3351. pdf_set_err(pdf, -ENOMEM, "No memory for PNG data");
  3352. goto free_buffers;
  3353. }
  3354. png_data_temp = data;
  3355. memcpy(&png_data_temp[png_data_total_length], &png_data[pos],
  3356. chunk_length);
  3357. png_data_total_length += chunk_length;
  3358. }
  3359. } else if (strncmp(chunk->type, png_chunk_end, 4) == 0) {
  3360. /* end of file, exit */
  3361. break;
  3362. }
  3363. if (chunk_length >= png_data_length) {
  3364. pdf_set_err(pdf, -EINVAL, "PNG chunk length larger than file");
  3365. goto free_buffers;
  3366. }
  3367. pos += chunk_length; // add chunk length
  3368. pos += sizeof(uint32_t); // add CRC length
  3369. }
  3370. /* if no length was found */
  3371. if (png_data_total_length == 0) {
  3372. pdf_set_err(pdf, -EINVAL, "PNG file has zero length");
  3373. goto free_buffers;
  3374. }
  3375. switch (header->colorType) {
  3376. case PNG_COLOR_GREYSCALE:
  3377. dstr_append(&colour_space, "/DeviceGray");
  3378. break;
  3379. case PNG_COLOR_RGB:
  3380. dstr_append(&colour_space, "/DeviceRGB");
  3381. break;
  3382. case PNG_COLOR_INDEXED:
  3383. if (palette_buffer_length == 0) {
  3384. pdf_set_err(pdf, -EINVAL, "Indexed PNG contains no palette");
  3385. goto free_buffers;
  3386. }
  3387. // Write the color palette to the color_palette buffer
  3388. dstr_printf(&colour_space,
  3389. "[ /Indexed\r\n"
  3390. " /DeviceRGB\r\n"
  3391. " %zu\r\n"
  3392. " <",
  3393. palette_buffer_length - 1);
  3394. // write individual paletter values
  3395. // the index value for every RGB value is determined by its position
  3396. // (0, 1, 2, ...)
  3397. for (size_t i = 0; i < palette_buffer_length; i++) {
  3398. dstr_printf(&colour_space, "%02X%02X%02X ", palette_buffer[i].red,
  3399. palette_buffer[i].green, palette_buffer[i].blue);
  3400. }
  3401. dstr_append(&colour_space, ">\r\n]");
  3402. break;
  3403. default:
  3404. pdf_set_err(pdf, -EINVAL,
  3405. "Cannot map PNG color type %d to PDF color space",
  3406. header->colorType);
  3407. goto free_buffers;
  3408. break;
  3409. }
  3410. final_data = (uint8_t *)malloc(png_data_total_length + 1024 +
  3411. dstr_len(&colour_space));
  3412. if (!final_data) {
  3413. pdf_set_err(pdf, -ENOMEM, "Unable to allocate PNG data %zu",
  3414. png_data_total_length + 1024 + dstr_len(&colour_space));
  3415. goto free_buffers;
  3416. }
  3417. // Write image information to PDF
  3418. written =
  3419. sprintf((char *)final_data,
  3420. "<<\r\n"
  3421. " /Type /XObject\r\n"
  3422. " /Name /Image%d\r\n"
  3423. " /Subtype /Image\r\n"
  3424. " /ColorSpace %s\r\n"
  3425. " /Width %u\r\n"
  3426. " /Height %u\r\n"
  3427. " /Interpolate true\r\n"
  3428. " /BitsPerComponent %u\r\n"
  3429. " /Filter /FlateDecode\r\n"
  3430. " /DecodeParms << /Predictor 15 /Colors %d "
  3431. "/BitsPerComponent %u /Columns %u >>\r\n"
  3432. " /Length %zu\r\n"
  3433. ">>stream\r\n",
  3434. flexarray_size(&pdf->objects), dstr_data(&colour_space),
  3435. header->width, header->height, header->bitDepth, ncolours,
  3436. header->bitDepth, header->width, png_data_total_length);
  3437. memcpy(&final_data[written], png_data_temp, png_data_total_length);
  3438. written += png_data_total_length;
  3439. written += sprintf((char *)&final_data[written], "\r\nendstream\r\n");
  3440. obj = pdf_add_object(pdf, OBJ_image);
  3441. if (!obj) {
  3442. goto free_buffers;
  3443. }
  3444. dstr_append_data(&obj->stream.stream, final_data, written);
  3445. if (get_img_display_dimensions(pdf, header->width, header->height,
  3446. &display_width, &display_height)) {
  3447. goto free_buffers;
  3448. }
  3449. success = true;
  3450. free_buffers:
  3451. if (final_data)
  3452. free(final_data);
  3453. if (palette_buffer)
  3454. free(palette_buffer);
  3455. if (png_data_temp)
  3456. free(png_data_temp);
  3457. dstr_free(&colour_space);
  3458. if (success)
  3459. return pdf_add_image(pdf, page, obj, x, y, display_width,
  3460. display_height);
  3461. else
  3462. return pdf->errval;
  3463. }
  3464. static int parse_bmp_header(struct pdf_img_info *info, const uint8_t *data,
  3465. size_t data_length, char *err_msg,
  3466. size_t err_msg_length)
  3467. {
  3468. if (data_length < sizeof(bmp_signature) + sizeof(struct bmp_header)) {
  3469. snprintf(err_msg, err_msg_length, "File is too short");
  3470. return -EINVAL;
  3471. }
  3472. if (memcmp(data, bmp_signature, sizeof(bmp_signature))) {
  3473. snprintf(err_msg, err_msg_length, "File is not correct BMP file");
  3474. return -EINVAL;
  3475. }
  3476. memcpy(&info->bmp, &data[sizeof(bmp_signature)],
  3477. sizeof(struct bmp_header));
  3478. if (info->bmp.biWidth < 0) {
  3479. snprintf(err_msg, err_msg_length, "BMP has negative width");
  3480. return -EINVAL;
  3481. }
  3482. if (info->bmp.biHeight == INT_MIN) {
  3483. snprintf(err_msg, err_msg_length, "BMP height overflow");
  3484. return -EINVAL;
  3485. }
  3486. info->width = info->bmp.biWidth;
  3487. // biHeight might be negative (positive indicates vertically mirrored
  3488. // lines)
  3489. info->height = abs(info->bmp.biHeight);
  3490. return 0;
  3491. }
  3492. static int pdf_add_bmp_data(struct pdf_doc *pdf, struct pdf_object *page,
  3493. float x, float y, float display_width,
  3494. float display_height,
  3495. const struct pdf_img_info *info,
  3496. const uint8_t *data, const size_t len)
  3497. {
  3498. const struct bmp_header *header = &info->bmp;
  3499. uint8_t *bmp_data = NULL;
  3500. uint8_t row_padding;
  3501. uint32_t bpp;
  3502. size_t data_len;
  3503. int retval;
  3504. const uint32_t width = info->width;
  3505. const uint32_t height = info->height;
  3506. if (header->bfSize != len)
  3507. return pdf_set_err(pdf, -EINVAL,
  3508. "BMP file seems to have wrong length");
  3509. if (header->biSize != 40)
  3510. return pdf_set_err(pdf, -EINVAL, "Wrong BMP header: biSize");
  3511. if (header->biCompression != 0)
  3512. return pdf_set_err(pdf, -EINVAL, "Wrong BMP compression value: %d",
  3513. header->biCompression);
  3514. if (header->biWidth > MAX_IMAGE_WIDTH || header->biWidth <= 0 ||
  3515. width > MAX_IMAGE_WIDTH || width == 0)
  3516. return pdf_set_err(pdf, -EINVAL, "BMP has invalid width: %d",
  3517. header->biWidth);
  3518. if (header->biHeight > MAX_IMAGE_HEIGHT ||
  3519. header->biHeight < -MAX_IMAGE_HEIGHT || header->biHeight == 0 ||
  3520. height > MAX_IMAGE_HEIGHT || height == 0)
  3521. return pdf_set_err(pdf, -EINVAL, "BMP has invalid height: %d",
  3522. header->biHeight);
  3523. if (header->biBitCount != 24 && header->biBitCount != 32)
  3524. return pdf_set_err(pdf, -EINVAL, "Unsupported BMP bitdepth: %d",
  3525. header->biBitCount);
  3526. bpp = header->biBitCount / 8;
  3527. /* BMP rows are 4-bytes padded! */
  3528. row_padding = (width * bpp) & 3;
  3529. data_len = (size_t)width * (size_t)height * 3;
  3530. if (header->bfOffBits >= len)
  3531. return pdf_set_err(pdf, -EINVAL, "Invalid BMP image offset");
  3532. if (len - header->bfOffBits <
  3533. (size_t)height * (width + row_padding) * bpp)
  3534. return pdf_set_err(pdf, -EINVAL, "Wrong BMP image size");
  3535. if (bpp == 3) {
  3536. /* 24 bits: change R and B colors */
  3537. bmp_data = (uint8_t *)malloc(data_len);
  3538. if (!bmp_data)
  3539. return pdf_set_err(pdf, -ENOMEM,
  3540. "Insufficient memory for bitmap");
  3541. for (uint32_t pos = 0; pos < width * height; pos++) {
  3542. uint32_t src_pos =
  3543. header->bfOffBits + 3 * (pos + (pos / width) * row_padding);
  3544. bmp_data[pos * 3] = data[src_pos + 2];
  3545. bmp_data[pos * 3 + 1] = data[src_pos + 1];
  3546. bmp_data[pos * 3 + 2] = data[src_pos];
  3547. }
  3548. } else if (bpp == 4) {
  3549. /* 32 bits: change R and B colors, remove key color */
  3550. int offs = 0;
  3551. bmp_data = (uint8_t *)malloc(data_len);
  3552. if (!bmp_data)
  3553. return pdf_set_err(pdf, -ENOMEM,
  3554. "Insufficient memory for bitmap");
  3555. for (uint32_t pos = 0; pos < width * height * 4; pos += 4) {
  3556. bmp_data[offs] = data[header->bfOffBits + pos + 2];
  3557. bmp_data[offs + 1] = data[header->bfOffBits + pos + 1];
  3558. bmp_data[offs + 2] = data[header->bfOffBits + pos];
  3559. offs += 3;
  3560. }
  3561. } else {
  3562. return pdf_set_err(pdf, -EINVAL, "Unsupported BMP bitdepth: %d",
  3563. header->biBitCount);
  3564. }
  3565. if (header->biHeight >= 0) {
  3566. // BMP has vertically mirrored representation of lines, so swap them
  3567. uint8_t *line = (uint8_t *)malloc(width * 3);
  3568. if (!line) {
  3569. free(bmp_data);
  3570. return pdf_set_err(pdf, -ENOMEM,
  3571. "Unable to allocate memory for bitmap mirror");
  3572. }
  3573. for (uint32_t pos = 0; pos < (height / 2); pos++) {
  3574. memcpy(line, &bmp_data[pos * width * 3], width * 3);
  3575. memcpy(&bmp_data[pos * width * 3],
  3576. &bmp_data[(height - pos - 1) * width * 3], width * 3);
  3577. memcpy(&bmp_data[(height - pos - 1) * width * 3], line,
  3578. width * 3);
  3579. }
  3580. free(line);
  3581. }
  3582. retval = pdf_add_rgb24(pdf, page, x, y, display_width, display_height,
  3583. bmp_data, width, height);
  3584. free(bmp_data);
  3585. return retval;
  3586. }
  3587. static int determine_image_format(const uint8_t *data, size_t length)
  3588. {
  3589. if (length >= sizeof(png_signature) &&
  3590. memcmp(data, png_signature, sizeof(png_signature)) == 0)
  3591. return IMAGE_PNG;
  3592. if (length >= sizeof(bmp_signature) &&
  3593. memcmp(data, bmp_signature, sizeof(bmp_signature)) == 0)
  3594. return IMAGE_BMP;
  3595. if (length >= sizeof(jpeg_signature) &&
  3596. memcmp(data, jpeg_signature, sizeof(jpeg_signature)) == 0)
  3597. return IMAGE_JPG;
  3598. if (length >= sizeof(ppm_signature) &&
  3599. memcmp(data, ppm_signature, sizeof(ppm_signature)) == 0)
  3600. return IMAGE_PPM;
  3601. if (length >= sizeof(pgm_signature) &&
  3602. memcmp(data, pgm_signature, sizeof(pgm_signature)) == 0)
  3603. return IMAGE_PPM;
  3604. return IMAGE_UNKNOWN;
  3605. }
  3606. int pdf_parse_image_header(struct pdf_img_info *info, const uint8_t *data,
  3607. size_t length, char *err_msg,
  3608. size_t err_msg_length)
  3609. {
  3610. const int image_format = determine_image_format(data, length);
  3611. info->image_format = image_format;
  3612. switch (image_format) {
  3613. case IMAGE_PNG:
  3614. return parse_png_header(info, data, length, err_msg, err_msg_length);
  3615. case IMAGE_BMP:
  3616. return parse_bmp_header(info, data, length, err_msg, err_msg_length);
  3617. case IMAGE_JPG:
  3618. return parse_jpeg_header(info, data, length, err_msg, err_msg_length);
  3619. case IMAGE_PPM:
  3620. return parse_ppm_header(info, data, length, err_msg, err_msg_length);
  3621. case IMAGE_UNKNOWN:
  3622. default:
  3623. snprintf(err_msg, err_msg_length, "Unknown file format");
  3624. return -EINVAL;
  3625. }
  3626. }
  3627. int pdf_add_image_data(struct pdf_doc *pdf, struct pdf_object *page, float x,
  3628. float y, float display_width, float display_height,
  3629. const uint8_t *data, size_t len)
  3630. {
  3631. struct pdf_img_info info = {
  3632. .image_format = IMAGE_UNKNOWN,
  3633. .width = 0,
  3634. .height = 0,
  3635. .jpeg = {0},
  3636. };
  3637. int ret = pdf_parse_image_header(&info, data, len, pdf->errstr,
  3638. sizeof(pdf->errstr));
  3639. if (ret)
  3640. return ret;
  3641. // Try and determine which image format it is based on the content
  3642. switch (info.image_format) {
  3643. case IMAGE_PNG:
  3644. return pdf_add_png_data(pdf, page, x, y, display_width,
  3645. display_height, &info, data, len);
  3646. case IMAGE_BMP:
  3647. return pdf_add_bmp_data(pdf, page, x, y, display_width,
  3648. display_height, &info, data, len);
  3649. case IMAGE_JPG:
  3650. return pdf_add_jpeg_data(pdf, page, x, y, display_width,
  3651. display_height, &info, data, len);
  3652. case IMAGE_PPM:
  3653. return pdf_add_ppm_data(pdf, page, x, y, display_width,
  3654. display_height, &info, data, len);
  3655. // This case should be caught in parse_image_header, but is checked
  3656. // here again for safety
  3657. case IMAGE_UNKNOWN:
  3658. default:
  3659. return pdf_set_err(pdf, -EINVAL, "Unable to determine image format");
  3660. }
  3661. }
  3662. int pdf_add_image_file(struct pdf_doc *pdf, struct pdf_object *page, float x,
  3663. float y, float display_width, float display_height,
  3664. const char *image_filename)
  3665. {
  3666. size_t len;
  3667. uint8_t *data;
  3668. int ret = 0;
  3669. data = get_file(pdf, image_filename, &len);
  3670. if (data == NULL)
  3671. return pdf_get_errval(pdf);
  3672. ret = pdf_add_image_data(pdf, page, x, y, display_width, display_height,
  3673. data, len);
  3674. free(data);
  3675. return ret;
  3676. }