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

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