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 66KB

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