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

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