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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.pdf;
  19. // Java
  20. import java.awt.geom.Point2D;
  21. import java.awt.geom.Rectangle2D;
  22. import java.io.ByteArrayInputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.text.DecimalFormat;
  26. import java.util.ArrayList;
  27. import java.util.Arrays;
  28. import java.util.BitSet;
  29. import java.util.Iterator;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.SortedSet;
  33. import java.util.TreeSet;
  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.java2d.color.NamedColorSpace;
  39. import org.apache.xmlgraphics.xmp.Metadata;
  40. import org.apache.fop.fonts.CIDFont;
  41. import org.apache.fop.fonts.CodePointMapping;
  42. import org.apache.fop.fonts.CustomFont;
  43. import org.apache.fop.fonts.EmbeddingMode;
  44. import org.apache.fop.fonts.FontDescriptor;
  45. import org.apache.fop.fonts.FontMetrics;
  46. import org.apache.fop.fonts.FontType;
  47. import org.apache.fop.fonts.LazyFont;
  48. import org.apache.fop.fonts.MultiByteFont;
  49. import org.apache.fop.fonts.SimpleSingleByteEncoding;
  50. import org.apache.fop.fonts.SingleByteEncoding;
  51. import org.apache.fop.fonts.SingleByteFont;
  52. import org.apache.fop.fonts.Typeface;
  53. import org.apache.fop.fonts.truetype.FontFileReader;
  54. import org.apache.fop.fonts.truetype.OFFontLoader;
  55. import org.apache.fop.fonts.truetype.OTFSubSetFile;
  56. import org.apache.fop.fonts.truetype.TTFSubSetFile;
  57. import org.apache.fop.fonts.type1.PFBData;
  58. import org.apache.fop.fonts.type1.PFBParser;
  59. import org.apache.fop.fonts.type1.Type1SubsetFile;
  60. /**
  61. * This class provides method to create and register PDF objects.
  62. */
  63. public class PDFFactory {
  64. /** Resolution of the User Space coordinate system (72dpi). */
  65. public static final int DEFAULT_PDF_RESOLUTION = 72;
  66. private PDFDocument document;
  67. private Log log = LogFactory.getLog(PDFFactory.class);
  68. private int subsetFontCounter = -1;
  69. /**
  70. * Creates a new PDFFactory.
  71. * @param document the parent PDFDocument needed to register the generated
  72. * objects
  73. */
  74. public PDFFactory(PDFDocument document) {
  75. this.document = document;
  76. }
  77. /**
  78. * Returns the parent PDFDocument associated with this factory.
  79. * @return PDFDocument the parent PDFDocument
  80. */
  81. public final PDFDocument getDocument() {
  82. return this.document;
  83. }
  84. /* ========================= structure objects ========================= */
  85. /**
  86. * Make a /Catalog (Root) object. This object is written in
  87. * the trailer.
  88. *
  89. * @param pages the pages pdf object that the root points to
  90. * @return the new pdf root object for this document
  91. */
  92. public PDFRoot makeRoot(PDFPages pages) {
  93. //Make a /Pages object. This object is written in the trailer.
  94. PDFRoot pdfRoot = new PDFRoot(++this.document.objectcount, pages);
  95. pdfRoot.setDocument(getDocument());
  96. getDocument().addTrailerObject(pdfRoot);
  97. return pdfRoot;
  98. }
  99. /**
  100. * Make a /Pages object. This object is written in the trailer.
  101. *
  102. * @return a new PDF Pages object for adding pages to
  103. */
  104. public PDFPages makePages() {
  105. PDFPages pdfPages = new PDFPages(++(this.document.objectcount));
  106. pdfPages.setDocument(getDocument());
  107. getDocument().addTrailerObject(pdfPages);
  108. return pdfPages;
  109. }
  110. /**
  111. * Make a /Resources object. This object is written in the trailer.
  112. *
  113. * @return a new PDF resources object
  114. */
  115. public PDFResources makeResources() {
  116. PDFResources pdfResources = new PDFResources(++this.document.objectcount);
  117. pdfResources.setDocument(getDocument());
  118. getDocument().addTrailerObject(pdfResources);
  119. return pdfResources;
  120. }
  121. /**
  122. * make an /Info object
  123. *
  124. * @param prod string indicating application producing the PDF
  125. * @return the created /Info object
  126. */
  127. protected PDFInfo makeInfo(String prod) {
  128. /*
  129. * create a PDFInfo with the next object number and add to
  130. * list of objects
  131. */
  132. PDFInfo pdfInfo = new PDFInfo();
  133. // set the default producer
  134. pdfInfo.setProducer(prod);
  135. getDocument().registerObject(pdfInfo);
  136. return pdfInfo;
  137. }
  138. /**
  139. * Make a Metadata object.
  140. * @param meta the DOM Document containing the XMP metadata.
  141. * @param readOnly true if the metadata packet should be marked read-only
  142. * @return the newly created Metadata object
  143. */
  144. public PDFMetadata makeMetadata(Metadata meta, boolean readOnly) {
  145. PDFMetadata pdfMetadata = new PDFMetadata(meta, readOnly);
  146. getDocument().registerObject(pdfMetadata);
  147. return pdfMetadata;
  148. }
  149. /**
  150. * Make a OutputIntent dictionary.
  151. * @return the newly created OutputIntent dictionary
  152. */
  153. public PDFOutputIntent makeOutputIntent() {
  154. PDFOutputIntent outputIntent = new PDFOutputIntent();
  155. getDocument().registerObject(outputIntent);
  156. return outputIntent;
  157. }
  158. /**
  159. * Make a /Page object. The page is assigned an object number immediately
  160. * so references can already be made. The page must be added to the
  161. * PDFDocument later using addObject().
  162. *
  163. * @param resources resources object to use
  164. * @param pageIndex index of the page (zero-based)
  165. * @param mediaBox the MediaBox area
  166. * @param cropBox the CropBox area
  167. * @param bleedBox the BleedBox area
  168. * @param trimBox the TrimBox area
  169. *
  170. * @return the created /Page object
  171. */
  172. public PDFPage makePage(PDFResources resources, int pageIndex,
  173. Rectangle2D mediaBox, Rectangle2D cropBox,
  174. Rectangle2D bleedBox, Rectangle2D trimBox) {
  175. /*
  176. * create a PDFPage with the next object number, the given
  177. * resources, contents and dimensions
  178. */
  179. PDFPage page = new PDFPage(resources, pageIndex, mediaBox, cropBox, bleedBox, trimBox);
  180. getDocument().assignObjectNumber(page);
  181. getDocument().getPages().addPage(page);
  182. return page;
  183. }
  184. /**
  185. * Make a /Page object. The page is assigned an object number immediately
  186. * so references can already be made. The page must be added to the
  187. * PDFDocument later using addObject().
  188. *
  189. * @param resources resources object to use
  190. * @param pageWidth width of the page in points
  191. * @param pageHeight height of the page in points
  192. * @param pageIndex index of the page (zero-based)
  193. *
  194. * @return the created /Page object
  195. */
  196. public PDFPage makePage(PDFResources resources,
  197. int pageWidth, int pageHeight, int pageIndex) {
  198. Rectangle2D mediaBox = new Rectangle2D.Double(0, 0, pageWidth, pageHeight);
  199. return makePage(resources, pageIndex, mediaBox, mediaBox, mediaBox, mediaBox);
  200. }
  201. /**
  202. * Make a /Page object. The page is assigned an object number immediately
  203. * so references can already be made. The page must be added to the
  204. * PDFDocument later using addObject().
  205. *
  206. * @param resources resources object to use
  207. * @param pageWidth width of the page in points
  208. * @param pageHeight height of the page in points
  209. *
  210. * @return the created /Page object
  211. */
  212. public PDFPage makePage(PDFResources resources,
  213. int pageWidth, int pageHeight) {
  214. return makePage(resources, pageWidth, pageHeight, -1);
  215. }
  216. /* ========================= functions ================================= */
  217. /**
  218. * make a type Exponential interpolation function
  219. * (for shading usually)
  220. *
  221. * @param theDomain List objects of Double objects.
  222. * This is the domain of the function.
  223. * See page 264 of the PDF 1.3 Spec.
  224. * @param theRange List of Doubles that is the Range of the function.
  225. * See page 264 of the PDF 1.3 Spec.
  226. * @param theCZero This is a vector of Double objects which defines the function result
  227. * when x=0.
  228. *
  229. * This attribute is optional.
  230. * It's described on page 268 of the PDF 1.3 spec.
  231. * @param theCOne This is a vector of Double objects which defines the function result
  232. * when x=1.
  233. *
  234. * This attribute is optional.
  235. * It's described on page 268 of the PDF 1.3 spec.
  236. * @param theInterpolationExponentN This is the inerpolation exponent.
  237. *
  238. * This attribute is required.
  239. * PDF Spec page 268
  240. * @param theFunctionType The type of the function, which should be 2.
  241. * @return the PDF function that was created
  242. */
  243. public PDFFunction makeFunction(int theFunctionType, List theDomain,
  244. List theRange, List theCZero,
  245. List theCOne,
  246. double theInterpolationExponentN) { // type 2
  247. PDFFunction function = new PDFFunction(theFunctionType, theDomain,
  248. theRange, theCZero, theCOne,
  249. theInterpolationExponentN);
  250. function = registerFunction(function);
  251. return function;
  252. }
  253. /**
  254. * Registers a function against the document
  255. * @param function The function to register
  256. */
  257. public PDFFunction registerFunction(PDFFunction function) {
  258. PDFFunction oldfunc = getDocument().findFunction(function);
  259. if (oldfunc == null) {
  260. getDocument().registerObject(function);
  261. } else {
  262. function = oldfunc;
  263. }
  264. return function;
  265. }
  266. /* ========================= shadings ================================== */
  267. /**
  268. * Registers a shading object against the document
  269. * @param res The PDF resource context
  270. * @param shading The shading object to be registered
  271. */
  272. public PDFShading registerShading(PDFResourceContext res, PDFShading shading) {
  273. PDFShading oldshad = getDocument().findShading(shading);
  274. if (oldshad == null) {
  275. getDocument().registerObject(shading);
  276. } else {
  277. shading = oldshad;
  278. }
  279. // add this shading to resources
  280. if (res != null) {
  281. res.getPDFResources().addShading(shading);
  282. } else {
  283. getDocument().getResources().addShading(shading);
  284. }
  285. return shading;
  286. }
  287. /* ========================= patterns ================================== */
  288. /**
  289. * Make a tiling pattern
  290. *
  291. * @param res the PDF resource context to add the shading, may be null
  292. * @param thePatternType the type of pattern, which is 1 for tiling.
  293. * @param theResources the resources associated with this pattern
  294. * @param thePaintType 1 or 2, colored or uncolored.
  295. * @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
  296. * @param theBBox List of Doubles: The pattern cell bounding box
  297. * @param theXStep horizontal spacing
  298. * @param theYStep vertical spacing
  299. * @param theMatrix Optional List of Doubles transformation matrix
  300. * @param theXUID Optional vector of Integers that uniquely identify the pattern
  301. * @param thePatternDataStream The stream of pattern data to be tiled.
  302. * @return the PDF pattern that was created
  303. */
  304. public PDFPattern makePattern(PDFResourceContext res, int thePatternType,
  305. PDFResources theResources, int thePaintType, int theTilingType,
  306. List theBBox, double theXStep,
  307. double theYStep, List theMatrix,
  308. List theXUID, StringBuffer thePatternDataStream) {
  309. // PDFResources theResources
  310. PDFPattern pattern = new PDFPattern(theResources, 1,
  311. thePaintType, theTilingType,
  312. theBBox, theXStep, theYStep,
  313. theMatrix, theXUID,
  314. thePatternDataStream);
  315. PDFPattern oldpatt = getDocument().findPattern(pattern);
  316. if (oldpatt == null) {
  317. getDocument().registerObject(pattern);
  318. } else {
  319. pattern = oldpatt;
  320. }
  321. if (res != null) {
  322. res.getPDFResources().addPattern(pattern);
  323. } else {
  324. getDocument().getResources().addPattern(pattern);
  325. }
  326. return (pattern);
  327. }
  328. public PDFPattern registerPattern(PDFResourceContext res, PDFPattern pattern) {
  329. PDFPattern oldpatt = getDocument().findPattern(pattern);
  330. if (oldpatt == null) {
  331. getDocument().registerObject(pattern);
  332. } else {
  333. pattern = oldpatt;
  334. }
  335. if (res != null) {
  336. res.getPDFResources().addPattern(pattern);
  337. } else {
  338. getDocument().getResources().addPattern(pattern);
  339. }
  340. return pattern;
  341. }
  342. /**
  343. * Make a smooth shading pattern
  344. *
  345. * @param res the PDF resource context to add the shading, may be null
  346. * @param thePatternType the type of the pattern, which is 2, smooth shading
  347. * @param theShading the PDF Shading object that comprises this pattern
  348. * @param theXUID optional:the extended unique Identifier if used.
  349. * @param theExtGState optional: the extended graphics state, if used.
  350. * @param theMatrix Optional:List of Doubles that specify the matrix.
  351. * @return the PDF pattern that was created
  352. */
  353. public PDFPattern makePattern(PDFResourceContext res,
  354. int thePatternType, PDFShading theShading,
  355. List theXUID, StringBuffer theExtGState,
  356. List theMatrix) {
  357. PDFPattern pattern = new PDFPattern(2, theShading,
  358. theXUID, theExtGState, theMatrix);
  359. PDFPattern oldpatt = getDocument().findPattern(pattern);
  360. if (oldpatt == null) {
  361. getDocument().registerObject(pattern);
  362. } else {
  363. pattern = oldpatt;
  364. }
  365. if (res != null) {
  366. res.getPDFResources().addPattern(pattern);
  367. } else {
  368. getDocument().getResources().addPattern(pattern);
  369. }
  370. return (pattern);
  371. }
  372. /* ============= named destinations and the name dictionary ============ */
  373. /**
  374. * Registers and returns newdest if it is unique. Otherwise, returns
  375. * the equal destination already present in the document.
  376. *
  377. * @param newdest a new, as yet unregistered destination
  378. * @return newdest if unique, else the already registered instance
  379. */
  380. protected PDFDestination getUniqueDestination(PDFDestination newdest) {
  381. PDFDestination existing = getDocument().findDestination(newdest);
  382. if (existing != null) {
  383. return existing;
  384. } else {
  385. getDocument().addDestination(newdest);
  386. return newdest;
  387. }
  388. }
  389. /**
  390. * Make a named destination.
  391. *
  392. * @param idRef ID Reference for this destination (the name of the destination)
  393. * @param goToRef Object reference to the GoTo Action
  394. * @return the newly created destrination
  395. */
  396. public PDFDestination makeDestination(String idRef, Object goToRef) {
  397. PDFDestination destination = new PDFDestination(idRef, goToRef);
  398. return getUniqueDestination(destination);
  399. }
  400. /**
  401. * Make a names dictionary (the /Names object).
  402. * @return the new PDFNames object
  403. */
  404. public PDFNames makeNames() {
  405. PDFNames names = new PDFNames();
  406. getDocument().assignObjectNumber(names);
  407. getDocument().addTrailerObject(names);
  408. return names;
  409. }
  410. /**
  411. * Make a names dictionary (the /PageLabels object).
  412. * @return the new PDFPageLabels object
  413. */
  414. public PDFPageLabels makePageLabels() {
  415. PDFPageLabels pageLabels = new PDFPageLabels();
  416. getDocument().assignObjectNumber(pageLabels);
  417. getDocument().addTrailerObject(pageLabels);
  418. return pageLabels;
  419. }
  420. /**
  421. * Make a the head object of the name dictionary (the /Dests object).
  422. *
  423. * @param destinationList a list of PDFDestination instances
  424. * @return the new PDFDests object
  425. */
  426. public PDFDests makeDests(List destinationList) {
  427. PDFDests dests;
  428. //TODO: Check why the below conditional branch is needed. Condition is always true...
  429. final boolean deep = true;
  430. //true for a "deep" structure (one node per entry), true for a "flat" structure
  431. if (deep) {
  432. dests = new PDFDests();
  433. PDFArray kids = new PDFArray(dests);
  434. Iterator iter = destinationList.iterator();
  435. while (iter.hasNext()) {
  436. PDFDestination dest = (PDFDestination)iter.next();
  437. PDFNameTreeNode node = new PDFNameTreeNode();
  438. getDocument().registerObject(node);
  439. node.setLowerLimit(dest.getIDRef());
  440. node.setUpperLimit(dest.getIDRef());
  441. node.setNames(new PDFArray(node));
  442. PDFArray names = node.getNames();
  443. names.add(dest);
  444. kids.add(node);
  445. }
  446. dests.setLowerLimit(((PDFNameTreeNode)kids.get(0)).getLowerLimit());
  447. dests.setUpperLimit(((PDFNameTreeNode)kids.get(kids.length() - 1)).getUpperLimit());
  448. dests.setKids(kids);
  449. } else {
  450. dests = new PDFDests(destinationList);
  451. }
  452. getDocument().registerObject(dests);
  453. return dests;
  454. }
  455. /**
  456. * Make a name tree node.
  457. *
  458. * @return the new name tree node
  459. */
  460. public PDFNameTreeNode makeNameTreeNode() {
  461. PDFNameTreeNode node = new PDFNameTreeNode();
  462. getDocument().registerObject(node);
  463. return node;
  464. }
  465. /* ========================= links ===================================== */
  466. // Some of the "yoffset-only" functions in this part are obsolete and can
  467. // possibly be removed or deprecated. Some are still called by PDFGraphics2D
  468. // (although that could be changed, they don't need the yOffset param anyway).
  469. /**
  470. * Create a PDF link to an existing PDFAction object
  471. *
  472. * @param rect the hotspot position in absolute coordinates
  473. * @param pdfAction the PDFAction that this link refers to
  474. * @return the new PDFLink object, or null if either rect or pdfAction is null
  475. */
  476. public PDFLink makeLink(Rectangle2D rect, PDFAction pdfAction) {
  477. if (rect == null || pdfAction == null) {
  478. return null;
  479. } else {
  480. PDFLink link = new PDFLink(rect);
  481. link.setAction(pdfAction);
  482. getDocument().registerObject(link);
  483. return link;
  484. // does findLink make sense? I mean, how often will it happen that several
  485. // links have the same target *and* the same hot rect? And findLink has to
  486. // walk and compare the entire link list everytime you call it...
  487. }
  488. }
  489. /**
  490. * Make an internal link.
  491. *
  492. * @param rect the hotspot position in absolute coordinates
  493. * @param page the target page reference value
  494. * @param dest the position destination
  495. * @return the new PDF link object
  496. */
  497. public PDFLink makeLink(Rectangle2D rect, String page, String dest) {
  498. PDFLink link = new PDFLink(rect);
  499. getDocument().registerObject(link);
  500. PDFGoTo gt = new PDFGoTo(page);
  501. gt.setDestination(dest);
  502. getDocument().registerObject(gt);
  503. PDFInternalLink internalLink = new PDFInternalLink(gt.referencePDF());
  504. link.setAction(internalLink);
  505. return link;
  506. }
  507. /**
  508. * Make a {@link PDFLink} object
  509. *
  510. * @param rect the clickable rectangle
  511. * @param destination the destination file
  512. * @param linkType the link type
  513. * @param yoffset the yoffset on the page for an internal link
  514. * @return the PDFLink object created
  515. */
  516. public PDFLink makeLink(Rectangle2D rect, String destination,
  517. int linkType, float yoffset) {
  518. //PDFLink linkObject;
  519. PDFLink link = new PDFLink(rect);
  520. if (linkType == PDFLink.EXTERNAL) {
  521. link.setAction(getExternalAction(destination, false));
  522. } else {
  523. // linkType is internal
  524. String goToReference = getGoToReference(destination, yoffset);
  525. PDFInternalLink internalLink = new PDFInternalLink(goToReference);
  526. link.setAction(internalLink);
  527. }
  528. PDFLink oldlink = getDocument().findLink(link);
  529. if (oldlink == null) {
  530. getDocument().registerObject(link);
  531. } else {
  532. link = oldlink;
  533. }
  534. return link;
  535. }
  536. private static final String EMBEDDED_FILE = "embedded-file:";
  537. /**
  538. * Create/find and return the appropriate external PDFAction according to the target
  539. *
  540. * @param target The external target. This may be a PDF file name
  541. * (optionally with internal page number or destination) or any type of URI.
  542. * @param newWindow boolean indicating whether the target should be
  543. * displayed in a new window
  544. * @return the PDFAction thus created or found
  545. */
  546. public PDFAction getExternalAction(String target, boolean newWindow) {
  547. int index;
  548. String targetLo = target.toLowerCase();
  549. if (target.startsWith(EMBEDDED_FILE)) {
  550. // File Attachments (Embedded Files)
  551. String filename = target.substring(EMBEDDED_FILE.length());
  552. return getActionForEmbeddedFile(filename, newWindow);
  553. } else if (targetLo.startsWith("http://")) {
  554. // HTTP URL?
  555. return new PDFUri(target);
  556. } else if (targetLo.startsWith("https://")) {
  557. // HTTPS URL?
  558. return new PDFUri(target);
  559. } else if (targetLo.startsWith("file://")) {
  560. // Non PDF files. Try to /Launch them.
  561. target = target.substring("file://".length());
  562. return getLaunchAction(target);
  563. } else if (targetLo.endsWith(".pdf")) {
  564. // Bare PDF file name?
  565. return getGoToPDFAction(target, null, -1, newWindow);
  566. } else if ((index = targetLo.indexOf(".pdf#page=")) > 0) {
  567. // PDF file + page?
  568. String filename = target.substring(0, index + 4);
  569. int page = Integer.parseInt(target.substring(index + 10));
  570. return getGoToPDFAction(filename, null, page, newWindow);
  571. } else if ((index = targetLo.indexOf(".pdf#dest=")) > 0) {
  572. // PDF file + destination?
  573. String filename = target.substring(0, index + 4);
  574. String dest = target.substring(index + 10);
  575. return getGoToPDFAction(filename, dest, -1, newWindow);
  576. } else {
  577. // None of the above? Default to URI:
  578. return new PDFUri(target);
  579. }
  580. }
  581. private PDFAction getActionForEmbeddedFile(String filename, boolean newWindow) {
  582. PDFNames names = getDocument().getRoot().getNames();
  583. if (names == null) {
  584. throw new IllegalStateException(
  585. "No Names dictionary present."
  586. + " Cannot create Launch Action for embedded file: " + filename);
  587. }
  588. PDFNameTreeNode embeddedFiles = names.getEmbeddedFiles();
  589. if (embeddedFiles == null) {
  590. throw new IllegalStateException(
  591. "No /EmbeddedFiles name tree present."
  592. + " Cannot create Launch Action for embedded file: " + filename);
  593. }
  594. //Find filespec reference for the embedded file
  595. filename = PDFText.toPDFString(filename, '_');
  596. PDFArray files = embeddedFiles.getNames();
  597. PDFReference embeddedFileRef = null;
  598. int i = 0;
  599. while (i < files.length()) {
  600. String name = (String)files.get(i);
  601. i++;
  602. PDFReference ref = (PDFReference)files.get(i);
  603. if (name.equals(filename)) {
  604. embeddedFileRef = ref;
  605. break;
  606. }
  607. i++;
  608. }
  609. if (embeddedFileRef == null) {
  610. throw new IllegalStateException(
  611. "No embedded file with name " + filename + " present.");
  612. }
  613. //Finally create the action
  614. //PDFLaunch action = new PDFLaunch(embeddedFileRef);
  615. //This works with Acrobat 8 but not with Acrobat 9
  616. //The following two options didn't seem to have any effect.
  617. //PDFGoToEmbedded action = new PDFGoToEmbedded(embeddedFileRef, 0, newWindow);
  618. //PDFGoToRemote action = new PDFGoToRemote(embeddedFileRef, 0, newWindow);
  619. //This finally seems to work:
  620. StringBuffer scriptBuffer = new StringBuffer();
  621. scriptBuffer.append("this.exportDataObject({cName:\"");
  622. scriptBuffer.append(filename);
  623. scriptBuffer.append("\", nLaunch:2});");
  624. PDFJavaScriptLaunchAction action = new PDFJavaScriptLaunchAction(scriptBuffer.toString());
  625. return action;
  626. }
  627. /**
  628. * Create or find a PDF GoTo with the given page reference string and Y offset,
  629. * and return its PDF object reference
  630. *
  631. * @param pdfPageRef the PDF page reference, e.g. "23 0 R"
  632. * @param yoffset the distance from the bottom of the page in points
  633. * @return the GoTo's object reference
  634. */
  635. public String getGoToReference(String pdfPageRef, float yoffset) {
  636. return getPDFGoTo(pdfPageRef, new Point2D.Float(0.0f, yoffset)).referencePDF();
  637. }
  638. /**
  639. * Finds and returns a PDFGoTo to the given page and position.
  640. * Creates the PDFGoTo if not found.
  641. *
  642. * @param pdfPageRef the PDF page reference
  643. * @param position the (X,Y) position in points
  644. *
  645. * @return the new or existing PDFGoTo object
  646. */
  647. public PDFGoTo getPDFGoTo(String pdfPageRef, Point2D position) {
  648. getDocument().getProfile().verifyActionAllowed();
  649. PDFGoTo gt = new PDFGoTo(pdfPageRef, position);
  650. PDFGoTo oldgt = getDocument().findGoTo(gt);
  651. if (oldgt == null) {
  652. getDocument().assignObjectNumber(gt);
  653. getDocument().addTrailerObject(gt);
  654. } else {
  655. gt = oldgt;
  656. }
  657. return gt;
  658. }
  659. /**
  660. * Create and return a goto pdf document action.
  661. * This creates a pdf files spec and pdf goto remote action.
  662. * It also checks available pdf objects so it will not create an
  663. * object if it already exists.
  664. *
  665. * @param file the pdf file name
  666. * @param dest the remote name destination, may be null
  667. * @param page the remote page number, -1 means not specified
  668. * @param newWindow boolean indicating whether the target should be
  669. * displayed in a new window
  670. * @return the pdf goto remote object
  671. */
  672. private PDFGoToRemote getGoToPDFAction(String file, String dest, int page, boolean newWindow) {
  673. getDocument().getProfile().verifyActionAllowed();
  674. PDFFileSpec fileSpec = new PDFFileSpec(file);
  675. PDFFileSpec oldspec = getDocument().findFileSpec(fileSpec);
  676. if (oldspec == null) {
  677. getDocument().registerObject(fileSpec);
  678. } else {
  679. fileSpec = oldspec;
  680. }
  681. PDFGoToRemote remote;
  682. if (dest == null && page == -1) {
  683. remote = new PDFGoToRemote(fileSpec, newWindow);
  684. } else if (dest != null) {
  685. remote = new PDFGoToRemote(fileSpec, dest, newWindow);
  686. } else {
  687. remote = new PDFGoToRemote(fileSpec, page, newWindow);
  688. }
  689. PDFGoToRemote oldremote = getDocument().findGoToRemote(remote);
  690. if (oldremote == null) {
  691. getDocument().registerObject(remote);
  692. } else {
  693. remote = oldremote;
  694. }
  695. return remote;
  696. }
  697. /**
  698. * Creates and returns a launch pdf document action using
  699. * <code>file</code> to create a file spcifiaciton for
  700. * the document/file to be opened with an external application.
  701. *
  702. * @param file the pdf file name
  703. * @return the pdf launch object
  704. */
  705. private PDFLaunch getLaunchAction(String file) {
  706. getDocument().getProfile().verifyActionAllowed();
  707. PDFFileSpec fileSpec = new PDFFileSpec(file);
  708. PDFFileSpec oldSpec = getDocument().findFileSpec(fileSpec);
  709. if (oldSpec == null) {
  710. getDocument().registerObject(fileSpec);
  711. } else {
  712. fileSpec = oldSpec;
  713. }
  714. PDFLaunch launch = new PDFLaunch(fileSpec);
  715. PDFLaunch oldLaunch = getDocument().findLaunch(launch);
  716. if (oldLaunch == null) {
  717. getDocument().registerObject(launch);
  718. } else {
  719. launch = oldLaunch;
  720. }
  721. return launch;
  722. }
  723. /**
  724. * Make an outline object and add it to the given parent
  725. *
  726. * @param parent the parent PDFOutline object (may be null)
  727. * @param label the title for the new outline object
  728. * @param actionRef the action reference string to be placed after the /A
  729. * @param showSubItems whether to initially display child outline items
  730. * @return the new PDF outline object
  731. */
  732. public PDFOutline makeOutline(PDFOutline parent, String label,
  733. String actionRef, boolean showSubItems) {
  734. PDFOutline pdfOutline = new PDFOutline(label, actionRef, showSubItems);
  735. if (parent != null) {
  736. parent.addOutline(pdfOutline);
  737. }
  738. getDocument().registerObject(pdfOutline);
  739. return pdfOutline;
  740. }
  741. /**
  742. * Make an outline object and add it to the given parent
  743. *
  744. * @param parent the parent PDFOutline object (may be null)
  745. * @param label the title for the new outline object
  746. * @param pdfAction the action that this outline item points to - must not be null!
  747. * @param showSubItems whether to initially display child outline items
  748. * @return the new PDFOutline object, or null if pdfAction is null
  749. */
  750. public PDFOutline makeOutline(PDFOutline parent, String label,
  751. PDFAction pdfAction, boolean showSubItems) {
  752. return pdfAction == null
  753. ? null
  754. : makeOutline(parent, label, pdfAction.getAction(), showSubItems);
  755. }
  756. // This one is obsolete now, at least it isn't called from anywhere inside FOP
  757. /**
  758. * Make an outline object and add it to the given outline
  759. *
  760. * @param parent parent PDFOutline object which may be null
  761. * @param label the title for the new outline object
  762. * @param destination the reference string for the action to go to
  763. * @param yoffset the yoffset on the destination page
  764. * @param showSubItems whether to initially display child outline items
  765. * @return the new PDF outline object
  766. */
  767. public PDFOutline makeOutline(PDFOutline parent, String label,
  768. String destination, float yoffset,
  769. boolean showSubItems) {
  770. String goToRef = getGoToReference(destination, yoffset);
  771. return makeOutline(parent, label, goToRef, showSubItems);
  772. }
  773. /* ========================= fonts ===================================== */
  774. /**
  775. * make a /Encoding object
  776. *
  777. * @param encodingName character encoding scheme name
  778. * @return the created /Encoding object
  779. */
  780. public PDFEncoding makeEncoding(String encodingName) {
  781. PDFEncoding encoding = new PDFEncoding(encodingName);
  782. getDocument().registerObject(encoding);
  783. return encoding;
  784. }
  785. /**
  786. * Make a Type1 /Font object.
  787. *
  788. * @param fontname internal name to use for this font (eg "F1")
  789. * @param basefont name of the base font (eg "Helvetica")
  790. * @param encoding character encoding scheme used by the font
  791. * @param metrics additional information about the font
  792. * @param descriptor additional information about the font
  793. * @return the created /Font object
  794. */
  795. public PDFFont makeFont(String fontname, String basefont,
  796. String encoding, FontMetrics metrics,
  797. FontDescriptor descriptor) {
  798. PDFFont preRegisteredfont = getDocument().findFont(fontname);
  799. if (preRegisteredfont != null) {
  800. return preRegisteredfont;
  801. }
  802. boolean forceToUnicode = true;
  803. if (descriptor == null) {
  804. //Usually Base 14 fonts
  805. PDFFont font = new PDFFont(fontname, FontType.TYPE1, basefont, encoding);
  806. getDocument().registerObject(font);
  807. if (forceToUnicode && !PDFEncoding.isPredefinedEncoding(encoding)) {
  808. SingleByteEncoding mapping;
  809. if (encoding != null) {
  810. mapping = CodePointMapping.getMapping(encoding);
  811. } else {
  812. //for Symbol and ZapfDingbats where encoding must be null in PDF
  813. Typeface tf = (Typeface)metrics;
  814. mapping = CodePointMapping.getMapping(tf.getEncodingName());
  815. }
  816. generateToUnicodeCmap(font, mapping);
  817. }
  818. return font;
  819. } else {
  820. FontType fonttype = metrics.getFontType();
  821. String fontPrefix = descriptor.isSubsetEmbedded() ? createSubsetFontPrefix() : "";
  822. String subsetFontName = fontPrefix + basefont;
  823. PDFFontDescriptor pdfdesc = makeFontDescriptor(descriptor, fontPrefix);
  824. PDFFont font = null;
  825. font = PDFFont.createFont(fontname, fonttype, subsetFontName, null);
  826. getDocument().registerObject(font);
  827. if (fonttype == FontType.TYPE0) {
  828. font.setEncoding(encoding);
  829. CIDFont cidMetrics;
  830. if (metrics instanceof LazyFont) {
  831. cidMetrics = (CIDFont)((LazyFont) metrics).getRealFont();
  832. } else {
  833. cidMetrics = (CIDFont)metrics;
  834. }
  835. PDFCIDSystemInfo sysInfo = new PDFCIDSystemInfo(cidMetrics.getRegistry(),
  836. cidMetrics.getOrdering(), cidMetrics.getSupplement());
  837. sysInfo.setDocument(document);
  838. PDFCIDFont cidFont = new PDFCIDFont(subsetFontName, cidMetrics.getCIDType(),
  839. cidMetrics.getDefaultWidth(), getFontWidths(cidMetrics), sysInfo,
  840. (PDFCIDFontDescriptor) pdfdesc);
  841. getDocument().registerObject(cidFont);
  842. PDFCMap cmap = new PDFToUnicodeCMap(cidMetrics.getCIDSet().getChars(), "fop-ucs-H",
  843. new PDFCIDSystemInfo("Adobe", "Identity", 0), false);
  844. getDocument().registerObject(cmap);
  845. ((PDFFontType0)font).setCMAP(cmap);
  846. ((PDFFontType0)font).setDescendantFonts(cidFont);
  847. } else {
  848. PDFFontNonBase14 nonBase14 = (PDFFontNonBase14)font;
  849. nonBase14.setDescriptor(pdfdesc);
  850. SingleByteFont singleByteFont;
  851. if (metrics instanceof LazyFont) {
  852. singleByteFont = (SingleByteFont)((LazyFont)metrics).getRealFont();
  853. } else {
  854. singleByteFont = (SingleByteFont)metrics;
  855. }
  856. int firstChar = 0;
  857. int lastChar = 0;
  858. boolean defaultChars = false;
  859. if (singleByteFont.getEmbeddingMode() == EmbeddingMode.SUBSET) {
  860. Map<Integer, Integer> usedGlyphs = singleByteFont.getUsedGlyphs();
  861. if (fonttype == FontType.TYPE1 && usedGlyphs.size() > 0) {
  862. SortedSet<Integer> keys = new TreeSet<Integer>(usedGlyphs.keySet());
  863. keys.remove(0);
  864. if (keys.size() > 0) {
  865. firstChar = keys.first();
  866. lastChar = keys.last();
  867. int[] newWidths = new int[(lastChar - firstChar) + 1];
  868. for (int i = firstChar; i < lastChar + 1; i++) {
  869. if (usedGlyphs.get(i) != null) {
  870. if (i - singleByteFont.getFirstChar() < metrics.getWidths().length) {
  871. newWidths[i - firstChar] = metrics.getWidths()[i
  872. - singleByteFont.getFirstChar()];
  873. } else {
  874. defaultChars = true;
  875. break;
  876. }
  877. } else {
  878. newWidths[i - firstChar] = 0;
  879. }
  880. }
  881. nonBase14.setWidthMetrics(firstChar,
  882. lastChar,
  883. new PDFArray(null, newWidths));
  884. }
  885. } else {
  886. defaultChars = true;
  887. }
  888. } else {
  889. defaultChars = true;
  890. }
  891. if (defaultChars) {
  892. firstChar = singleByteFont.getFirstChar();
  893. lastChar = singleByteFont.getLastChar();
  894. nonBase14.setWidthMetrics(firstChar,
  895. lastChar,
  896. new PDFArray(null, metrics.getWidths()));
  897. }
  898. //Handle encoding
  899. SingleByteEncoding mapping = singleByteFont.getEncoding();
  900. if (singleByteFont.isSymbolicFont()) {
  901. //no encoding, use the font's encoding
  902. if (forceToUnicode) {
  903. generateToUnicodeCmap(nonBase14, mapping);
  904. }
  905. } else if (PDFEncoding.isPredefinedEncoding(mapping.getName())) {
  906. font.setEncoding(mapping.getName());
  907. //No ToUnicode CMap necessary if PDF 1.4, chapter 5.9 (page 368) is to be
  908. //believed.
  909. } else {
  910. Object pdfEncoding = createPDFEncoding(mapping,
  911. singleByteFont.getFontName());
  912. if (pdfEncoding instanceof PDFEncoding) {
  913. font.setEncoding((PDFEncoding)pdfEncoding);
  914. } else {
  915. font.setEncoding((String)pdfEncoding);
  916. }
  917. if (forceToUnicode) {
  918. generateToUnicodeCmap(nonBase14, mapping);
  919. }
  920. }
  921. //Handle additional encodings (characters outside the primary encoding)
  922. if (singleByteFont.hasAdditionalEncodings()) {
  923. for (int i = 0, c = singleByteFont.getAdditionalEncodingCount(); i < c; i++) {
  924. SimpleSingleByteEncoding addEncoding
  925. = singleByteFont.getAdditionalEncoding(i);
  926. String name = fontname + "_" + (i + 1);
  927. Object pdfenc = createPDFEncoding(addEncoding,
  928. singleByteFont.getFontName());
  929. PDFFontNonBase14 addFont = (PDFFontNonBase14)PDFFont.createFont(
  930. name, fonttype,
  931. basefont, pdfenc);
  932. addFont.setDescriptor(pdfdesc);
  933. addFont.setWidthMetrics(
  934. addEncoding.getFirstChar(),
  935. addEncoding.getLastChar(),
  936. new PDFArray(null, singleByteFont.getAdditionalWidths(i)));
  937. getDocument().registerObject(addFont);
  938. getDocument().getResources().addFont(addFont);
  939. if (forceToUnicode) {
  940. generateToUnicodeCmap(addFont, addEncoding);
  941. }
  942. }
  943. }
  944. }
  945. return font;
  946. }
  947. }
  948. private void generateToUnicodeCmap(PDFFont font, SingleByteEncoding encoding) {
  949. PDFCMap cmap = new PDFToUnicodeCMap(encoding.getUnicodeCharMap(),
  950. "fop-ucs-H",
  951. new PDFCIDSystemInfo("Adobe", "Identity", 0), true);
  952. getDocument().registerObject(cmap);
  953. font.setToUnicode(cmap);
  954. }
  955. /**
  956. * Creates a PDFEncoding instance from a CodePointMapping instance.
  957. * @param encoding the code point mapping (encoding)
  958. * @param fontName ...
  959. * @return the PDF Encoding dictionary (or a String with the predefined encoding)
  960. */
  961. public Object createPDFEncoding(SingleByteEncoding encoding, String fontName) {
  962. return PDFEncoding.createPDFEncoding(encoding, fontName);
  963. }
  964. private PDFWArray getFontWidths(CIDFont cidFont) {
  965. // Create widths for reencoded chars
  966. PDFWArray warray = new PDFWArray();
  967. int[] widths = cidFont.getCIDSet().getWidths();
  968. warray.addEntry(0, widths);
  969. return warray;
  970. }
  971. private String createSubsetFontPrefix() {
  972. subsetFontCounter++;
  973. DecimalFormat counterFormat = new DecimalFormat("00000");
  974. String counterString = counterFormat.format(subsetFontCounter);
  975. // Subset prefix as described in chapter 5.5.3 of PDF 1.4
  976. StringBuffer sb = new StringBuffer("E");
  977. for (char c : counterString.toCharArray()) {
  978. // translate numbers to uppercase characters
  979. sb.append((char) (c + ('A' - '0')));
  980. }
  981. sb.append("+");
  982. return sb.toString();
  983. }
  984. /**
  985. * make a /FontDescriptor object
  986. *
  987. * @param desc the font descriptor
  988. * @param fontPrefix the String with which to prefix the font name
  989. * @return the new PDF font descriptor
  990. */
  991. private PDFFontDescriptor makeFontDescriptor(FontDescriptor desc, String fontPrefix) {
  992. PDFFontDescriptor descriptor = null;
  993. if (desc.getFontType() == FontType.TYPE0) {
  994. // CID Font
  995. descriptor = new PDFCIDFontDescriptor(fontPrefix + desc.getEmbedFontName(),
  996. desc.getFontBBox(),
  997. desc.getCapHeight(),
  998. desc.getFlags(),
  999. desc.getItalicAngle(),
  1000. desc.getStemV(), null);
  1001. } else {
  1002. // Create normal FontDescriptor
  1003. descriptor = new PDFFontDescriptor(fontPrefix + desc.getEmbedFontName(),
  1004. desc.getAscender(),
  1005. desc.getDescender(),
  1006. desc.getCapHeight(),
  1007. desc.getFlags(),
  1008. new PDFRectangle(desc.getFontBBox()),
  1009. desc.getItalicAngle(),
  1010. desc.getStemV());
  1011. }
  1012. getDocument().registerObject(descriptor);
  1013. // Check if the font is embeddable
  1014. if (desc.isEmbeddable()) {
  1015. AbstractPDFStream stream = makeFontFile(desc, fontPrefix);
  1016. if (stream != null) {
  1017. descriptor.setFontFile(desc.getFontType(), stream);
  1018. getDocument().registerObject(stream);
  1019. }
  1020. CustomFont font = getCustomFont(desc);
  1021. if (font instanceof CIDFont) {
  1022. CIDFont cidFont = (CIDFont)font;
  1023. buildCIDSet(descriptor, cidFont);
  1024. }
  1025. }
  1026. return descriptor;
  1027. }
  1028. private void buildCIDSet(PDFFontDescriptor descriptor, CIDFont cidFont) {
  1029. BitSet cidSet = cidFont.getCIDSet().getGlyphIndices();
  1030. PDFStream pdfStream = makeStream(null, true);
  1031. ByteArrayOutputStream baout = new ByteArrayOutputStream(cidSet.length() / 8 + 1);
  1032. int value = 0;
  1033. for (int i = 0, c = cidSet.length(); i < c; i++) {
  1034. int shift = i % 8;
  1035. boolean b = cidSet.get(i);
  1036. if (b) {
  1037. value |= 1 << 7 - shift;
  1038. }
  1039. if (shift == 7) {
  1040. baout.write(value);
  1041. value = 0;
  1042. }
  1043. }
  1044. baout.write(value);
  1045. try {
  1046. pdfStream.setData(baout.toByteArray());
  1047. descriptor.setCIDSet(pdfStream);
  1048. } catch (IOException ioe) {
  1049. log.error(
  1050. "Failed to write CIDSet [" + cidFont + "] "
  1051. + cidFont.getEmbedFontName(), ioe);
  1052. } finally {
  1053. IOUtils.closeQuietly(baout);
  1054. }
  1055. }
  1056. /**
  1057. * Embeds a font.
  1058. * @param desc FontDescriptor of the font.
  1059. * @return PDFStream The embedded font file
  1060. */
  1061. public AbstractPDFStream makeFontFile(FontDescriptor desc, String fontPrefix) {
  1062. if (desc.getFontType() == FontType.OTHER) {
  1063. throw new IllegalArgumentException("Trying to embed unsupported font type: "
  1064. + desc.getFontType());
  1065. }
  1066. CustomFont font = getCustomFont(desc);
  1067. InputStream in = null;
  1068. try {
  1069. in = font.getInputStream();
  1070. if (in == null) {
  1071. return null;
  1072. } else {
  1073. AbstractPDFStream embeddedFont = null;
  1074. if (desc.getFontType() == FontType.TYPE0) {
  1075. MultiByteFont mbfont = (MultiByteFont) font;
  1076. FontFileReader reader = new FontFileReader(in);
  1077. byte[] fontBytes;
  1078. String header = OFFontLoader.readHeader(reader);
  1079. boolean isCFF = mbfont.isOTFFile();
  1080. if (font.getEmbeddingMode() == EmbeddingMode.FULL) {
  1081. fontBytes = reader.getAllBytes();
  1082. if (isCFF) {
  1083. //Ensure version 1.6 for full OTF CFF embedding
  1084. document.setPDFVersion(Version.V1_6);
  1085. }
  1086. } else {
  1087. fontBytes = getFontSubsetBytes(reader, mbfont, header, fontPrefix, desc,
  1088. isCFF);
  1089. }
  1090. embeddedFont = getFontStream(font, fontBytes, isCFF);
  1091. } else if (desc.getFontType() == FontType.TYPE1) {
  1092. if (font.getEmbeddingMode() != EmbeddingMode.SUBSET) {
  1093. embeddedFont = fullyEmbedType1Font(in);
  1094. } else {
  1095. assert font instanceof SingleByteFont;
  1096. SingleByteFont sbfont = (SingleByteFont)font;
  1097. Type1SubsetFile pfbFile = new Type1SubsetFile();
  1098. byte[] subsetData = pfbFile.createSubset(in, sbfont, fontPrefix);
  1099. InputStream subsetStream = new ByteArrayInputStream(subsetData);
  1100. PFBParser parser = new PFBParser();
  1101. PFBData pfb = parser.parsePFB(subsetStream);
  1102. embeddedFont = new PDFT1Stream();
  1103. ((PDFT1Stream) embeddedFont).setData(pfb);
  1104. }
  1105. } else {
  1106. byte[] file = IOUtils.toByteArray(in);
  1107. embeddedFont = new PDFTTFStream(file.length);
  1108. ((PDFTTFStream) embeddedFont).setData(file, file.length);
  1109. }
  1110. /*
  1111. embeddedFont.getFilterList().addFilter("flate");
  1112. if (getDocument().isEncryptionActive()) {
  1113. getDocument().applyEncryption(embeddedFont);
  1114. } else {
  1115. embeddedFont.getFilterList().addFilter("ascii-85");
  1116. }*/
  1117. return embeddedFont;
  1118. }
  1119. } catch (IOException ioe) {
  1120. log.error("Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe);
  1121. return null;
  1122. } finally {
  1123. IOUtils.closeQuietly(in);
  1124. }
  1125. }
  1126. private AbstractPDFStream fullyEmbedType1Font(InputStream in) throws IOException {
  1127. PFBParser parser = new PFBParser();
  1128. PFBData pfb = parser.parsePFB(in);
  1129. AbstractPDFStream embeddedFont = new PDFT1Stream();
  1130. ((PDFT1Stream) embeddedFont).setData(pfb);
  1131. return embeddedFont;
  1132. }
  1133. private byte[] getFontSubsetBytes(FontFileReader reader, MultiByteFont mbfont, String header,
  1134. String fontPrefix, FontDescriptor desc, boolean isCFF) throws IOException {
  1135. if (isCFF) {
  1136. OTFSubSetFile otfFile = new OTFSubSetFile();
  1137. otfFile.readFont(reader, fontPrefix + desc.getEmbedFontName(), header, mbfont);
  1138. return otfFile.getFontSubset();
  1139. } else {
  1140. TTFSubSetFile otfFile = new TTFSubSetFile();
  1141. otfFile.readFont(reader, mbfont.getTTCName(), header, mbfont.getUsedGlyphs());
  1142. return otfFile.getFontSubset();
  1143. }
  1144. }
  1145. private AbstractPDFStream getFontStream(CustomFont font, byte[] fontBytes, boolean isCFF)
  1146. throws IOException {
  1147. AbstractPDFStream embeddedFont;
  1148. if (isCFF) {
  1149. embeddedFont = new PDFCFFStreamType0C(font.getEmbeddingMode() == EmbeddingMode.FULL);
  1150. ((PDFCFFStreamType0C) embeddedFont).setData(fontBytes, fontBytes.length);
  1151. } else {
  1152. embeddedFont = new PDFTTFStream(fontBytes.length);
  1153. ((PDFTTFStream) embeddedFont).setData(fontBytes, fontBytes.length);
  1154. }
  1155. return embeddedFont;
  1156. }
  1157. private CustomFont getCustomFont(FontDescriptor desc) {
  1158. Typeface tempFont;
  1159. if (desc instanceof LazyFont) {
  1160. tempFont = ((LazyFont)desc).getRealFont();
  1161. } else {
  1162. tempFont = (Typeface)desc;
  1163. }
  1164. if (!(tempFont instanceof CustomFont)) {
  1165. throw new IllegalArgumentException(
  1166. "FontDescriptor must be instance of CustomFont, but is a "
  1167. + desc.getClass().getName());
  1168. }
  1169. return (CustomFont)tempFont;
  1170. }
  1171. /* ========================= streams =================================== */
  1172. /**
  1173. * Make a stream object
  1174. *
  1175. * @param type the type of stream to be created
  1176. * @param add if true then the stream will be added immediately
  1177. * @return the stream object created
  1178. */
  1179. public PDFStream makeStream(String type, boolean add) {
  1180. // create a PDFStream with the next object number
  1181. // and add it to the list of objects
  1182. PDFStream obj = new PDFStream();
  1183. obj.setDocument(getDocument());
  1184. obj.getFilterList().addDefaultFilters(
  1185. getDocument().getFilterMap(),
  1186. type);
  1187. if (add) {
  1188. getDocument().registerObject(obj);
  1189. }
  1190. //getDocument().applyEncryption(obj);
  1191. return obj;
  1192. }
  1193. /**
  1194. * Create a PDFICCStream
  1195. * @see PDFImageXObject
  1196. * @see org.apache.fop.pdf.PDFDeviceColorSpace
  1197. * @return the new PDF ICC stream object
  1198. */
  1199. public PDFICCStream makePDFICCStream() {
  1200. PDFICCStream iccStream = new PDFICCStream();
  1201. getDocument().registerObject(iccStream);
  1202. //getDocument().applyEncryption(iccStream);
  1203. return iccStream;
  1204. }
  1205. /* ========================= misc. objects ============================= */
  1206. /**
  1207. * Makes a new ICCBased color space and registers it in the resource context.
  1208. * @param res the PDF resource context to add the shading, may be null
  1209. * @param explicitName the explicit name for the color space, may be null
  1210. * @param iccStream the ICC stream to associate with this color space
  1211. * @return the newly instantiated color space
  1212. */
  1213. public PDFICCBasedColorSpace makeICCBasedColorSpace(PDFResourceContext res,
  1214. String explicitName, PDFICCStream iccStream) {
  1215. PDFICCBasedColorSpace cs = new PDFICCBasedColorSpace(explicitName, iccStream);
  1216. getDocument().registerObject(cs);
  1217. if (res != null) {
  1218. res.getPDFResources().addColorSpace(cs);
  1219. } else {
  1220. getDocument().getResources().addColorSpace(cs);
  1221. }
  1222. return cs;
  1223. }
  1224. /**
  1225. * Create a new Separation color space.
  1226. * @param res the resource context (may be null)
  1227. * @param ncs the named color space to map to a separation color space
  1228. * @return the newly created Separation color space
  1229. */
  1230. public PDFSeparationColorSpace makeSeparationColorSpace(PDFResourceContext res,
  1231. NamedColorSpace ncs) {
  1232. String colorName = ncs.getColorName();
  1233. final Double zero = new Double(0d);
  1234. final Double one = new Double(1d);
  1235. List theDomain = Arrays.asList(new Double[] {zero, one});
  1236. List theRange = Arrays.asList(new Double[] {zero, one, zero, one, zero, one});
  1237. List theCZero = Arrays.asList(new Double[] {one, one, one});
  1238. List theCOne = new ArrayList();
  1239. float[] comps = ncs.getRGBColor().getColorComponents(null);
  1240. for (int i = 0, c = comps.length; i < c; i++) {
  1241. theCOne.add(new Double(comps[i]));
  1242. }
  1243. PDFFunction tintFunction = makeFunction(2, theDomain, theRange,
  1244. theCZero, theCOne, 1.0d);
  1245. PDFSeparationColorSpace cs = new PDFSeparationColorSpace(colorName, tintFunction);
  1246. getDocument().registerObject(cs);
  1247. if (res != null) {
  1248. res.getPDFResources().addColorSpace(cs);
  1249. } else {
  1250. getDocument().getResources().addColorSpace(cs);
  1251. }
  1252. return cs;
  1253. }
  1254. /**
  1255. * Make an Array object (ex. Widths array for a font).
  1256. *
  1257. * @param values the int array values
  1258. * @return the PDF Array with the int values
  1259. */
  1260. public PDFArray makeArray(int[] values) {
  1261. PDFArray array = new PDFArray(null, values);
  1262. getDocument().registerObject(array);
  1263. return array;
  1264. }
  1265. /**
  1266. * make an ExtGState for extra graphics options
  1267. * This tries to find a GState that will setup the correct values
  1268. * for the current context. If there is no suitable GState it will
  1269. * create a new one.
  1270. *
  1271. * @param settings the settings required by the caller
  1272. * @param current the current GState of the current PDF context
  1273. * @return a PDF GState, either an existing GState or a new one
  1274. */
  1275. public PDFGState makeGState(Map settings, PDFGState current) {
  1276. // try to locate a gstate that has all the settings
  1277. // or will inherit from the current gstate
  1278. // compare "DEFAULT + settings" with "current + each gstate"
  1279. PDFGState wanted = new PDFGState();
  1280. wanted.addValues(PDFGState.DEFAULT);
  1281. wanted.addValues(settings);
  1282. PDFGState existing = getDocument().findGState(wanted, current);
  1283. if (existing != null) {
  1284. return existing;
  1285. }
  1286. PDFGState gstate = new PDFGState();
  1287. gstate.addValues(settings);
  1288. getDocument().registerObject(gstate);
  1289. return gstate;
  1290. }
  1291. /**
  1292. * Make an annotation list object
  1293. *
  1294. * @return the annotation list object created
  1295. */
  1296. public PDFAnnotList makeAnnotList() {
  1297. PDFAnnotList obj = new PDFAnnotList();
  1298. getDocument().assignObjectNumber(obj);
  1299. return obj;
  1300. }
  1301. public PDFLayer makeLayer(String id) {
  1302. PDFLayer layer = new PDFLayer(id);
  1303. getDocument().registerObject(layer);
  1304. return layer;
  1305. }
  1306. public PDFSetOCGStateAction makeSetOCGStateAction(String id) {
  1307. PDFSetOCGStateAction action = new PDFSetOCGStateAction(id);
  1308. getDocument().registerObject(action);
  1309. return action;
  1310. }
  1311. public PDFTransitionAction makeTransitionAction(String id) {
  1312. PDFTransitionAction action = new PDFTransitionAction(id);
  1313. getDocument().registerObject(action);
  1314. return action;
  1315. }
  1316. public PDFNavigator makeNavigator(String id) {
  1317. PDFNavigator navigator = new PDFNavigator(id);
  1318. getDocument().registerObject(navigator);
  1319. return navigator;
  1320. }
  1321. }