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

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