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

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