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

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