You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PDFFactory.java 75KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.pdf;
  19. // Java
  20. import java.awt.Color;
  21. import java.awt.geom.Point2D;
  22. import java.awt.geom.Rectangle2D;
  23. import java.io.FileNotFoundException;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.net.MalformedURLException;
  27. import java.text.DecimalFormat;
  28. import java.util.ArrayList;
  29. import java.util.Arrays;
  30. import java.util.BitSet;
  31. import java.util.Iterator;
  32. import java.util.List;
  33. import java.util.Map;
  34. import javax.xml.transform.Source;
  35. import javax.xml.transform.stream.StreamSource;
  36. import org.apache.commons.io.IOUtils;
  37. import org.apache.commons.io.output.ByteArrayOutputStream;
  38. import org.apache.commons.logging.Log;
  39. import org.apache.commons.logging.LogFactory;
  40. import org.apache.xmlgraphics.java2d.color.ColorUtil;
  41. import org.apache.xmlgraphics.java2d.color.NamedColorSpace;
  42. import org.apache.xmlgraphics.xmp.Metadata;
  43. import org.apache.fop.fonts.CIDFont;
  44. import org.apache.fop.fonts.CIDSubset;
  45. import org.apache.fop.fonts.CodePointMapping;
  46. import org.apache.fop.fonts.CustomFont;
  47. import org.apache.fop.fonts.FontDescriptor;
  48. import org.apache.fop.fonts.FontMetrics;
  49. import org.apache.fop.fonts.FontType;
  50. import org.apache.fop.fonts.LazyFont;
  51. import org.apache.fop.fonts.MultiByteFont;
  52. import org.apache.fop.fonts.SimpleSingleByteEncoding;
  53. import org.apache.fop.fonts.SingleByteEncoding;
  54. import org.apache.fop.fonts.SingleByteFont;
  55. import org.apache.fop.fonts.Typeface;
  56. import org.apache.fop.fonts.truetype.FontFileReader;
  57. import org.apache.fop.fonts.truetype.TTFSubSetFile;
  58. import org.apache.fop.fonts.type1.PFBData;
  59. import org.apache.fop.fonts.type1.PFBParser;
  60. import org.apache.xmlgraphics.xmp.Metadata;
  61. /**
  62. * This class provides method to create and register PDF objects.
  63. */
  64. public class PDFFactory {
  65. /** Resolution of the User Space coordinate system (72dpi). */
  66. public static final int DEFAULT_PDF_RESOLUTION = 72;
  67. private PDFDocument document;
  68. private Log log = LogFactory.getLog(PDFFactory.class);
  69. private int subsetFontCounter = -1;
  70. /**
  71. * Creates a new PDFFactory.
  72. * @param document the parent PDFDocument needed to register the generated
  73. * objects
  74. */
  75. public PDFFactory(PDFDocument document) {
  76. this.document = document;
  77. }
  78. /**
  79. * Returns the parent PDFDocument associated with this factory.
  80. * @return PDFDocument the parent PDFDocument
  81. */
  82. public final PDFDocument getDocument() {
  83. return this.document;
  84. }
  85. /* ========================= structure objects ========================= */
  86. /**
  87. * Make a /Catalog (Root) object. This object is written in
  88. * the trailer.
  89. *
  90. * @param pages the pages pdf object that the root points to
  91. * @return the new pdf root object for this document
  92. */
  93. public PDFRoot makeRoot(PDFPages pages) {
  94. //Make a /Pages object. This object is written in the trailer.
  95. PDFRoot pdfRoot = new PDFRoot(++this.document.objectcount, pages);
  96. pdfRoot.setDocument(getDocument());
  97. getDocument().addTrailerObject(pdfRoot);
  98. return pdfRoot;
  99. }
  100. /**
  101. * Make a /Pages object. This object is written in the trailer.
  102. *
  103. * @return a new PDF Pages object for adding pages to
  104. */
  105. public PDFPages makePages() {
  106. PDFPages pdfPages = new PDFPages(++(this.document.objectcount));
  107. pdfPages.setDocument(getDocument());
  108. getDocument().addTrailerObject(pdfPages);
  109. return pdfPages;
  110. }
  111. /**
  112. * Make a /Resources object. This object is written in the trailer.
  113. *
  114. * @return a new PDF resources object
  115. */
  116. public PDFResources makeResources() {
  117. PDFResources pdfResources = new PDFResources(++this.document.objectcount);
  118. pdfResources.setDocument(getDocument());
  119. getDocument().addTrailerObject(pdfResources);
  120. return pdfResources;
  121. }
  122. /**
  123. * make an /Info object
  124. *
  125. * @param prod string indicating application producing the PDF
  126. * @return the created /Info object
  127. */
  128. protected PDFInfo makeInfo(String prod) {
  129. /*
  130. * create a PDFInfo with the next object number and add to
  131. * list of objects
  132. */
  133. PDFInfo pdfInfo = new PDFInfo();
  134. // set the default producer
  135. pdfInfo.setProducer(prod);
  136. getDocument().registerObject(pdfInfo);
  137. return pdfInfo;
  138. }
  139. /**
  140. * Make a Metadata object.
  141. * @param meta the DOM Document containing the XMP metadata.
  142. * @param readOnly true if the metadata packet should be marked read-only
  143. * @return the newly created Metadata object
  144. */
  145. public PDFMetadata makeMetadata(Metadata meta, boolean readOnly) {
  146. PDFMetadata pdfMetadata = new PDFMetadata(meta, readOnly);
  147. getDocument().registerObject(pdfMetadata);
  148. return pdfMetadata;
  149. }
  150. /**
  151. * Make a OutputIntent dictionary.
  152. * @return the newly created OutputIntent dictionary
  153. */
  154. public PDFOutputIntent makeOutputIntent() {
  155. PDFOutputIntent outputIntent = new PDFOutputIntent();
  156. getDocument().registerObject(outputIntent);
  157. return outputIntent;
  158. }
  159. /**
  160. * Make a /Page object. The page is assigned an object number immediately
  161. * so references can already be made. The page must be added to the
  162. * PDFDocument later using addObject().
  163. *
  164. * @param resources resources object to use
  165. * @param pageIndex index of the page (zero-based)
  166. * @param mediaBox the MediaBox area
  167. * @param cropBox the CropBox area
  168. * @param bleedBox the BleedBox area
  169. * @param trimBox the TrimBox area
  170. *
  171. * @return the created /Page object
  172. */
  173. public PDFPage makePage(PDFResources resources, int pageIndex,
  174. Rectangle2D mediaBox, Rectangle2D cropBox,
  175. Rectangle2D bleedBox, Rectangle2D trimBox) {
  176. /*
  177. * create a PDFPage with the next object number, the given
  178. * resources, contents and dimensions
  179. */
  180. PDFPage page = new PDFPage(resources, pageIndex, mediaBox, cropBox, bleedBox, trimBox);
  181. getDocument().assignObjectNumber(page);
  182. getDocument().getPages().addPage(page);
  183. return page;
  184. }
  185. /**
  186. * Make a /Page object. The page is assigned an object number immediately
  187. * so references can already be made. The page must be added to the
  188. * PDFDocument later using addObject().
  189. *
  190. * @param resources resources object to use
  191. * @param pageWidth width of the page in points
  192. * @param pageHeight height of the page in points
  193. * @param pageIndex index of the page (zero-based)
  194. *
  195. * @return the created /Page object
  196. */
  197. public PDFPage makePage(PDFResources resources,
  198. int pageWidth, int pageHeight, int pageIndex) {
  199. Rectangle2D mediaBox = new Rectangle2D.Double(0, 0, pageWidth, pageHeight);
  200. return makePage(resources, pageIndex, mediaBox, mediaBox, mediaBox, mediaBox);
  201. }
  202. /**
  203. * Make a /Page object. The page is assigned an object number immediately
  204. * so references can already be made. The page must be added to the
  205. * PDFDocument later using addObject().
  206. *
  207. * @param resources resources object to use
  208. * @param pageWidth width of the page in points
  209. * @param pageHeight height of the page in points
  210. *
  211. * @return the created /Page object
  212. */
  213. public PDFPage makePage(PDFResources resources,
  214. int pageWidth, int pageHeight) {
  215. return makePage(resources, pageWidth, pageHeight, -1);
  216. }
  217. /* ========================= functions ================================= */
  218. /**
  219. * Make a Type 0 sampled function
  220. *
  221. * @param theDomain List objects of Double objects.
  222. * This is the domain of the function.
  223. * See page 264 of the PDF 1.3 Spec.
  224. * @param theRange List objects of Double objects.
  225. * This is the Range of the function.
  226. * See page 264 of the PDF 1.3 Spec.
  227. * @param theSize A List object of Integer objects.
  228. * This is the number of samples in each input dimension.
  229. * I can't imagine there being more or less than two input dimensions,
  230. * so maybe this should be an array of length 2.
  231. *
  232. * See page 265 of the PDF 1.3 Spec.
  233. * @param theBitsPerSample An int specifying the number of bits user
  234. * to represent each sample value.
  235. * Limited to 1,2,4,8,12,16,24 or 32.
  236. * See page 265 of the 1.3 PDF Spec.
  237. * @param theOrder The order of interpolation between samples.
  238. * Default is 1 (one). Limited
  239. * to 1 (one) or 3, which means linear or cubic-spline interpolation.
  240. *
  241. * This attribute is optional.
  242. *
  243. * See page 265 in the PDF 1.3 spec.
  244. * @param theEncode List objects of Double objects.
  245. * This is the linear mapping of input values intop the domain
  246. * of the function's sample table. Default is hard to represent in
  247. * ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
  248. * This attribute is optional.
  249. *
  250. * See page 265 in the PDF 1.3 spec.
  251. * @param theDecode List objects of Double objects.
  252. * This is a linear mapping of sample values into the range.
  253. * The default is just the range.
  254. *
  255. * This attribute is optional.
  256. * Read about it on page 265 of the PDF 1.3 spec.
  257. * @param theFunctionDataStream The sample values that specify
  258. * the function are provided in a stream.
  259. *
  260. * This is optional, but is almost always used.
  261. *
  262. * Page 265 of the PDF 1.3 spec has more.
  263. * @param theFilter This is a vector of String objects which
  264. * are the various filters that have are to be
  265. * applied to the stream to make sense of it.
  266. * Order matters, so watch out.
  267. *
  268. * This is not documented in the Function section of the PDF 1.3 spec,
  269. * it was deduced from samples that this is sometimes used, even if we may never
  270. * use it in FOP. It is added for completeness sake.
  271. * @param theFunctionType This is the type of function (0,2,3, or 4).
  272. * It should be 0 as this is the constructor for sampled functions.
  273. * @return the PDF function that was created
  274. */
  275. public PDFFunction makeFunction( // CSOK: ParameterNumber
  276. int theFunctionType, List theDomain,
  277. List theRange, List theSize,
  278. int theBitsPerSample, int theOrder,
  279. List theEncode, List theDecode,
  280. StringBuffer theFunctionDataStream,
  281. List theFilter) {
  282. // Type 0 function
  283. PDFFunction function = new PDFFunction(theFunctionType, theDomain,
  284. theRange, theSize,
  285. theBitsPerSample, theOrder,
  286. theEncode, theDecode,
  287. theFunctionDataStream,
  288. theFilter);
  289. PDFFunction oldfunc = getDocument().findFunction(function);
  290. if (oldfunc == null) {
  291. getDocument().registerObject(function);
  292. } else {
  293. function = oldfunc;
  294. }
  295. return (function);
  296. }
  297. /**
  298. * make a type Exponential interpolation function
  299. * (for shading usually)
  300. *
  301. * @param theDomain List objects of Double objects.
  302. * This is the domain of the function.
  303. * See page 264 of the PDF 1.3 Spec.
  304. * @param theRange List of Doubles that is the Range of the function.
  305. * See page 264 of the PDF 1.3 Spec.
  306. * @param theCZero This is a vector of Double objects which defines the function result
  307. * when x=0.
  308. *
  309. * This attribute is optional.
  310. * It's described on page 268 of the PDF 1.3 spec.
  311. * @param theCOne This is a vector of Double objects which defines the function result
  312. * when x=1.
  313. *
  314. * This attribute is optional.
  315. * It's described on page 268 of the PDF 1.3 spec.
  316. * @param theInterpolationExponentN This is the inerpolation exponent.
  317. *
  318. * This attribute is required.
  319. * PDF Spec page 268
  320. * @param theFunctionType The type of the function, which should be 2.
  321. * @return the PDF function that was created
  322. */
  323. public PDFFunction makeFunction(int theFunctionType, List theDomain,
  324. List theRange, List theCZero,
  325. List theCOne,
  326. double theInterpolationExponentN) { // type 2
  327. PDFFunction function = new PDFFunction(theFunctionType, theDomain,
  328. theRange, theCZero, theCOne,
  329. theInterpolationExponentN);
  330. PDFFunction oldfunc = getDocument().findFunction(function);
  331. if (oldfunc == null) {
  332. getDocument().registerObject(function);
  333. } else {
  334. function = oldfunc;
  335. }
  336. return (function);
  337. }
  338. /**
  339. * Make a Type 3 Stitching function
  340. *
  341. * @param theDomain List objects of Double objects.
  342. * This is the domain of the function.
  343. * See page 264 of the PDF 1.3 Spec.
  344. * @param theRange List objects of Double objects.
  345. * This is the Range of the function.
  346. * See page 264 of the PDF 1.3 Spec.
  347. * @param theFunctions An List of the PDFFunction objects
  348. * that the stitching function stitches.
  349. *
  350. * This attributed is required.
  351. * It is described on page 269 of the PDF spec.
  352. * @param theBounds This is a vector of Doubles representing
  353. * the numbers that, in conjunction with Domain
  354. * define the intervals to which each function from
  355. * the 'functions' object applies. It must be in
  356. * order of increasing magnitude, and each must be
  357. * within Domain.
  358. *
  359. * It basically sets how much of the gradient each function handles.
  360. *
  361. * This attributed is required.
  362. * It's described on page 269 of the PDF 1.3 spec.
  363. * @param theEncode List objects of Double objects.
  364. * This is the linear mapping of input values intop the domain
  365. * of the function's sample table. Default is hard to represent in
  366. * ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
  367. * This attribute is required.
  368. *
  369. * See page 270 in the PDF 1.3 spec.
  370. * @param theFunctionType This is the function type. It should be 3,
  371. * for a stitching function.
  372. * @return the PDF function that was created
  373. */
  374. public PDFFunction makeFunction(int theFunctionType, List theDomain,
  375. List theRange, List theFunctions,
  376. List theBounds,
  377. List theEncode) {
  378. // Type 3
  379. PDFFunction function = new PDFFunction(theFunctionType, theDomain,
  380. theRange, theFunctions,
  381. theBounds, theEncode);
  382. PDFFunction oldfunc = getDocument().findFunction(function);
  383. if (oldfunc == null) {
  384. getDocument().registerObject(function);
  385. } else {
  386. function = oldfunc;
  387. }
  388. return (function);
  389. }
  390. /**
  391. * make a postscript calculator function
  392. *
  393. * @param theNumber the PDF object number
  394. * @param theFunctionType the type of function to make
  395. * @param theDomain the domain values
  396. * @param theRange the range values of the function
  397. * @param theFunctionDataStream a string containing the pdf drawing
  398. * @return the PDF function that was created
  399. */
  400. public PDFFunction makeFunction(int theNumber, int theFunctionType,
  401. List theDomain, List theRange,
  402. StringBuffer theFunctionDataStream) {
  403. // Type 4
  404. PDFFunction function = new PDFFunction(theFunctionType, theDomain,
  405. theRange,
  406. theFunctionDataStream);
  407. PDFFunction oldfunc = getDocument().findFunction(function);
  408. if (oldfunc == null) {
  409. getDocument().registerObject(function);
  410. } else {
  411. function = oldfunc;
  412. }
  413. return (function);
  414. }
  415. /* ========================= shadings ================================== */
  416. /**
  417. * make a function based shading object
  418. *
  419. * @param res the PDF resource context to add the shading, may be null
  420. * @param theShadingType The type of shading object, which should be 1 for function
  421. * based shading.
  422. * @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
  423. * @param theBackground An array of color components appropriate to the
  424. * colorspace key specifying a single color value.
  425. * This key is used by the f operator buy ignored by the sh operator.
  426. * @param theBBox List of double's representing a rectangle
  427. * in the coordinate space that is current at the
  428. * time of shading is imaged. Temporary clipping
  429. * boundary.
  430. * @param theAntiAlias Whether or not to anti-alias.
  431. * @param theDomain Optional vector of Doubles specifying the domain.
  432. * @param theMatrix List of Doubles specifying the matrix.
  433. * If it's a pattern, then the matrix maps it to pattern space.
  434. * If it's a shading, then it maps it to current user space.
  435. * It's optional, the default is the identity matrix
  436. * @param theFunction The PDF Function that maps an (x,y) location to a color
  437. * @return the PDF shading that was created
  438. */
  439. public PDFShading makeShading( // CSOK: ParameterNumber
  440. PDFResourceContext res, int theShadingType,
  441. PDFDeviceColorSpace theColorSpace,
  442. List theBackground, List theBBox,
  443. boolean theAntiAlias, List theDomain,
  444. List theMatrix,
  445. PDFFunction theFunction) {
  446. // make Shading of Type 1
  447. PDFShading shading = new PDFShading(theShadingType,
  448. theColorSpace, theBackground,
  449. theBBox, theAntiAlias, theDomain,
  450. theMatrix, theFunction);
  451. PDFShading oldshad = getDocument().findShading(shading);
  452. if (oldshad == null) {
  453. getDocument().registerObject(shading);
  454. } else {
  455. shading = oldshad;
  456. }
  457. // add this shading to resources
  458. if (res != null) {
  459. res.getPDFResources().addShading(shading);
  460. } else {
  461. getDocument().getResources().addShading(shading);
  462. }
  463. return (shading);
  464. }
  465. /**
  466. * Make an axial or radial shading object.
  467. *
  468. * @param res the PDF resource context to add the shading, may be null
  469. * @param theShadingType 2 or 3 for axial or radial shading
  470. * @param theColorSpace "DeviceRGB" or similar.
  471. * @param theBackground theBackground An array of color components appropriate to the
  472. * colorspace key specifying a single color value.
  473. * This key is used by the f operator buy ignored by the sh operator.
  474. * @param theBBox List of double's representing a rectangle
  475. * in the coordinate space that is current at the
  476. * time of shading is imaged. Temporary clipping
  477. * boundary.
  478. * @param theAntiAlias Default is false
  479. * @param theCoords List of four (type 2) or 6 (type 3) Double
  480. * @param theDomain List of Doubles specifying the domain
  481. * @param theFunction the Stitching (PDFfunction type 3) function,
  482. * even if it's stitching a single function
  483. * @param theExtend List of Booleans of whether to extend the
  484. * start and end colors past the start and end points
  485. * The default is [false, false]
  486. * @return the PDF shading that was created
  487. */
  488. public PDFShading makeShading( // CSOK: ParameterNumber
  489. PDFResourceContext res, int theShadingType,
  490. PDFDeviceColorSpace theColorSpace,
  491. List theBackground, List theBBox,
  492. boolean theAntiAlias, List theCoords,
  493. List theDomain, PDFFunction theFunction,
  494. List theExtend) {
  495. // make Shading of Type 2 or 3
  496. PDFShading shading = new PDFShading(theShadingType,
  497. theColorSpace, theBackground,
  498. theBBox, theAntiAlias, theCoords,
  499. theDomain, theFunction,
  500. theExtend);
  501. PDFShading oldshad = getDocument().findShading(shading);
  502. if (oldshad == null) {
  503. getDocument().registerObject(shading);
  504. } else {
  505. shading = oldshad;
  506. }
  507. if (res != null) {
  508. res.getPDFResources().addShading(shading);
  509. } else {
  510. getDocument().getResources().addShading(shading);
  511. }
  512. return (shading);
  513. }
  514. /**
  515. * Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
  516. * shading object
  517. *
  518. * @param res the PDF resource context to add the shading, may be null
  519. * @param theShadingType 4, 6, or 7 depending on whether it's
  520. * Free-form gouraud-shaded triangle meshes, coons patch meshes,
  521. * or tensor product patch meshes, respectively.
  522. * @param theColorSpace "DeviceRGB" or similar.
  523. * @param theBackground theBackground An array of color components appropriate to the
  524. * colorspace key specifying a single color value.
  525. * This key is used by the f operator buy ignored by the sh operator.
  526. * @param theBBox List of double's representing a rectangle
  527. * in the coordinate space that is current at the
  528. * time of shading is imaged. Temporary clipping
  529. * boundary.
  530. * @param theAntiAlias Default is false
  531. * @param theBitsPerCoordinate 1,2,4,8,12,16,24 or 32.
  532. * @param theBitsPerComponent 1,2,4,8,12, and 16
  533. * @param theBitsPerFlag 2,4,8.
  534. * @param theDecode List of Doubles see PDF 1.3 spec pages 303 to 312.
  535. * @param theFunction the PDFFunction
  536. * @return the PDF shading that was created
  537. */
  538. public PDFShading makeShading( // CSOK: ParameterNumber
  539. PDFResourceContext res, int theShadingType,
  540. PDFDeviceColorSpace theColorSpace,
  541. List theBackground, List theBBox,
  542. boolean theAntiAlias,
  543. int theBitsPerCoordinate,
  544. int theBitsPerComponent,
  545. int theBitsPerFlag, List theDecode,
  546. PDFFunction theFunction) {
  547. // make Shading of type 4,6 or 7
  548. PDFShading shading = new PDFShading(theShadingType,
  549. theColorSpace, theBackground,
  550. theBBox, theAntiAlias,
  551. theBitsPerCoordinate,
  552. theBitsPerComponent,
  553. theBitsPerFlag, theDecode,
  554. theFunction);
  555. PDFShading oldshad = getDocument().findShading(shading);
  556. if (oldshad == null) {
  557. getDocument().registerObject(shading);
  558. } else {
  559. shading = oldshad;
  560. }
  561. if (res != null) {
  562. res.getPDFResources().addShading(shading);
  563. } else {
  564. getDocument().getResources().addShading(shading);
  565. }
  566. return (shading);
  567. }
  568. /**
  569. * make a Lattice-Form Gouraud mesh shading object
  570. *
  571. * @param res the PDF resource context to add the shading, may be null
  572. * @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
  573. * without spaces. "Shading1" or "Sh1" are good examples.
  574. * @param theColorSpace "DeviceRGB" or similar.
  575. * @param theBackground theBackground An array of color components appropriate to the
  576. * colorspace key specifying a single color value.
  577. * This key is used by the f operator buy ignored by the sh operator.
  578. * @param theBBox List of double's representing a rectangle
  579. * in the coordinate space that is current at the
  580. * time of shading is imaged. Temporary clipping
  581. * boundary.
  582. * @param theAntiAlias Default is false
  583. * @param theBitsPerCoordinate 1,2,4,8,12,16, 24, or 32
  584. * @param theBitsPerComponent 1,2,4,8,12,24,32
  585. * @param theDecode List of Doubles. See page 305 in PDF 1.3 spec.
  586. * @param theVerticesPerRow number of vertices in each "row" of the lattice.
  587. * @param theFunction The PDFFunction that's mapped on to this shape
  588. * @return the PDF shading that was created
  589. */
  590. public PDFShading makeShading( // CSOK: ParameterNumber
  591. PDFResourceContext res, int theShadingType,
  592. PDFDeviceColorSpace theColorSpace,
  593. List theBackground, List theBBox,
  594. boolean theAntiAlias,
  595. int theBitsPerCoordinate,
  596. int theBitsPerComponent, List theDecode,
  597. int theVerticesPerRow,
  598. PDFFunction theFunction) {
  599. // make shading of Type 5
  600. PDFShading shading = new PDFShading(theShadingType,
  601. theColorSpace, theBackground,
  602. theBBox, theAntiAlias,
  603. theBitsPerCoordinate,
  604. theBitsPerComponent, theDecode,
  605. theVerticesPerRow, theFunction);
  606. PDFShading oldshad = getDocument().findShading(shading);
  607. if (oldshad == null) {
  608. getDocument().registerObject(shading);
  609. } else {
  610. shading = oldshad;
  611. }
  612. if (res != null) {
  613. res.getPDFResources().addShading(shading);
  614. } else {
  615. getDocument().getResources().addShading(shading);
  616. }
  617. return (shading);
  618. }
  619. /* ========================= patterns ================================== */
  620. /**
  621. * Make a tiling pattern
  622. *
  623. * @param res the PDF resource context to add the shading, may be null
  624. * @param thePatternType the type of pattern, which is 1 for tiling.
  625. * @param theResources the resources associated with this pattern
  626. * @param thePaintType 1 or 2, colored or uncolored.
  627. * @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
  628. * @param theBBox List of Doubles: The pattern cell bounding box
  629. * @param theXStep horizontal spacing
  630. * @param theYStep vertical spacing
  631. * @param theMatrix Optional List of Doubles transformation matrix
  632. * @param theXUID Optional vector of Integers that uniquely identify the pattern
  633. * @param thePatternDataStream The stream of pattern data to be tiled.
  634. * @return the PDF pattern that was created
  635. */
  636. public PDFPattern makePattern( // CSOK: ParameterNumber
  637. PDFResourceContext res, int thePatternType, // 1
  638. PDFResources theResources, int thePaintType, int theTilingType,
  639. List theBBox, double theXStep,
  640. double theYStep, List theMatrix,
  641. List theXUID, StringBuffer thePatternDataStream) {
  642. // PDFResources theResources
  643. PDFPattern pattern = new PDFPattern(theResources, 1,
  644. thePaintType, theTilingType,
  645. theBBox, theXStep, theYStep,
  646. theMatrix, theXUID,
  647. thePatternDataStream);
  648. PDFPattern oldpatt = getDocument().findPattern(pattern);
  649. if (oldpatt == null) {
  650. getDocument().registerObject(pattern);
  651. } else {
  652. pattern = oldpatt;
  653. }
  654. if (res != null) {
  655. res.getPDFResources().addPattern(pattern);
  656. } else {
  657. getDocument().getResources().addPattern(pattern);
  658. }
  659. return (pattern);
  660. }
  661. /**
  662. * Make a smooth shading pattern
  663. *
  664. * @param res the PDF resource context to add the shading, may be null
  665. * @param thePatternType the type of the pattern, which is 2, smooth shading
  666. * @param theShading the PDF Shading object that comprises this pattern
  667. * @param theXUID optional:the extended unique Identifier if used.
  668. * @param theExtGState optional: the extended graphics state, if used.
  669. * @param theMatrix Optional:List of Doubles that specify the matrix.
  670. * @return the PDF pattern that was created
  671. */
  672. public PDFPattern makePattern(PDFResourceContext res,
  673. int thePatternType, PDFShading theShading,
  674. List theXUID, StringBuffer theExtGState,
  675. List theMatrix) {
  676. PDFPattern pattern = new PDFPattern(2, theShading,
  677. theXUID, theExtGState, theMatrix);
  678. PDFPattern oldpatt = getDocument().findPattern(pattern);
  679. if (oldpatt == null) {
  680. getDocument().registerObject(pattern);
  681. } else {
  682. pattern = oldpatt;
  683. }
  684. if (res != null) {
  685. res.getPDFResources().addPattern(pattern);
  686. } else {
  687. getDocument().getResources().addPattern(pattern);
  688. }
  689. return (pattern);
  690. }
  691. /**
  692. * Make a gradient
  693. *
  694. * @param res the PDF resource context to add the shading, may be null
  695. * @param radial if true a radial gradient will be created
  696. * @param theColorspace the colorspace of the gradient
  697. * @param theColors the list of colors for the gradient
  698. * @param theBounds the list of bounds associated with the colors
  699. * @param theCoords the coordinates for the gradient
  700. * @param theMatrix the coordinate-transformation matrix
  701. * @return the PDF pattern that was created
  702. */
  703. public PDFPattern makeGradient(PDFResourceContext res, boolean radial,
  704. PDFDeviceColorSpace theColorspace,
  705. List theColors, List theBounds,
  706. List theCoords, List theMatrix) {
  707. PDFShading myShad;
  708. PDFFunction myfunky;
  709. PDFFunction myfunc;
  710. List theCzero;
  711. List theCone;
  712. PDFPattern myPattern;
  713. //PDFColorSpace theColorSpace;
  714. double interpolation = 1.000;
  715. List theFunctions = new ArrayList();
  716. int currentPosition;
  717. int lastPosition = theColors.size() - 1;
  718. // if 5 elements, the penultimate element is 3.
  719. // do not go beyond that, because you always need
  720. // to have a next color when creating the function.
  721. for (currentPosition = 0; currentPosition < lastPosition;
  722. currentPosition++) { // for every consecutive color pair
  723. Color currentColor = (Color)theColors.get(currentPosition);
  724. Color nextColor = (Color)theColors.get(currentPosition + 1);
  725. // colorspace must be consistent, so we simply convert to sRGB where necessary
  726. if (!currentColor.getColorSpace().isCS_sRGB()) {
  727. //Convert to sRGB
  728. currentColor = ColorUtil.toSRGBColor(currentColor);
  729. theColors.set(currentPosition, currentColor);
  730. }
  731. if (!nextColor.getColorSpace().isCS_sRGB()) {
  732. //Convert to sRGB
  733. nextColor = ColorUtil.toSRGBColor(nextColor);
  734. theColors.set(currentPosition + 1, nextColor);
  735. }
  736. theCzero = toColorVector(currentColor);
  737. theCone = toColorVector(nextColor);
  738. myfunc = makeFunction(2, null, null, theCzero, theCone,
  739. interpolation);
  740. theFunctions.add(myfunc);
  741. } // end of for every consecutive color pair
  742. myfunky = makeFunction(3, null, null, theFunctions, theBounds,
  743. null);
  744. if (radial) {
  745. if (theCoords.size() == 6) {
  746. myShad = makeShading(res, 3, getDocument().getPDFColorSpace(),
  747. null, null,
  748. false, theCoords, null, myfunky,
  749. null);
  750. } else { // if the center x, center y, and radius specifiy
  751. // the gradient, then assume the same center x, center y,
  752. // and radius of zero for the other necessary component
  753. List newCoords = new ArrayList();
  754. newCoords.add(theCoords.get(0));
  755. newCoords.add(theCoords.get(1));
  756. newCoords.add(theCoords.get(2));
  757. newCoords.add(theCoords.get(0));
  758. newCoords.add(theCoords.get(1));
  759. newCoords.add(new Double(0.0));
  760. myShad = makeShading(res, 3, getDocument().getPDFColorSpace(),
  761. null, null,
  762. false, newCoords, null, myfunky,
  763. null);
  764. }
  765. } else {
  766. myShad = makeShading(res, 2, getDocument().getPDFColorSpace(),
  767. null, null,
  768. false, theCoords, null, myfunky,
  769. null);
  770. }
  771. myPattern = makePattern(res, 2, myShad, null, null, theMatrix);
  772. return (myPattern);
  773. }
  774. private List toColorVector(Color nextColor) {
  775. List vector = new java.util.ArrayList();
  776. float[] comps = nextColor.getColorComponents(null);
  777. for (int i = 0, c = comps.length; i < c; i++) {
  778. vector.add(new Double(comps[i]));
  779. }
  780. return vector;
  781. }
  782. /* ============= named destinations and the name dictionary ============ */
  783. /**
  784. * Registers and returns newdest if it is unique. Otherwise, returns
  785. * the equal destination already present in the document.
  786. *
  787. * @param newdest a new, as yet unregistered destination
  788. * @return newdest if unique, else the already registered instance
  789. */
  790. protected PDFDestination getUniqueDestination(PDFDestination newdest) {
  791. PDFDestination existing = getDocument().findDestination(newdest);
  792. if (existing != null) {
  793. return existing;
  794. } else {
  795. getDocument().addDestination(newdest);
  796. return newdest;
  797. }
  798. }
  799. /**
  800. * Make a named destination.
  801. *
  802. * @param idRef ID Reference for this destination (the name of the destination)
  803. * @param goToRef Object reference to the GoTo Action
  804. * @return the newly created destrination
  805. */
  806. public PDFDestination makeDestination(String idRef, Object goToRef) {
  807. PDFDestination destination = new PDFDestination(idRef, goToRef);
  808. return getUniqueDestination(destination);
  809. }
  810. /**
  811. * Make a names dictionary (the /Names object).
  812. * @return the new PDFNames object
  813. */
  814. public PDFNames makeNames() {
  815. PDFNames names = new PDFNames();
  816. getDocument().assignObjectNumber(names);
  817. getDocument().addTrailerObject(names);
  818. return names;
  819. }
  820. /**
  821. * Make a names dictionary (the /PageLabels object).
  822. * @return the new PDFPageLabels object
  823. */
  824. public PDFPageLabels makePageLabels() {
  825. PDFPageLabels pageLabels = new PDFPageLabels();
  826. getDocument().assignObjectNumber(pageLabels);
  827. getDocument().addTrailerObject(pageLabels);
  828. return pageLabels;
  829. }
  830. /**
  831. * Creates and returns a StructTreeRoot object. Used for accessibility.
  832. * @param parentTree the value of the ParenTree entry
  833. * @return structure Tree Root element
  834. */
  835. public PDFStructTreeRoot makeStructTreeRoot(PDFParentTree parentTree) {
  836. PDFStructTreeRoot structTreeRoot = new PDFStructTreeRoot(parentTree);
  837. getDocument().assignObjectNumber(structTreeRoot);
  838. getDocument().addTrailerObject(structTreeRoot);
  839. getDocument().getRoot().setStructTreeRoot(structTreeRoot);
  840. return structTreeRoot;
  841. }
  842. /**
  843. * Creates and returns a StructElem object.
  844. *
  845. * @param structureType the structure type of the new element (value for the
  846. * S entry)
  847. * @param parent the parent of the new structure element in the structure
  848. * hierarchy
  849. * @return the newly created element
  850. */
  851. public PDFStructElem makeStructureElement(PDFName structureType, PDFObject parent) {
  852. PDFStructElem structElem = new PDFStructElem(parent, structureType);
  853. getDocument().assignObjectNumber(structElem);
  854. getDocument().addTrailerObject(structElem);
  855. return structElem;
  856. }
  857. /**
  858. * Make a the head object of the name dictionary (the /Dests object).
  859. *
  860. * @param destinationList a list of PDFDestination instances
  861. * @return the new PDFDests object
  862. */
  863. public PDFDests makeDests(List destinationList) {
  864. PDFDests dests;
  865. //TODO: Check why the below conditional branch is needed. Condition is always true...
  866. final boolean deep = true;
  867. //true for a "deep" structure (one node per entry), true for a "flat" structure
  868. if (deep) {
  869. dests = new PDFDests();
  870. PDFArray kids = new PDFArray(dests);
  871. Iterator iter = destinationList.iterator();
  872. while (iter.hasNext()) {
  873. PDFDestination dest = (PDFDestination)iter.next();
  874. PDFNameTreeNode node = new PDFNameTreeNode();
  875. getDocument().registerObject(node);
  876. node.setLowerLimit(dest.getIDRef());
  877. node.setUpperLimit(dest.getIDRef());
  878. node.setNames(new PDFArray(node));
  879. PDFArray names = node.getNames();
  880. names.add(dest);
  881. kids.add(node);
  882. }
  883. dests.setLowerLimit(((PDFNameTreeNode)kids.get(0)).getLowerLimit());
  884. dests.setUpperLimit(((PDFNameTreeNode)kids.get(kids.length() - 1)).getUpperLimit());
  885. dests.setKids(kids);
  886. } else {
  887. dests = new PDFDests(destinationList);
  888. }
  889. getDocument().registerObject(dests);
  890. return dests;
  891. }
  892. /**
  893. * Make a name tree node.
  894. *
  895. * @return the new name tree node
  896. */
  897. public PDFNameTreeNode makeNameTreeNode() {
  898. PDFNameTreeNode node = new PDFNameTreeNode();
  899. getDocument().registerObject(node);
  900. return node;
  901. }
  902. /* ========================= links ===================================== */
  903. // Some of the "yoffset-only" functions in this part are obsolete and can
  904. // possibly be removed or deprecated. Some are still called by PDFGraphics2D
  905. // (although that could be changed, they don't need the yOffset param anyway).
  906. /**
  907. * Create a PDF link to an existing PDFAction object
  908. *
  909. * @param rect the hotspot position in absolute coordinates
  910. * @param pdfAction the PDFAction that this link refers to
  911. * @return the new PDFLink object, or null if either rect or pdfAction is null
  912. */
  913. public PDFLink makeLink(Rectangle2D rect, PDFAction pdfAction) {
  914. if (rect == null || pdfAction == null) {
  915. return null;
  916. } else {
  917. PDFLink link = new PDFLink(rect);
  918. link.setAction(pdfAction);
  919. getDocument().registerObject(link);
  920. return link;
  921. // does findLink make sense? I mean, how often will it happen that several
  922. // links have the same target *and* the same hot rect? And findLink has to
  923. // walk and compare the entire link list everytime you call it...
  924. }
  925. }
  926. /**
  927. * Make an internal link.
  928. *
  929. * @param rect the hotspot position in absolute coordinates
  930. * @param page the target page reference value
  931. * @param dest the position destination
  932. * @return the new PDF link object
  933. */
  934. public PDFLink makeLink(Rectangle2D rect, String page, String dest) {
  935. PDFLink link = new PDFLink(rect);
  936. getDocument().registerObject(link);
  937. PDFGoTo gt = new PDFGoTo(page);
  938. gt.setDestination(dest);
  939. getDocument().registerObject(gt);
  940. PDFInternalLink internalLink = new PDFInternalLink(gt.referencePDF());
  941. link.setAction(internalLink);
  942. return link;
  943. }
  944. /**
  945. * Make a {@link PDFLink} object
  946. *
  947. * @param rect the clickable rectangle
  948. * @param destination the destination file
  949. * @param linkType the link type
  950. * @param yoffset the yoffset on the page for an internal link
  951. * @return the PDFLink object created
  952. */
  953. public PDFLink makeLink(Rectangle2D rect, String destination,
  954. int linkType, float yoffset) {
  955. //PDFLink linkObject;
  956. PDFLink link = new PDFLink(rect);
  957. if (linkType == PDFLink.EXTERNAL) {
  958. link.setAction(getExternalAction(destination, false));
  959. } else {
  960. // linkType is internal
  961. String goToReference = getGoToReference(destination, yoffset);
  962. PDFInternalLink internalLink = new PDFInternalLink(goToReference);
  963. link.setAction(internalLink);
  964. }
  965. PDFLink oldlink = getDocument().findLink(link);
  966. if (oldlink == null) {
  967. getDocument().registerObject(link);
  968. } else {
  969. link = oldlink;
  970. }
  971. return link;
  972. }
  973. private static final String EMBEDDED_FILE = "embedded-file:";
  974. /**
  975. * Create/find and return the appropriate external PDFAction according to the target
  976. *
  977. * @param target The external target. This may be a PDF file name
  978. * (optionally with internal page number or destination) or any type of URI.
  979. * @param newWindow boolean indicating whether the target should be
  980. * displayed in a new window
  981. * @return the PDFAction thus created or found
  982. */
  983. public PDFAction getExternalAction(String target, boolean newWindow) {
  984. int index;
  985. String targetLo = target.toLowerCase();
  986. if (target.startsWith(EMBEDDED_FILE)) {
  987. // File Attachments (Embedded Files)
  988. String filename = target.substring(EMBEDDED_FILE.length());
  989. return getActionForEmbeddedFile(filename, newWindow);
  990. } else if (targetLo.startsWith("http://")) {
  991. // HTTP URL?
  992. return new PDFUri(target);
  993. } else if (targetLo.startsWith("file://")) {
  994. // Non PDF files. Try to /Launch them.
  995. target = target.substring("file://".length());
  996. return getLaunchAction(target);
  997. } else if (targetLo.endsWith(".pdf")) {
  998. // Bare PDF file name?
  999. return getGoToPDFAction(target, null, -1, newWindow);
  1000. } else if ((index = targetLo.indexOf(".pdf#page=")) > 0) { // CSOK: InnerAssignment
  1001. // PDF file + page?
  1002. String filename = target.substring(0, index + 4);
  1003. int page = Integer.parseInt(target.substring(index + 10));
  1004. return getGoToPDFAction(filename, null, page, newWindow);
  1005. } else if ((index = targetLo.indexOf(".pdf#dest=")) > 0) { // CSOK: InnerAssignment
  1006. // PDF file + destination?
  1007. String filename = target.substring(0, index + 4);
  1008. String dest = target.substring(index + 10);
  1009. return getGoToPDFAction(filename, dest, -1, newWindow);
  1010. } else {
  1011. // None of the above? Default to URI:
  1012. return new PDFUri(target);
  1013. }
  1014. }
  1015. private PDFAction getActionForEmbeddedFile(String filename, boolean newWindow) {
  1016. PDFNames names = getDocument().getRoot().getNames();
  1017. if (names == null) {
  1018. throw new IllegalStateException(
  1019. "No Names dictionary present."
  1020. + " Cannot create Launch Action for embedded file: " + filename);
  1021. }
  1022. PDFNameTreeNode embeddedFiles = names.getEmbeddedFiles();
  1023. if (embeddedFiles == null) {
  1024. throw new IllegalStateException(
  1025. "No /EmbeddedFiles name tree present."
  1026. + " Cannot create Launch Action for embedded file: " + filename);
  1027. }
  1028. //Find filespec reference for the embedded file
  1029. filename = PDFText.toPDFString(filename, '_');
  1030. PDFArray files = embeddedFiles.getNames();
  1031. PDFReference embeddedFileRef = null;
  1032. int i = 0;
  1033. while (i < files.length()) {
  1034. String name = (String)files.get(i);
  1035. i++;
  1036. PDFReference ref = (PDFReference)files.get(i);
  1037. if (name.equals(filename)) {
  1038. embeddedFileRef = ref;
  1039. break;
  1040. }
  1041. i++;
  1042. }
  1043. if (embeddedFileRef == null) {
  1044. throw new IllegalStateException(
  1045. "No embedded file with name " + filename + " present.");
  1046. }
  1047. //Finally create the action
  1048. //PDFLaunch action = new PDFLaunch(embeddedFileRef);
  1049. //This works with Acrobat 8 but not with Acrobat 9
  1050. //The following two options didn't seem to have any effect.
  1051. //PDFGoToEmbedded action = new PDFGoToEmbedded(embeddedFileRef, 0, newWindow);
  1052. //PDFGoToRemote action = new PDFGoToRemote(embeddedFileRef, 0, newWindow);
  1053. //This finally seems to work:
  1054. StringBuffer scriptBuffer = new StringBuffer();
  1055. scriptBuffer.append("this.exportDataObject({cName:\"");
  1056. scriptBuffer.append(filename);
  1057. scriptBuffer.append("\", nLaunch:2});");
  1058. PDFJavaScriptLaunchAction action = new PDFJavaScriptLaunchAction(scriptBuffer.toString());
  1059. return action;
  1060. }
  1061. /**
  1062. * Create or find a PDF GoTo with the given page reference string and Y offset,
  1063. * and return its PDF object reference
  1064. *
  1065. * @param pdfPageRef the PDF page reference, e.g. "23 0 R"
  1066. * @param yoffset the distance from the bottom of the page in points
  1067. * @return the GoTo's object reference
  1068. */
  1069. public String getGoToReference(String pdfPageRef, float yoffset) {
  1070. return getPDFGoTo(pdfPageRef, new Point2D.Float(0.0f, yoffset)).referencePDF();
  1071. }
  1072. /**
  1073. * Finds and returns a PDFGoTo to the given page and position.
  1074. * Creates the PDFGoTo if not found.
  1075. *
  1076. * @param pdfPageRef the PDF page reference
  1077. * @param position the (X,Y) position in points
  1078. *
  1079. * @return the new or existing PDFGoTo object
  1080. */
  1081. public PDFGoTo getPDFGoTo(String pdfPageRef, Point2D position) {
  1082. getDocument().getProfile().verifyActionAllowed();
  1083. PDFGoTo gt = new PDFGoTo(pdfPageRef, position);
  1084. PDFGoTo oldgt = getDocument().findGoTo(gt);
  1085. if (oldgt == null) {
  1086. getDocument().assignObjectNumber(gt);
  1087. getDocument().addTrailerObject(gt);
  1088. } else {
  1089. gt = oldgt;
  1090. }
  1091. return gt;
  1092. }
  1093. /**
  1094. * Create and return a goto pdf document action.
  1095. * This creates a pdf files spec and pdf goto remote action.
  1096. * It also checks available pdf objects so it will not create an
  1097. * object if it already exists.
  1098. *
  1099. * @param file the pdf file name
  1100. * @param dest the remote name destination, may be null
  1101. * @param page the remote page number, -1 means not specified
  1102. * @param newWindow boolean indicating whether the target should be
  1103. * displayed in a new window
  1104. * @return the pdf goto remote object
  1105. */
  1106. private PDFGoToRemote getGoToPDFAction(String file, String dest, int page, boolean newWindow) {
  1107. getDocument().getProfile().verifyActionAllowed();
  1108. PDFFileSpec fileSpec = new PDFFileSpec(file);
  1109. PDFFileSpec oldspec = getDocument().findFileSpec(fileSpec);
  1110. if (oldspec == null) {
  1111. getDocument().registerObject(fileSpec);
  1112. } else {
  1113. fileSpec = oldspec;
  1114. }
  1115. PDFGoToRemote remote;
  1116. if (dest == null && page == -1) {
  1117. remote = new PDFGoToRemote(fileSpec, newWindow);
  1118. } else if (dest != null) {
  1119. remote = new PDFGoToRemote(fileSpec, dest, newWindow);
  1120. } else {
  1121. remote = new PDFGoToRemote(fileSpec, page, newWindow);
  1122. }
  1123. PDFGoToRemote oldremote = getDocument().findGoToRemote(remote);
  1124. if (oldremote == null) {
  1125. getDocument().registerObject(remote);
  1126. } else {
  1127. remote = oldremote;
  1128. }
  1129. return remote;
  1130. }
  1131. /**
  1132. * Creates and returns a launch pdf document action using
  1133. * <code>file</code> to create a file spcifiaciton for
  1134. * the document/file to be opened with an external application.
  1135. *
  1136. * @param file the pdf file name
  1137. * @return the pdf launch object
  1138. */
  1139. private PDFLaunch getLaunchAction(String file) {
  1140. getDocument().getProfile().verifyActionAllowed();
  1141. PDFFileSpec fileSpec = new PDFFileSpec(file);
  1142. PDFFileSpec oldSpec = getDocument().findFileSpec(fileSpec);
  1143. if (oldSpec == null) {
  1144. getDocument().registerObject(fileSpec);
  1145. } else {
  1146. fileSpec = oldSpec;
  1147. }
  1148. PDFLaunch launch = new PDFLaunch(fileSpec);
  1149. PDFLaunch oldLaunch = getDocument().findLaunch(launch);
  1150. if (oldLaunch == null) {
  1151. getDocument().registerObject(launch);
  1152. } else {
  1153. launch = oldLaunch;
  1154. }
  1155. return launch;
  1156. }
  1157. /**
  1158. * Make an outline object and add it to the given parent
  1159. *
  1160. * @param parent the parent PDFOutline object (may be null)
  1161. * @param label the title for the new outline object
  1162. * @param actionRef the action reference string to be placed after the /A
  1163. * @param showSubItems whether to initially display child outline items
  1164. * @return the new PDF outline object
  1165. */
  1166. public PDFOutline makeOutline(PDFOutline parent, String label,
  1167. String actionRef, boolean showSubItems) {
  1168. PDFOutline pdfOutline = new PDFOutline(label, actionRef, showSubItems);
  1169. if (parent != null) {
  1170. parent.addOutline(pdfOutline);
  1171. }
  1172. getDocument().registerObject(pdfOutline);
  1173. return pdfOutline;
  1174. }
  1175. /**
  1176. * Make an outline object and add it to the given parent
  1177. *
  1178. * @param parent the parent PDFOutline object (may be null)
  1179. * @param label the title for the new outline object
  1180. * @param pdfAction the action that this outline item points to - must not be null!
  1181. * @param showSubItems whether to initially display child outline items
  1182. * @return the new PDFOutline object, or null if pdfAction is null
  1183. */
  1184. public PDFOutline makeOutline(PDFOutline parent, String label,
  1185. PDFAction pdfAction, boolean showSubItems) {
  1186. return pdfAction == null
  1187. ? null
  1188. : makeOutline(parent, label, pdfAction.getAction(), showSubItems);
  1189. }
  1190. // This one is obsolete now, at least it isn't called from anywhere inside FOP
  1191. /**
  1192. * Make an outline object and add it to the given outline
  1193. *
  1194. * @param parent parent PDFOutline object which may be null
  1195. * @param label the title for the new outline object
  1196. * @param destination the reference string for the action to go to
  1197. * @param yoffset the yoffset on the destination page
  1198. * @param showSubItems whether to initially display child outline items
  1199. * @return the new PDF outline object
  1200. */
  1201. public PDFOutline makeOutline(PDFOutline parent, String label,
  1202. String destination, float yoffset,
  1203. boolean showSubItems) {
  1204. String goToRef = getGoToReference(destination, yoffset);
  1205. return makeOutline(parent, label, goToRef, showSubItems);
  1206. }
  1207. /* ========================= fonts ===================================== */
  1208. /**
  1209. * make a /Encoding object
  1210. *
  1211. * @param encodingName character encoding scheme name
  1212. * @return the created /Encoding object
  1213. */
  1214. public PDFEncoding makeEncoding(String encodingName) {
  1215. PDFEncoding encoding = new PDFEncoding(encodingName);
  1216. getDocument().registerObject(encoding);
  1217. return encoding;
  1218. }
  1219. /**
  1220. * Make a Type1 /Font object.
  1221. *
  1222. * @param fontname internal name to use for this font (eg "F1")
  1223. * @param basefont name of the base font (eg "Helvetica")
  1224. * @param encoding character encoding scheme used by the font
  1225. * @param metrics additional information about the font
  1226. * @param descriptor additional information about the font
  1227. * @return the created /Font object
  1228. */
  1229. public PDFFont makeFont(String fontname, String basefont,
  1230. String encoding, FontMetrics metrics,
  1231. FontDescriptor descriptor) {
  1232. PDFFont preRegisteredfont = getDocument().findFont(fontname);
  1233. if (preRegisteredfont != null) {
  1234. return preRegisteredfont;
  1235. }
  1236. boolean forceToUnicode = true;
  1237. if (descriptor == null) {
  1238. //Usually Base 14 fonts
  1239. PDFFont font = new PDFFont(fontname, FontType.TYPE1, basefont, encoding);
  1240. getDocument().registerObject(font);
  1241. if (forceToUnicode && !PDFEncoding.isPredefinedEncoding(encoding)) {
  1242. SingleByteEncoding mapping;
  1243. if (encoding != null) {
  1244. mapping = CodePointMapping.getMapping(encoding);
  1245. } else {
  1246. //for Symbol and ZapfDingbats where encoding must be null in PDF
  1247. Typeface tf = (Typeface)metrics;
  1248. mapping = CodePointMapping.getMapping(tf.getEncodingName());
  1249. }
  1250. generateToUnicodeCmap(font, mapping);
  1251. }
  1252. return font;
  1253. } else {
  1254. FontType fonttype = metrics.getFontType();
  1255. String fontPrefix = descriptor.isSubsetEmbedded() ? createSubsetFontPrefix() : "";
  1256. String subsetFontName = fontPrefix + basefont;
  1257. PDFFontDescriptor pdfdesc = makeFontDescriptor(descriptor, fontPrefix);
  1258. PDFFont font = null;
  1259. font = PDFFont.createFont(fontname, fonttype, subsetFontName, null);
  1260. getDocument().registerObject(font);
  1261. if (fonttype == FontType.TYPE0) {
  1262. font.setEncoding(encoding);
  1263. CIDFont cidMetrics;
  1264. if (metrics instanceof LazyFont) {
  1265. cidMetrics = (CIDFont)((LazyFont) metrics).getRealFont();
  1266. } else {
  1267. cidMetrics = (CIDFont)metrics;
  1268. }
  1269. PDFCIDSystemInfo sysInfo
  1270. = new PDFCIDSystemInfo(cidMetrics.getRegistry(),
  1271. cidMetrics.getOrdering(),
  1272. cidMetrics.getSupplement());
  1273. PDFCIDFont cidFont = new PDFCIDFont(subsetFontName,
  1274. cidMetrics.getCIDType(),
  1275. cidMetrics.getDefaultWidth(),
  1276. getSubsetWidths(cidMetrics), sysInfo,
  1277. (PDFCIDFontDescriptor)pdfdesc);
  1278. getDocument().registerObject(cidFont);
  1279. PDFCMap cmap = new PDFToUnicodeCMap(
  1280. cidMetrics.getCIDSubset().getSubsetChars(),
  1281. "fop-ucs-H",
  1282. new PDFCIDSystemInfo("Adobe",
  1283. "Identity",
  1284. 0), false);
  1285. getDocument().registerObject(cmap);
  1286. ((PDFFontType0)font).setCMAP(cmap);
  1287. ((PDFFontType0)font).setDescendantFonts(cidFont);
  1288. } else {
  1289. PDFFontNonBase14 nonBase14 = (PDFFontNonBase14)font;
  1290. nonBase14.setDescriptor(pdfdesc);
  1291. SingleByteFont singleByteFont;
  1292. if (metrics instanceof LazyFont) {
  1293. singleByteFont = (SingleByteFont)((LazyFont)metrics).getRealFont();
  1294. } else {
  1295. singleByteFont = (SingleByteFont)metrics;
  1296. }
  1297. int firstChar = singleByteFont.getFirstChar();
  1298. int lastChar = singleByteFont.getLastChar();
  1299. nonBase14.setWidthMetrics(firstChar,
  1300. lastChar,
  1301. new PDFArray(null, metrics.getWidths()));
  1302. //Handle encoding
  1303. SingleByteEncoding mapping = singleByteFont.getEncoding();
  1304. if (singleByteFont.isSymbolicFont()) {
  1305. //no encoding, use the font's encoding
  1306. if (forceToUnicode) {
  1307. generateToUnicodeCmap(nonBase14, mapping);
  1308. }
  1309. } else if (PDFEncoding.isPredefinedEncoding(mapping.getName())) {
  1310. font.setEncoding(mapping.getName());
  1311. //No ToUnicode CMap necessary if PDF 1.4, chapter 5.9 (page 368) is to be
  1312. //believed.
  1313. } else {
  1314. Object pdfEncoding = createPDFEncoding(mapping,
  1315. singleByteFont.getFontName());
  1316. if (pdfEncoding instanceof PDFEncoding) {
  1317. font.setEncoding((PDFEncoding)pdfEncoding);
  1318. } else {
  1319. font.setEncoding((String)pdfEncoding);
  1320. }
  1321. if (forceToUnicode) {
  1322. generateToUnicodeCmap(nonBase14, mapping);
  1323. }
  1324. }
  1325. //Handle additional encodings (characters outside the primary encoding)
  1326. if (singleByteFont.hasAdditionalEncodings()) {
  1327. for (int i = 0, c = singleByteFont.getAdditionalEncodingCount(); i < c; i++) {
  1328. SimpleSingleByteEncoding addEncoding
  1329. = singleByteFont.getAdditionalEncoding(i);
  1330. String name = fontname + "_" + (i + 1);
  1331. Object pdfenc = createPDFEncoding(addEncoding,
  1332. singleByteFont.getFontName());
  1333. PDFFontNonBase14 addFont = (PDFFontNonBase14)PDFFont.createFont(
  1334. name, fonttype,
  1335. basefont, pdfenc);
  1336. addFont.setDescriptor(pdfdesc);
  1337. addFont.setWidthMetrics(
  1338. addEncoding.getFirstChar(),
  1339. addEncoding.getLastChar(),
  1340. new PDFArray(null, singleByteFont.getAdditionalWidths(i)));
  1341. getDocument().registerObject(addFont);
  1342. getDocument().getResources().addFont(addFont);
  1343. if (forceToUnicode) {
  1344. generateToUnicodeCmap(addFont, addEncoding);
  1345. }
  1346. }
  1347. }
  1348. }
  1349. return font;
  1350. }
  1351. }
  1352. private void generateToUnicodeCmap(PDFFont font, SingleByteEncoding encoding) {
  1353. PDFCMap cmap = new PDFToUnicodeCMap(encoding.getUnicodeCharMap(),
  1354. "fop-ucs-H",
  1355. new PDFCIDSystemInfo("Adobe", "Identity", 0), true);
  1356. getDocument().registerObject(cmap);
  1357. font.setToUnicode(cmap);
  1358. }
  1359. /**
  1360. * Creates a PDFEncoding instance from a CodePointMapping instance.
  1361. * @param encoding the code point mapping (encoding)
  1362. * @param fontNameHint ...
  1363. * @return the PDF Encoding dictionary (or a String with the predefined encoding)
  1364. */
  1365. public Object createPDFEncoding(SingleByteEncoding encoding, String fontNameHint) {
  1366. SingleByteEncoding baseEncoding;
  1367. if (fontNameHint.indexOf("Symbol") >= 0) {
  1368. baseEncoding = CodePointMapping.getMapping(
  1369. CodePointMapping.SYMBOL_ENCODING);
  1370. } else {
  1371. baseEncoding = CodePointMapping.getMapping(
  1372. CodePointMapping.STANDARD_ENCODING);
  1373. }
  1374. PDFEncoding pdfEncoding = new PDFEncoding(baseEncoding.getName());
  1375. PDFEncoding.DifferencesBuilder builder
  1376. = pdfEncoding.createDifferencesBuilder();
  1377. int start = -1;
  1378. String[] baseNames = baseEncoding.getCharNameMap();
  1379. String[] charNameMap = encoding.getCharNameMap();
  1380. for (int i = 0, ci = charNameMap.length; i < ci; i++) {
  1381. String basec = baseNames[i];
  1382. String c = charNameMap[i];
  1383. if (!basec.equals(c)) {
  1384. if (start != i) {
  1385. builder.addDifference(i);
  1386. start = i;
  1387. }
  1388. builder.addName(c);
  1389. start++;
  1390. }
  1391. }
  1392. if (builder.hasDifferences()) {
  1393. pdfEncoding.setDifferences(builder.toPDFArray());
  1394. return pdfEncoding;
  1395. } else {
  1396. return baseEncoding.getName();
  1397. }
  1398. }
  1399. /**
  1400. * Creates and returns a width array with the widths of all the characters in the subset.
  1401. * @param cidFont the font
  1402. * @return the width array
  1403. */
  1404. public PDFWArray getSubsetWidths(CIDFont cidFont) {
  1405. // Create widths for reencoded chars
  1406. PDFWArray warray = new PDFWArray();
  1407. int[] widths = cidFont.getWidths();
  1408. CIDSubset subset = cidFont.getCIDSubset();
  1409. int[] tmpWidth = new int[subset.getSubsetSize()];
  1410. for (int i = 0, c = subset.getSubsetSize(); i < c; i++) {
  1411. int nwx = Math.max(0, subset.getGlyphIndexForSubsetIndex(i));
  1412. tmpWidth[i] = widths[nwx];
  1413. }
  1414. warray.addEntry(0, tmpWidth);
  1415. return warray;
  1416. }
  1417. private String createSubsetFontPrefix() {
  1418. subsetFontCounter++;
  1419. DecimalFormat counterFormat = new DecimalFormat("00000");
  1420. String counterString = counterFormat.format(subsetFontCounter);
  1421. // Subset prefix as described in chapter 5.5.3 of PDF 1.4
  1422. StringBuffer sb = new StringBuffer("E");
  1423. for (char c : counterString.toCharArray()) {
  1424. // translate numbers to uppercase characters
  1425. sb.append((char) (c + ('A' - '0')));
  1426. }
  1427. sb.append("+");
  1428. return sb.toString();
  1429. }
  1430. /**
  1431. * make a /FontDescriptor object
  1432. *
  1433. * @param desc the font descriptor
  1434. * @param fontPrefix the String with which to prefix the font name
  1435. * @return the new PDF font descriptor
  1436. */
  1437. private PDFFontDescriptor makeFontDescriptor(FontDescriptor desc, String fontPrefix) {
  1438. PDFFontDescriptor descriptor = null;
  1439. if (desc.getFontType() == FontType.TYPE0) {
  1440. // CID Font
  1441. descriptor = new PDFCIDFontDescriptor(fontPrefix + desc.getEmbedFontName(),
  1442. desc.getFontBBox(),
  1443. desc.getCapHeight(),
  1444. desc.getFlags(),
  1445. desc.getItalicAngle(),
  1446. desc.getStemV(), null);
  1447. } else {
  1448. // Create normal FontDescriptor
  1449. descriptor = new PDFFontDescriptor(desc.getEmbedFontName(),
  1450. desc.getAscender(),
  1451. desc.getDescender(),
  1452. desc.getCapHeight(),
  1453. desc.getFlags(),
  1454. new PDFRectangle(desc.getFontBBox()),
  1455. desc.getItalicAngle(),
  1456. desc.getStemV());
  1457. }
  1458. getDocument().registerObject(descriptor);
  1459. // Check if the font is embeddable
  1460. if (desc.isEmbeddable()) {
  1461. AbstractPDFStream stream = makeFontFile(desc);
  1462. if (stream != null) {
  1463. descriptor.setFontFile(desc.getFontType(), stream);
  1464. getDocument().registerObject(stream);
  1465. }
  1466. CustomFont font = getCustomFont(desc);
  1467. if (font instanceof CIDFont) {
  1468. CIDFont cidFont = (CIDFont)font;
  1469. buildCIDSet(descriptor, cidFont);
  1470. }
  1471. }
  1472. return descriptor;
  1473. }
  1474. private void buildCIDSet(PDFFontDescriptor descriptor, CIDFont cidFont) {
  1475. BitSet cidSubset = cidFont.getCIDSubset().getGlyphIndexBitSet();
  1476. PDFStream cidSet = makeStream(null, true);
  1477. ByteArrayOutputStream baout = new ByteArrayOutputStream(cidSubset.length() / 8 + 1);
  1478. int value = 0;
  1479. for (int i = 0, c = cidSubset.length(); i < c; i++) {
  1480. int shift = i % 8;
  1481. boolean b = cidSubset.get(i);
  1482. if (b) {
  1483. value |= 1 << 7 - shift;
  1484. }
  1485. if (shift == 7) {
  1486. baout.write(value);
  1487. value = 0;
  1488. }
  1489. }
  1490. baout.write(value);
  1491. try {
  1492. cidSet.setData(baout.toByteArray());
  1493. descriptor.setCIDSet(cidSet);
  1494. } catch (IOException ioe) {
  1495. log.error(
  1496. "Failed to write CIDSet [" + cidFont + "] "
  1497. + cidFont.getEmbedFontName(), ioe);
  1498. }
  1499. }
  1500. /**
  1501. * Embeds a font.
  1502. * @param desc FontDescriptor of the font.
  1503. * @return PDFStream The embedded font file
  1504. */
  1505. public AbstractPDFStream makeFontFile(FontDescriptor desc) {
  1506. if (desc.getFontType() == FontType.OTHER) {
  1507. throw new IllegalArgumentException("Trying to embed unsupported font type: "
  1508. + desc.getFontType());
  1509. }
  1510. CustomFont font = getCustomFont(desc);
  1511. InputStream in = null;
  1512. try {
  1513. Source source = font.getEmbedFileSource();
  1514. if (source == null && font.getEmbedResourceName() != null) {
  1515. source = new StreamSource(this.getClass()
  1516. .getResourceAsStream(font.getEmbedResourceName()));
  1517. }
  1518. if (source == null) {
  1519. return null;
  1520. }
  1521. if (source instanceof StreamSource) {
  1522. in = ((StreamSource) source).getInputStream();
  1523. }
  1524. if (in == null && source.getSystemId() != null) {
  1525. try {
  1526. in = new java.net.URL(source.getSystemId()).openStream();
  1527. } catch (MalformedURLException e) {
  1528. //TODO: Why construct a new exception here, when it is not thrown?
  1529. new FileNotFoundException(
  1530. "File not found. URL could not be resolved: "
  1531. + e.getMessage());
  1532. }
  1533. }
  1534. if (in == null) {
  1535. return null;
  1536. }
  1537. //Make sure the InputStream is decorated with a BufferedInputStream
  1538. if (!(in instanceof java.io.BufferedInputStream)) {
  1539. in = new java.io.BufferedInputStream(in);
  1540. }
  1541. if (in == null) {
  1542. return null;
  1543. } else {
  1544. try {
  1545. AbstractPDFStream embeddedFont;
  1546. if (desc.getFontType() == FontType.TYPE0) {
  1547. MultiByteFont mbfont = (MultiByteFont)font;
  1548. FontFileReader reader = new FontFileReader(in);
  1549. TTFSubSetFile subset = new TTFSubSetFile();
  1550. byte[] subsetFont = subset.readFont(reader,
  1551. mbfont.getTTCName(), mbfont.getUsedGlyphs());
  1552. // Only TrueType CID fonts are supported now
  1553. embeddedFont = new PDFTTFStream(subsetFont.length);
  1554. ((PDFTTFStream)embeddedFont).setData(subsetFont, subsetFont.length);
  1555. } else if (desc.getFontType() == FontType.TYPE1) {
  1556. PFBParser parser = new PFBParser();
  1557. PFBData pfb = parser.parsePFB(in);
  1558. embeddedFont = new PDFT1Stream();
  1559. ((PDFT1Stream)embeddedFont).setData(pfb);
  1560. } else {
  1561. byte[] file = IOUtils.toByteArray(in);
  1562. embeddedFont = new PDFTTFStream(file.length);
  1563. ((PDFTTFStream)embeddedFont).setData(file, file.length);
  1564. }
  1565. /*
  1566. embeddedFont.getFilterList().addFilter("flate");
  1567. if (getDocument().isEncryptionActive()) {
  1568. getDocument().applyEncryption(embeddedFont);
  1569. } else {
  1570. embeddedFont.getFilterList().addFilter("ascii-85");
  1571. }*/
  1572. return embeddedFont;
  1573. } finally {
  1574. in.close();
  1575. }
  1576. }
  1577. } catch (IOException ioe) {
  1578. log.error(
  1579. "Failed to embed font [" + desc + "] "
  1580. + desc.getEmbedFontName(), ioe);
  1581. return null;
  1582. }
  1583. }
  1584. private CustomFont getCustomFont(FontDescriptor desc) {
  1585. Typeface tempFont;
  1586. if (desc instanceof LazyFont) {
  1587. tempFont = ((LazyFont)desc).getRealFont();
  1588. } else {
  1589. tempFont = (Typeface)desc;
  1590. }
  1591. if (!(tempFont instanceof CustomFont)) {
  1592. throw new IllegalArgumentException(
  1593. "FontDescriptor must be instance of CustomFont, but is a "
  1594. + desc.getClass().getName());
  1595. }
  1596. return (CustomFont)tempFont;
  1597. }
  1598. /* ========================= streams =================================== */
  1599. /**
  1600. * Make a stream object
  1601. *
  1602. * @param type the type of stream to be created
  1603. * @param add if true then the stream will be added immediately
  1604. * @return the stream object created
  1605. */
  1606. public PDFStream makeStream(String type, boolean add) {
  1607. // create a PDFStream with the next object number
  1608. // and add it to the list of objects
  1609. PDFStream obj = new PDFStream();
  1610. obj.setDocument(getDocument());
  1611. obj.getFilterList().addDefaultFilters(
  1612. getDocument().getFilterMap(),
  1613. type);
  1614. if (add) {
  1615. getDocument().registerObject(obj);
  1616. }
  1617. //getDocument().applyEncryption(obj);
  1618. return obj;
  1619. }
  1620. /**
  1621. * Create a PDFICCStream
  1622. * @see PDFImageXObject
  1623. * @see org.apache.fop.pdf.PDFDeviceColorSpace
  1624. * @return the new PDF ICC stream object
  1625. */
  1626. public PDFICCStream makePDFICCStream() {
  1627. PDFICCStream iccStream = new PDFICCStream();
  1628. getDocument().registerObject(iccStream);
  1629. //getDocument().applyEncryption(iccStream);
  1630. return iccStream;
  1631. }
  1632. /* ========================= misc. objects ============================= */
  1633. /**
  1634. * Makes a new ICCBased color space and registers it in the resource context.
  1635. * @param res the PDF resource context to add the shading, may be null
  1636. * @param explicitName the explicit name for the color space, may be null
  1637. * @param iccStream the ICC stream to associate with this color space
  1638. * @return the newly instantiated color space
  1639. */
  1640. public PDFICCBasedColorSpace makeICCBasedColorSpace(PDFResourceContext res,
  1641. String explicitName, PDFICCStream iccStream) {
  1642. PDFICCBasedColorSpace cs = new PDFICCBasedColorSpace(explicitName, iccStream);
  1643. getDocument().registerObject(cs);
  1644. if (res != null) {
  1645. res.getPDFResources().addColorSpace(cs);
  1646. } else {
  1647. getDocument().getResources().addColorSpace(cs);
  1648. }
  1649. return cs;
  1650. }
  1651. /**
  1652. * Create a new Separation color space.
  1653. * @param res the resource context (may be null)
  1654. * @param ncs the named color space to map to a separation color space
  1655. * @return the newly created Separation color space
  1656. */
  1657. public PDFSeparationColorSpace makeSeparationColorSpace(PDFResourceContext res,
  1658. NamedColorSpace ncs) {
  1659. String colorName = ncs.getColorName();
  1660. final Double zero = new Double(0d);
  1661. final Double one = new Double(1d);
  1662. List theDomain = Arrays.asList(new Double[] {zero, one});
  1663. List theRange = Arrays.asList(new Double[] {zero, one, zero, one, zero, one});
  1664. List theCZero = Arrays.asList(new Double[] {one, one, one});
  1665. List theCOne = new ArrayList();
  1666. float[] comps = ncs.getRGBColor().getColorComponents(null);
  1667. for (int i = 0, c = comps.length; i < c; i++) {
  1668. theCOne.add(new Double(comps[i]));
  1669. }
  1670. PDFFunction tintFunction = makeFunction(2, theDomain, theRange,
  1671. theCZero, theCOne, 1.0d);
  1672. PDFSeparationColorSpace cs = new PDFSeparationColorSpace(colorName, tintFunction);
  1673. getDocument().registerObject(cs);
  1674. if (res != null) {
  1675. res.getPDFResources().addColorSpace(cs);
  1676. } else {
  1677. getDocument().getResources().addColorSpace(cs);
  1678. }
  1679. return cs;
  1680. }
  1681. /**
  1682. * Make an Array object (ex. Widths array for a font).
  1683. *
  1684. * @param values the int array values
  1685. * @return the PDF Array with the int values
  1686. */
  1687. public PDFArray makeArray(int[] values) {
  1688. PDFArray array = new PDFArray(null, values);
  1689. getDocument().registerObject(array);
  1690. return array;
  1691. }
  1692. /**
  1693. * make an ExtGState for extra graphics options
  1694. * This tries to find a GState that will setup the correct values
  1695. * for the current context. If there is no suitable GState it will
  1696. * create a new one.
  1697. *
  1698. * @param settings the settings required by the caller
  1699. * @param current the current GState of the current PDF context
  1700. * @return a PDF GState, either an existing GState or a new one
  1701. */
  1702. public PDFGState makeGState(Map settings, PDFGState current) {
  1703. // try to locate a gstate that has all the settings
  1704. // or will inherit from the current gstate
  1705. // compare "DEFAULT + settings" with "current + each gstate"
  1706. PDFGState wanted = new PDFGState();
  1707. wanted.addValues(PDFGState.DEFAULT);
  1708. wanted.addValues(settings);
  1709. PDFGState existing = getDocument().findGState(wanted, current);
  1710. if (existing != null) {
  1711. return existing;
  1712. }
  1713. PDFGState gstate = new PDFGState();
  1714. gstate.addValues(settings);
  1715. getDocument().registerObject(gstate);
  1716. return gstate;
  1717. }
  1718. /**
  1719. * Make an annotation list object
  1720. *
  1721. * @return the annotation list object created
  1722. */
  1723. public PDFAnnotList makeAnnotList() {
  1724. PDFAnnotList obj = new PDFAnnotList();
  1725. getDocument().assignObjectNumber(obj);
  1726. return obj;
  1727. }
  1728. }