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.

PDFDocument.java 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.io.UnsupportedEncodingException;
  24. import java.io.Writer;
  25. import java.security.MessageDigest;
  26. import java.security.NoSuchAlgorithmException;
  27. import java.text.DateFormat;
  28. import java.text.SimpleDateFormat;
  29. import java.util.ArrayList;
  30. import java.util.Collections;
  31. import java.util.Date;
  32. import java.util.HashMap;
  33. import java.util.Iterator;
  34. import java.util.LinkedList;
  35. import java.util.List;
  36. import java.util.Map;
  37. import org.apache.commons.logging.Log;
  38. import org.apache.commons.logging.LogFactory;
  39. /* image support modified from work of BoBoGi */
  40. /* font support based on work by Takayuki Takeuchi */
  41. /**
  42. * Class representing a PDF document.
  43. *
  44. * The document is built up by calling various methods and then finally
  45. * output to given filehandle using output method.
  46. *
  47. * A PDF document consists of a series of numbered objects preceded by a
  48. * header and followed by an xref table and trailer. The xref table
  49. * allows for quick access to objects by listing their character
  50. * positions within the document. For this reason the PDF document must
  51. * keep track of the character position of each object. The document
  52. * also keeps direct track of the /Root, /Info and /Resources objects.
  53. *
  54. * Modified by Mark Lillywhite, mark-fop@inomial.com. The changes
  55. * involve: ability to output pages one-at-a-time in a streaming
  56. * fashion (rather than storing them all for output at the end);
  57. * ability to write the /Pages object after writing the rest
  58. * of the document; ability to write to a stream and flush
  59. * the object list; enhanced trailer output; cleanups.
  60. *
  61. */
  62. public class PDFDocument {
  63. private static final Integer LOCATION_PLACEHOLDER = new Integer(0);
  64. /** Integer constant to represent PDF 1.3 */
  65. public static final int PDF_VERSION_1_3 = 3;
  66. /** Integer constant to represent PDF 1.4 */
  67. public static final int PDF_VERSION_1_4 = 4;
  68. /** the encoding to use when converting strings to PDF commands */
  69. public static final String ENCODING = "ISO-8859-1";
  70. /** the counter for object numbering */
  71. protected int objectcount = 0;
  72. /** the logger instance */
  73. private Log log = LogFactory.getLog("org.apache.fop.pdf");
  74. /** the current character position */
  75. private int position = 0;
  76. /** character position of xref table */
  77. private int xref;
  78. /** the character position of each object */
  79. private List location = new ArrayList();
  80. /** List of objects to write in the trailer */
  81. private List trailerObjects = new ArrayList();
  82. /** the objects themselves */
  83. private List objects = new LinkedList();
  84. /** Indicates what PDF version is active */
  85. private int pdfVersion = PDF_VERSION_1_4;
  86. /** Indicates which PDF profiles are active (PDF/A, PDF/X etc.) */
  87. private PDFProfile pdfProfile = new PDFProfile(this);
  88. /** the /Root object */
  89. private PDFRoot root;
  90. /** The root outline object */
  91. private PDFOutline outlineRoot = null;
  92. /** The /Pages object (mark-fop@inomial.com) */
  93. private PDFPages pages;
  94. /** the /Info object */
  95. private PDFInfo info;
  96. /** the /Resources object */
  97. private PDFResources resources;
  98. /** the document's encryption, if it exists */
  99. private PDFEncryption encryption;
  100. /** the colorspace (0=RGB, 1=CMYK) */
  101. private PDFDeviceColorSpace colorspace =
  102. new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB);
  103. /** the counter for Pattern name numbering (e.g. 'Pattern1') */
  104. private int patternCount = 0;
  105. /** the counter for Shading name numbering */
  106. private int shadingCount = 0;
  107. /** the counter for XObject numbering */
  108. private int xObjectCount = 0;
  109. /** the {@link PDFXObject}s map */
  110. /* TODO: Should be modified (works only for image subtype) */
  111. private Map xObjectsMap = new HashMap();
  112. /** The {@link PDFFont} map */
  113. private Map fontMap = new HashMap();
  114. /** The {@link PDFFilter} map */
  115. private Map filterMap = new HashMap();
  116. /** List of {@link PDFGState}s. */
  117. private List gstates = new ArrayList();
  118. /** List of {@link PDFFunction}s. */
  119. private List functions = new ArrayList();
  120. /** List of {@link PDFShading}s. */
  121. private List shadings = new ArrayList();
  122. /** List of {@link PDFPattern}s. */
  123. private List patterns = new ArrayList();
  124. /** List of {@link PDFLink}s. */
  125. private List links = new ArrayList();
  126. /** List of {@link PDFDestination}s. */
  127. private List destinations;
  128. /** List of {@link PDFFileSpec}s. */
  129. private List filespecs = new ArrayList();
  130. /** List of {@link PDFGoToRemote}s. */
  131. private List gotoremotes = new ArrayList();
  132. /** List of {@link PDFGoTo}s. */
  133. private List gotos = new ArrayList();
  134. /** List of {@link PDFLaunch}es. */
  135. private List launches = new ArrayList();
  136. /**
  137. * The PDFDests object for the name dictionary.
  138. * Note: This object is not a list.
  139. */
  140. private PDFDests dests;
  141. private PDFFactory factory;
  142. private boolean encodingOnTheFly = true;
  143. /**
  144. * Creates an empty PDF document.
  145. *
  146. * The constructor creates a /Root and /Pages object to
  147. * track the document but does not write these objects until
  148. * the trailer is written. Note that the object ID of the
  149. * pages object is determined now, and the xref table is
  150. * updated later. This allows Pages to refer to their
  151. * Parent before we write it out.
  152. *
  153. * @param prod the name of the producer of this pdf document
  154. */
  155. public PDFDocument(String prod) {
  156. this.factory = new PDFFactory(this);
  157. /* create the /Root, /Info and /Resources objects */
  158. this.pages = getFactory().makePages();
  159. // Create the Root object
  160. this.root = getFactory().makeRoot(this.pages);
  161. // Create the Resources object
  162. this.resources = getFactory().makeResources();
  163. // Make the /Info record
  164. this.info = getFactory().makeInfo(prod);
  165. }
  166. /**
  167. * @return the integer representing the active PDF version
  168. * (one of PDFDocument.PDF_VERSION_*)
  169. */
  170. public int getPDFVersion() {
  171. return this.pdfVersion;
  172. }
  173. /** @return the String representing the active PDF version */
  174. public String getPDFVersionString() {
  175. switch (getPDFVersion()) {
  176. case PDF_VERSION_1_3:
  177. return "1.3";
  178. case PDF_VERSION_1_4:
  179. return "1.4";
  180. default:
  181. throw new IllegalStateException("Unsupported PDF version selected");
  182. }
  183. }
  184. /** @return the PDF profile currently active. */
  185. public PDFProfile getProfile() {
  186. return this.pdfProfile;
  187. }
  188. /**
  189. * Returns the factory for PDF objects.
  190. *
  191. * @return the {@link PDFFactory} object
  192. */
  193. public PDFFactory getFactory() {
  194. return this.factory;
  195. }
  196. /**
  197. * Indicates whether stream encoding on-the-fly is enabled. If enabled
  198. * stream can be serialized without the need for a buffer to merely
  199. * calculate the stream length.
  200. *
  201. * @return <code>true</code> if on-the-fly encoding is enabled
  202. */
  203. public boolean isEncodingOnTheFly() {
  204. return this.encodingOnTheFly;
  205. }
  206. /**
  207. * Converts text to a byte array for writing to a PDF file.
  208. *
  209. * @param text text to convert/encode
  210. * @return the resulting <code>byte</code> array
  211. */
  212. public static byte[] encode(String text) {
  213. try {
  214. return text.getBytes(ENCODING);
  215. } catch (UnsupportedEncodingException uee) {
  216. return text.getBytes();
  217. }
  218. }
  219. /**
  220. * Creates and returns a Writer object wrapping the given OutputStream. The Writer is
  221. * buffered to reduce the number of calls to the encoding converter so don't forget
  222. * to <code>flush()</code> the Writer after use or before writing directly to the
  223. * underlying OutputStream.
  224. *
  225. * @param out the OutputStream to write to
  226. * @return the requested Writer
  227. */
  228. public static Writer getWriterFor(OutputStream out) {
  229. try {
  230. return new java.io.BufferedWriter(new java.io.OutputStreamWriter(out, ENCODING));
  231. } catch (UnsupportedEncodingException uee) {
  232. throw new Error("JVM doesn't support " + ENCODING + " encoding!");
  233. }
  234. }
  235. /**
  236. * Sets the producer of the document.
  237. *
  238. * @param producer string indicating application producing the PDF
  239. */
  240. public void setProducer(String producer) {
  241. this.info.setProducer(producer);
  242. }
  243. /**
  244. * Sets the creation date of the document.
  245. *
  246. * @param date Date to be stored as creation date in the PDF.
  247. */
  248. public void setCreationDate(Date date) {
  249. this.info.setCreationDate(date);
  250. }
  251. /**
  252. * Sets the creator of the document.
  253. *
  254. * @param creator string indicating application creating the document
  255. */
  256. public void setCreator(String creator) {
  257. this.info.setCreator(creator);
  258. }
  259. /**
  260. * Sets the filter map to use for filters in this document.
  261. *
  262. * @param map the map of filter lists for each stream type
  263. */
  264. public void setFilterMap(Map map) {
  265. this.filterMap = map;
  266. }
  267. /**
  268. * Returns the {@link PDFFilter}s map used for filters in this document.
  269. *
  270. * @return the map of filters being used
  271. */
  272. public Map getFilterMap() {
  273. return this.filterMap;
  274. }
  275. /**
  276. * Returns the {@link PDFPages} object associated with the root object.
  277. *
  278. * @return the {@link PDFPages} object
  279. */
  280. public PDFPages getPages() {
  281. return this.pages;
  282. }
  283. /**
  284. * Get the {@link PDFRoot} object for this document.
  285. *
  286. * @return the {@link PDFRoot} object
  287. */
  288. public PDFRoot getRoot() {
  289. return this.root;
  290. }
  291. /**
  292. * Makes sure a Lang entry has been set on the document catalog, setting it
  293. * to a default value if necessary. When accessibility is enabled the
  294. * language must be specified for any text element in the document.
  295. */
  296. public void enforceLanguageOnRoot() {
  297. if (root.getLanguage() == null) {
  298. String fallbackLanguage;
  299. if (getProfile().getPDFAMode().isPDFA1LevelA()) {
  300. //According to Annex B of ISO-19005-1:2005(E), section B.2
  301. fallbackLanguage = "x-unknown";
  302. } else {
  303. //No language has been set on the first page-sequence, so fall back to "en".
  304. fallbackLanguage = "en";
  305. }
  306. root.setLanguage(fallbackLanguage);
  307. }
  308. }
  309. /**
  310. * Get the {@link PDFInfo} object for this document.
  311. *
  312. * @return the {@link PDFInfo} object
  313. */
  314. public PDFInfo getInfo() {
  315. return this.info;
  316. }
  317. /**
  318. * Registers a {@link PDFObject} in this PDF document.
  319. * The object is assigned a new object number.
  320. *
  321. * @param obj {@link PDFObject} to add
  322. * @return the added {@link PDFObject} added (with its object number set)
  323. */
  324. public PDFObject registerObject(PDFObject obj) {
  325. assignObjectNumber(obj);
  326. addObject(obj);
  327. return obj;
  328. }
  329. /**
  330. * Assigns the {@link PDFObject} an object number,
  331. * and sets the parent of the {@link PDFObject} to this document.
  332. *
  333. * @param obj {@link PDFObject} to assign a number to
  334. */
  335. public void assignObjectNumber(PDFObject obj) {
  336. if (obj == null) {
  337. throw new NullPointerException("obj must not be null");
  338. }
  339. if (obj.hasObjectNumber()) {
  340. throw new IllegalStateException(
  341. "Error registering a PDFObject: "
  342. + "PDFObject already has an object number");
  343. }
  344. PDFDocument currentParent = obj.getDocument();
  345. if (currentParent != null && currentParent != this) {
  346. throw new IllegalStateException(
  347. "Error registering a PDFObject: "
  348. + "PDFObject already has a parent PDFDocument");
  349. }
  350. obj.setObjectNumber(++this.objectcount);
  351. if (currentParent == null) {
  352. obj.setDocument(this);
  353. }
  354. }
  355. /**
  356. * Adds a {@link PDFObject} to this document.
  357. * The object <em>MUST</em> have an object number assigned.
  358. *
  359. * @param obj {@link PDFObject} to add
  360. */
  361. public void addObject(PDFObject obj) {
  362. if (obj == null) {
  363. throw new NullPointerException("obj must not be null");
  364. }
  365. if (!obj.hasObjectNumber()) {
  366. throw new IllegalStateException(
  367. "Error adding a PDFObject: "
  368. + "PDFObject doesn't have an object number");
  369. }
  370. //Add object to list
  371. this.objects.add(obj);
  372. //Add object to special lists where necessary
  373. if (obj instanceof PDFFunction) {
  374. this.functions.add(obj);
  375. }
  376. if (obj instanceof PDFShading) {
  377. final String shadingName = "Sh" + (++this.shadingCount);
  378. ((PDFShading)obj).setName(shadingName);
  379. this.shadings.add(obj);
  380. }
  381. if (obj instanceof PDFPattern) {
  382. final String patternName = "Pa" + (++this.patternCount);
  383. ((PDFPattern)obj).setName(patternName);
  384. this.patterns.add(obj);
  385. }
  386. if (obj instanceof PDFFont) {
  387. final PDFFont font = (PDFFont)obj;
  388. this.fontMap.put(font.getName(), font);
  389. }
  390. if (obj instanceof PDFGState) {
  391. this.gstates.add(obj);
  392. }
  393. if (obj instanceof PDFPage) {
  394. this.pages.notifyKidRegistered((PDFPage)obj);
  395. }
  396. if (obj instanceof PDFLaunch) {
  397. this.launches.add(obj);
  398. }
  399. if (obj instanceof PDFLink) {
  400. this.links.add(obj);
  401. }
  402. if (obj instanceof PDFFileSpec) {
  403. this.filespecs.add(obj);
  404. }
  405. if (obj instanceof PDFGoToRemote) {
  406. this.gotoremotes.add(obj);
  407. }
  408. }
  409. /**
  410. * Add trailer object.
  411. * Adds an object to the list of trailer objects.
  412. *
  413. * @param obj the PDF object to add
  414. */
  415. public void addTrailerObject(PDFObject obj) {
  416. this.trailerObjects.add(obj);
  417. if (obj instanceof PDFGoTo) {
  418. this.gotos.add(obj);
  419. }
  420. }
  421. /**
  422. * Apply the encryption filter to a PDFStream if encryption is enabled.
  423. *
  424. * @param stream PDFStream to encrypt
  425. */
  426. public void applyEncryption(AbstractPDFStream stream) {
  427. if (isEncryptionActive()) {
  428. this.encryption.applyFilter(stream);
  429. }
  430. }
  431. /**
  432. * Enables PDF encryption.
  433. *
  434. * @param params The encryption parameters for the pdf file
  435. */
  436. public void setEncryption(PDFEncryptionParams params) {
  437. getProfile().verifyEncryptionAllowed();
  438. this.encryption = PDFEncryptionManager.newInstance(++this.objectcount, params);
  439. if (this.encryption != null) {
  440. PDFObject pdfObject = (PDFObject)this.encryption;
  441. pdfObject.setDocument(this);
  442. addTrailerObject(pdfObject);
  443. } else {
  444. log.warn(
  445. "PDF encryption is unavailable. PDF will be "
  446. + "generated without encryption.");
  447. }
  448. }
  449. /**
  450. * Indicates whether encryption is active for this PDF or not.
  451. *
  452. * @return boolean True if encryption is active
  453. */
  454. public boolean isEncryptionActive() {
  455. return this.encryption != null;
  456. }
  457. /**
  458. * Returns the active Encryption object.
  459. *
  460. * @return the Encryption object
  461. */
  462. public PDFEncryption getEncryption() {
  463. return this.encryption;
  464. }
  465. private Object findPDFObject(List list, PDFObject compare) {
  466. for (Iterator iter = list.iterator(); iter.hasNext();) {
  467. PDFObject obj = (PDFObject) iter.next();
  468. if (compare.contentEquals(obj)) {
  469. return obj;
  470. }
  471. }
  472. return null;
  473. }
  474. /**
  475. * Looks through the registered functions to see if one that is equal to
  476. * a reference object exists
  477. *
  478. * @param compare reference object
  479. * @return the function if it was found, null otherwise
  480. */
  481. protected PDFFunction findFunction(PDFFunction compare) {
  482. return (PDFFunction)findPDFObject(this.functions, compare);
  483. }
  484. /**
  485. * Looks through the registered shadings to see if one that is equal to
  486. * a reference object exists
  487. *
  488. * @param compare reference object
  489. * @return the shading if it was found, null otherwise
  490. */
  491. protected PDFShading findShading(PDFShading compare) {
  492. return (PDFShading)findPDFObject(this.shadings, compare);
  493. }
  494. /**
  495. * Find a previous pattern.
  496. * The problem with this is for tiling patterns the pattern
  497. * data stream is stored and may use up memory, usually this
  498. * would only be a small amount of data.
  499. *
  500. * @param compare reference object
  501. * @return the shading if it was found, null otherwise
  502. */
  503. protected PDFPattern findPattern(PDFPattern compare) {
  504. return (PDFPattern)findPDFObject(this.patterns, compare);
  505. }
  506. /**
  507. * Finds a font.
  508. *
  509. * @param fontname name of the font
  510. * @return PDFFont the requested font, null if it wasn't found
  511. */
  512. protected PDFFont findFont(String fontname) {
  513. return (PDFFont)this.fontMap.get(fontname);
  514. }
  515. /**
  516. * Finds a named destination.
  517. *
  518. * @param compare reference object to use as search template
  519. * @return the link if found, null otherwise
  520. */
  521. protected PDFDestination findDestination(PDFDestination compare) {
  522. int index = getDestinationList().indexOf(compare);
  523. if (index >= 0) {
  524. return (PDFDestination)getDestinationList().get(index);
  525. } else {
  526. return null;
  527. }
  528. }
  529. /**
  530. * Finds a link.
  531. *
  532. * @param compare reference object to use as search template
  533. * @return the link if found, null otherwise
  534. */
  535. protected PDFLink findLink(PDFLink compare) {
  536. return (PDFLink)findPDFObject(this.links, compare);
  537. }
  538. /**
  539. * Finds a file spec.
  540. *
  541. * @param compare reference object to use as search template
  542. * @return the file spec if found, null otherwise
  543. */
  544. protected PDFFileSpec findFileSpec(PDFFileSpec compare) {
  545. return (PDFFileSpec)findPDFObject(this.filespecs, compare);
  546. }
  547. /**
  548. * Finds a goto remote.
  549. *
  550. * @param compare reference object to use as search template
  551. * @return the goto remote if found, null otherwise
  552. */
  553. protected PDFGoToRemote findGoToRemote(PDFGoToRemote compare) {
  554. return (PDFGoToRemote)findPDFObject(this.gotoremotes, compare);
  555. }
  556. /**
  557. * Finds a goto.
  558. *
  559. * @param compare reference object to use as search template
  560. * @return the goto if found, null otherwise
  561. */
  562. protected PDFGoTo findGoTo(PDFGoTo compare) {
  563. return (PDFGoTo)findPDFObject(this.gotos, compare);
  564. }
  565. /**
  566. * Finds a launch.
  567. *
  568. * @param compare reference object to use as search template
  569. * @return the launch if found, null otherwise
  570. */
  571. protected PDFLaunch findLaunch(PDFLaunch compare) {
  572. return (PDFLaunch) findPDFObject(this.launches, compare);
  573. }
  574. /**
  575. * Looks for an existing GState to use
  576. *
  577. * @param wanted requested features
  578. * @param current currently active features
  579. * @return the GState if found, null otherwise
  580. */
  581. protected PDFGState findGState(PDFGState wanted, PDFGState current) {
  582. PDFGState poss;
  583. Iterator iter = this.gstates.iterator();
  584. while (iter.hasNext()) {
  585. PDFGState avail = (PDFGState)iter.next();
  586. poss = new PDFGState();
  587. poss.addValues(current);
  588. poss.addValues(avail);
  589. if (poss.equals(wanted)) {
  590. return avail;
  591. }
  592. }
  593. return null;
  594. }
  595. /**
  596. * Returns the PDF color space object.
  597. *
  598. * @return the color space
  599. */
  600. public PDFDeviceColorSpace getPDFColorSpace() {
  601. return this.colorspace;
  602. }
  603. /**
  604. * Returns the color space.
  605. *
  606. * @return the color space
  607. */
  608. public int getColorSpace() {
  609. return getPDFColorSpace().getColorSpace();
  610. }
  611. /**
  612. * Set the color space.
  613. * This is used when creating gradients.
  614. *
  615. * @param theColorspace the new color space
  616. */
  617. public void setColorSpace(int theColorspace) {
  618. this.colorspace.setColorSpace(theColorspace);
  619. }
  620. /**
  621. * Returns the font map for this document.
  622. *
  623. * @return the map of fonts used in this document
  624. */
  625. public Map getFontMap() {
  626. return this.fontMap;
  627. }
  628. /**
  629. * Resolve a URI.
  630. *
  631. * @param uri the uri to resolve
  632. * @throws java.io.FileNotFoundException if the URI could not be resolved
  633. * @return the InputStream from the URI.
  634. */
  635. protected InputStream resolveURI(String uri)
  636. throws java.io.FileNotFoundException {
  637. try {
  638. /* TODO: Temporary hack to compile, improve later */
  639. return new java.net.URL(uri).openStream();
  640. } catch (Exception e) {
  641. throw new java.io.FileNotFoundException(
  642. "URI could not be resolved (" + e.getMessage() + "): " + uri);
  643. }
  644. }
  645. /**
  646. * Get an image from the image map.
  647. *
  648. * @param key the image key to look for
  649. * @return the image or PDFXObject for the key if found
  650. * @deprecated Use getXObject instead (so forms are treated in the same way)
  651. */
  652. public PDFImageXObject getImage(String key) {
  653. return (PDFImageXObject)this.xObjectsMap.get(key);
  654. }
  655. /**
  656. * Get an XObject from the image map.
  657. *
  658. * @param key the XObject key to look for
  659. * @return the PDFXObject for the key if found
  660. */
  661. public PDFXObject getXObject(String key) {
  662. return (PDFXObject)this.xObjectsMap.get(key);
  663. }
  664. /**
  665. * Gets the PDFDests object (which represents the /Dests entry).
  666. *
  667. * @return the PDFDests object (which represents the /Dests entry).
  668. */
  669. public PDFDests getDests() {
  670. return this.dests;
  671. }
  672. /**
  673. * Adds a destination to the document.
  674. * @param destination the destination object
  675. */
  676. public void addDestination(PDFDestination destination) {
  677. if (this.destinations == null) {
  678. this.destinations = new ArrayList();
  679. }
  680. this.destinations.add(destination);
  681. }
  682. /**
  683. * Gets the list of named destinations.
  684. *
  685. * @return the list of named destinations.
  686. */
  687. public List getDestinationList() {
  688. if (hasDestinations()) {
  689. return this.destinations;
  690. } else {
  691. return Collections.EMPTY_LIST;
  692. }
  693. }
  694. /**
  695. * Gets whether the document has named destinations.
  696. *
  697. * @return whether the document has named destinations.
  698. */
  699. public boolean hasDestinations() {
  700. return this.destinations != null && !this.destinations.isEmpty();
  701. }
  702. /**
  703. * Add an image to the PDF document.
  704. * This adds an image to the PDF objects.
  705. * If an image with the same key already exists it will return the
  706. * old {@link PDFXObject}.
  707. *
  708. * @param res the PDF resource context to add to, may be null
  709. * @param img the PDF image to add
  710. * @return the PDF XObject that references the PDF image data
  711. */
  712. public PDFImageXObject addImage(PDFResourceContext res, PDFImage img) {
  713. // check if already created
  714. String key = img.getKey();
  715. PDFImageXObject xObject = (PDFImageXObject)this.xObjectsMap.get(key);
  716. if (xObject != null) {
  717. if (res != null) {
  718. res.getPDFResources().addXObject(xObject);
  719. }
  720. return xObject;
  721. }
  722. // setup image
  723. img.setup(this);
  724. // create a new XObject
  725. xObject = new PDFImageXObject(++this.xObjectCount, img);
  726. registerObject(xObject);
  727. this.resources.addXObject(xObject);
  728. if (res != null) {
  729. res.getPDFResources().addXObject(xObject);
  730. }
  731. this.xObjectsMap.put(key, xObject);
  732. return xObject;
  733. }
  734. /**
  735. * Add a form XObject to the PDF document.
  736. * This adds a Form XObject to the PDF objects.
  737. * If a Form XObject with the same key already exists it will return the
  738. * old {@link PDFFormXObject}.
  739. *
  740. * @param res the PDF resource context to add to, may be null
  741. * @param cont the PDF Stream contents of the Form XObject
  742. * @param formres a reference to the PDF Resources for the Form XObject data
  743. * @param key the key for the object
  744. * @return the PDF Form XObject that references the PDF data
  745. */
  746. public PDFFormXObject addFormXObject(
  747. PDFResourceContext res,
  748. PDFStream cont,
  749. PDFReference formres,
  750. String key) {
  751. // check if already created
  752. PDFFormXObject xObject = (PDFFormXObject)xObjectsMap.get(key);
  753. if (xObject != null) {
  754. if (res != null) {
  755. res.getPDFResources().addXObject(xObject);
  756. }
  757. return xObject;
  758. }
  759. xObject = new PDFFormXObject(
  760. ++this.xObjectCount,
  761. cont,
  762. formres);
  763. registerObject(xObject);
  764. this.resources.addXObject(xObject);
  765. if (res != null) {
  766. res.getPDFResources().addXObject(xObject);
  767. }
  768. this.xObjectsMap.put(key, xObject);
  769. return xObject;
  770. }
  771. /**
  772. * Get the root Outlines object. This method does not write
  773. * the outline to the PDF document, it simply creates a
  774. * reference for later.
  775. *
  776. * @return the PDF Outline root object
  777. */
  778. public PDFOutline getOutlineRoot() {
  779. if (this.outlineRoot != null) {
  780. return this.outlineRoot;
  781. }
  782. this.outlineRoot = new PDFOutline(null, null, true);
  783. assignObjectNumber(this.outlineRoot);
  784. addTrailerObject(this.outlineRoot);
  785. this.root.setRootOutline(this.outlineRoot);
  786. return this.outlineRoot;
  787. }
  788. /**
  789. * Get the /Resources object for the document
  790. *
  791. * @return the /Resources object
  792. */
  793. public PDFResources getResources() {
  794. return this.resources;
  795. }
  796. /**
  797. * Ensure there is room in the locations xref for the number of
  798. * objects that have been created.
  799. * @param objidx the object's index
  800. * @param position the position
  801. */
  802. private void setLocation(int objidx, int position) {
  803. while (this.location.size() <= objidx) {
  804. this.location.add(LOCATION_PLACEHOLDER);
  805. }
  806. this.location.set(objidx, new Integer(position));
  807. }
  808. /**
  809. * Writes out the entire document
  810. *
  811. * @param stream the OutputStream to output the document to
  812. * @throws IOException if there is an exception writing to the output stream
  813. */
  814. public void output(OutputStream stream) throws IOException {
  815. //Write out objects until the list is empty. This approach (used with a
  816. //LinkedList) allows for output() methods to create and register objects
  817. //on the fly even during serialization.
  818. while (this.objects.size() > 0) {
  819. /* Retrieve first */
  820. PDFObject object = (PDFObject)this.objects.remove(0);
  821. /*
  822. * add the position of this object to the list of object
  823. * locations
  824. */
  825. setLocation(object.getObjectNumber() - 1, this.position);
  826. /*
  827. * output the object and increment the character position
  828. * by the object's length
  829. */
  830. this.position += object.output(stream);
  831. }
  832. //Clear all objects written to the file
  833. //this.objects.clear();
  834. }
  835. /**
  836. * Write the PDF header.
  837. *
  838. * This method must be called prior to formatting
  839. * and outputting AreaTrees.
  840. *
  841. * @param stream the OutputStream to write the header to
  842. * @throws IOException if there is an exception writing to the output stream
  843. */
  844. public void outputHeader(OutputStream stream) throws IOException {
  845. this.position = 0;
  846. getProfile().verifyPDFVersion();
  847. byte[] pdf = encode("%PDF-" + getPDFVersionString() + "\n");
  848. stream.write(pdf);
  849. this.position += pdf.length;
  850. // output a binary comment as recommended by the PDF spec (3.4.1)
  851. byte[] bin = {
  852. (byte)'%',
  853. (byte)0xAA,
  854. (byte)0xAB,
  855. (byte)0xAC,
  856. (byte)0xAD,
  857. (byte)'\n' };
  858. stream.write(bin);
  859. this.position += bin.length;
  860. }
  861. /** @return the "ID" entry for the file trailer */
  862. protected String getIDEntry() {
  863. try {
  864. MessageDigest digest = MessageDigest.getInstance("MD5");
  865. DateFormat df = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS");
  866. digest.update(encode(df.format(new Date())));
  867. //Ignoring the filename here for simplicity even though it's recommended by the PDF spec
  868. digest.update(encode(String.valueOf(this.position)));
  869. digest.update(getInfo().toPDF());
  870. byte[] res = digest.digest();
  871. String s = PDFText.toHex(res);
  872. return "/ID [" + s + " " + s + "]";
  873. } catch (NoSuchAlgorithmException e) {
  874. if (getProfile().isIDEntryRequired()) {
  875. throw new UnsupportedOperationException("MD5 not available: " + e.getMessage());
  876. } else {
  877. return ""; //Entry is optional if PDF/A or PDF/X are not active
  878. }
  879. }
  880. }
  881. /**
  882. * Write the trailer
  883. *
  884. * @param stream the OutputStream to write the trailer to
  885. * @throws IOException if there is an exception writing to the output stream
  886. */
  887. public void outputTrailer(OutputStream stream) throws IOException {
  888. if (hasDestinations()) {
  889. Collections.sort(this.destinations, new DestinationComparator());
  890. this.dests = getFactory().makeDests(this.destinations);
  891. if (this.root.getNames() == null) {
  892. this.root.setNames(getFactory().makeNames());
  893. }
  894. this.root.getNames().setDests(dests);
  895. }
  896. output(stream);
  897. for (int count = 0; count < this.trailerObjects.size(); count++) {
  898. PDFObject o = (PDFObject)this.trailerObjects.get(count);
  899. this.location.set(
  900. o.getObjectNumber() - 1,
  901. new Integer(this.position));
  902. this.position += o.output(stream);
  903. }
  904. /* output the xref table and increment the character position
  905. by the table's length */
  906. this.position += outputXref(stream);
  907. /* construct the trailer */
  908. StringBuffer pdf = new StringBuffer(128);
  909. pdf.append("trailer\n<<\n/Size ")
  910. .append(this.objectcount + 1)
  911. .append("\n/Root ")
  912. .append(this.root.referencePDF())
  913. .append("\n/Info ")
  914. .append(this.info.referencePDF())
  915. .append('\n');
  916. if (this.isEncryptionActive()) {
  917. pdf.append(this.encryption.getTrailerEntry());
  918. } else {
  919. pdf.append(this.getIDEntry());
  920. }
  921. pdf.append("\n>>\nstartxref\n")
  922. .append(this.xref)
  923. .append("\n%%EOF\n");
  924. /* write the trailer */
  925. stream.write(encode(pdf.toString()));
  926. }
  927. /**
  928. * Write the xref table
  929. *
  930. * @param stream the OutputStream to write the xref table to
  931. * @return the number of characters written
  932. * @throws IOException in case of an error writing the result to
  933. * the parameter stream
  934. */
  935. private int outputXref(OutputStream stream) throws IOException {
  936. /* remember position of xref table */
  937. this.xref = this.position;
  938. /* construct initial part of xref */
  939. StringBuffer pdf = new StringBuffer(128);
  940. pdf.append("xref\n0 ");
  941. pdf.append(this.objectcount + 1);
  942. pdf.append("\n0000000000 65535 f \n");
  943. String s, loc;
  944. for (int count = 0; count < this.location.size(); count++) {
  945. final String padding = "0000000000";
  946. s = this.location.get(count).toString();
  947. /* contruct xref entry for object */
  948. loc = padding.substring(s.length()) + s;
  949. /* append to xref table */
  950. pdf = pdf.append(loc).append(" 00000 n \n");
  951. }
  952. /* write the xref table and return the character length */
  953. byte[] pdfBytes = encode(pdf.toString());
  954. stream.write(pdfBytes);
  955. return pdfBytes.length;
  956. }
  957. }