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

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