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

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