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

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