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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. * Get the {@link PDFInfo} object for this document.
  291. *
  292. * @return the {@link PDFInfo} object
  293. */
  294. public PDFInfo getInfo() {
  295. return this.info;
  296. }
  297. /**
  298. * Registers a {@link PDFObject} in this PDF document.
  299. * The object is assigned a new object number.
  300. *
  301. * @param obj {@link PDFObject} to add
  302. * @return the added {@link PDFObject} added (with its object number set)
  303. */
  304. public PDFObject registerObject(PDFObject obj) {
  305. assignObjectNumber(obj);
  306. addObject(obj);
  307. return obj;
  308. }
  309. /**
  310. * Assigns the {@link PDFObject} an object number,
  311. * and sets the parent of the {@link PDFObject} to this document.
  312. *
  313. * @param obj {@link PDFObject} to assign a number to
  314. */
  315. public void assignObjectNumber(PDFObject obj) {
  316. if (obj == null) {
  317. throw new NullPointerException("obj must not be null");
  318. }
  319. if (obj.hasObjectNumber()) {
  320. throw new IllegalStateException(
  321. "Error registering a PDFObject: "
  322. + "PDFObject already has an object number");
  323. }
  324. PDFDocument currentParent = obj.getDocument();
  325. if (currentParent != null && currentParent != this) {
  326. throw new IllegalStateException(
  327. "Error registering a PDFObject: "
  328. + "PDFObject already has a parent PDFDocument");
  329. }
  330. obj.setObjectNumber(++this.objectcount);
  331. if (currentParent == null) {
  332. obj.setDocument(this);
  333. }
  334. }
  335. /**
  336. * Adds a {@link PDFObject} to this document.
  337. * The object <em>MUST</em> have an object number assigned.
  338. *
  339. * @param obj {@link PDFObject} to add
  340. */
  341. public void addObject(PDFObject obj) {
  342. if (obj == null) {
  343. throw new NullPointerException("obj must not be null");
  344. }
  345. if (!obj.hasObjectNumber()) {
  346. throw new IllegalStateException(
  347. "Error adding a PDFObject: "
  348. + "PDFObject doesn't have an object number");
  349. }
  350. //Add object to list
  351. this.objects.add(obj);
  352. //Add object to special lists where necessary
  353. if (obj instanceof PDFFunction) {
  354. this.functions.add(obj);
  355. }
  356. if (obj instanceof PDFShading) {
  357. final String shadingName = "Sh" + (++this.shadingCount);
  358. ((PDFShading)obj).setName(shadingName);
  359. this.shadings.add(obj);
  360. }
  361. if (obj instanceof PDFPattern) {
  362. final String patternName = "Pa" + (++this.patternCount);
  363. ((PDFPattern)obj).setName(patternName);
  364. this.patterns.add(obj);
  365. }
  366. if (obj instanceof PDFFont) {
  367. final PDFFont font = (PDFFont)obj;
  368. this.fontMap.put(font.getName(), font);
  369. }
  370. if (obj instanceof PDFGState) {
  371. this.gstates.add(obj);
  372. }
  373. if (obj instanceof PDFPage) {
  374. this.pages.notifyKidRegistered((PDFPage)obj);
  375. }
  376. if (obj instanceof PDFLaunch) {
  377. this.launches.add(obj);
  378. }
  379. if (obj instanceof PDFLink) {
  380. this.links.add(obj);
  381. }
  382. if (obj instanceof PDFFileSpec) {
  383. this.filespecs.add(obj);
  384. }
  385. if (obj instanceof PDFGoToRemote) {
  386. this.gotoremotes.add(obj);
  387. }
  388. }
  389. /**
  390. * Add trailer object.
  391. * Adds an object to the list of trailer objects.
  392. *
  393. * @param obj the PDF object to add
  394. */
  395. public void addTrailerObject(PDFObject obj) {
  396. this.trailerObjects.add(obj);
  397. if (obj instanceof PDFGoTo) {
  398. this.gotos.add(obj);
  399. }
  400. }
  401. /**
  402. * Apply the encryption filter to a PDFStream if encryption is enabled.
  403. *
  404. * @param stream PDFStream to encrypt
  405. */
  406. public void applyEncryption(AbstractPDFStream stream) {
  407. if (isEncryptionActive()) {
  408. this.encryption.applyFilter(stream);
  409. }
  410. }
  411. /**
  412. * Enables PDF encryption.
  413. *
  414. * @param params The encryption parameters for the pdf file
  415. */
  416. public void setEncryption(PDFEncryptionParams params) {
  417. getProfile().verifyEncryptionAllowed();
  418. fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator();
  419. this.encryption = PDFEncryptionManager.newInstance(++this.objectcount, params, this);
  420. if (this.encryption != null) {
  421. PDFObject pdfObject = (PDFObject)this.encryption;
  422. addTrailerObject(pdfObject);
  423. } else {
  424. log.warn(
  425. "PDF encryption is unavailable. PDF will be "
  426. + "generated without encryption.");
  427. }
  428. }
  429. /**
  430. * Indicates whether encryption is active for this PDF or not.
  431. *
  432. * @return boolean True if encryption is active
  433. */
  434. public boolean isEncryptionActive() {
  435. return this.encryption != null;
  436. }
  437. /**
  438. * Returns the active Encryption object.
  439. *
  440. * @return the Encryption object
  441. */
  442. public PDFEncryption getEncryption() {
  443. return this.encryption;
  444. }
  445. private Object findPDFObject(List list, PDFObject compare) {
  446. for (Iterator iter = list.iterator(); iter.hasNext();) {
  447. PDFObject obj = (PDFObject) iter.next();
  448. if (compare.contentEquals(obj)) {
  449. return obj;
  450. }
  451. }
  452. return null;
  453. }
  454. /**
  455. * Looks through the registered functions to see if one that is equal to
  456. * a reference object exists
  457. *
  458. * @param compare reference object
  459. * @return the function if it was found, null otherwise
  460. */
  461. protected PDFFunction findFunction(PDFFunction compare) {
  462. return (PDFFunction)findPDFObject(this.functions, compare);
  463. }
  464. /**
  465. * Looks through the registered shadings to see if one that is equal to
  466. * a reference object exists
  467. *
  468. * @param compare reference object
  469. * @return the shading if it was found, null otherwise
  470. */
  471. protected PDFShading findShading(PDFShading compare) {
  472. return (PDFShading)findPDFObject(this.shadings, compare);
  473. }
  474. /**
  475. * Find a previous pattern.
  476. * The problem with this is for tiling patterns the pattern
  477. * data stream is stored and may use up memory, usually this
  478. * would only be a small amount of data.
  479. *
  480. * @param compare reference object
  481. * @return the shading if it was found, null otherwise
  482. */
  483. protected PDFPattern findPattern(PDFPattern compare) {
  484. return (PDFPattern)findPDFObject(this.patterns, compare);
  485. }
  486. /**
  487. * Finds a font.
  488. *
  489. * @param fontname name of the font
  490. * @return PDFFont the requested font, null if it wasn't found
  491. */
  492. protected PDFFont findFont(String fontname) {
  493. return (PDFFont)this.fontMap.get(fontname);
  494. }
  495. /**
  496. * Finds a named destination.
  497. *
  498. * @param compare reference object to use as search template
  499. * @return the link if found, null otherwise
  500. */
  501. protected PDFDestination findDestination(PDFDestination compare) {
  502. int index = getDestinationList().indexOf(compare);
  503. if (index >= 0) {
  504. return (PDFDestination)getDestinationList().get(index);
  505. } else {
  506. return null;
  507. }
  508. }
  509. /**
  510. * Finds a link.
  511. *
  512. * @param compare reference object to use as search template
  513. * @return the link if found, null otherwise
  514. */
  515. protected PDFLink findLink(PDFLink compare) {
  516. return (PDFLink)findPDFObject(this.links, compare);
  517. }
  518. /**
  519. * Finds a file spec.
  520. *
  521. * @param compare reference object to use as search template
  522. * @return the file spec if found, null otherwise
  523. */
  524. protected PDFFileSpec findFileSpec(PDFFileSpec compare) {
  525. return (PDFFileSpec)findPDFObject(this.filespecs, compare);
  526. }
  527. /**
  528. * Finds a goto remote.
  529. *
  530. * @param compare reference object to use as search template
  531. * @return the goto remote if found, null otherwise
  532. */
  533. protected PDFGoToRemote findGoToRemote(PDFGoToRemote compare) {
  534. return (PDFGoToRemote)findPDFObject(this.gotoremotes, compare);
  535. }
  536. /**
  537. * Finds a goto.
  538. *
  539. * @param compare reference object to use as search template
  540. * @return the goto if found, null otherwise
  541. */
  542. protected PDFGoTo findGoTo(PDFGoTo compare) {
  543. return (PDFGoTo)findPDFObject(this.gotos, compare);
  544. }
  545. /**
  546. * Finds a launch.
  547. *
  548. * @param compare reference object to use as search template
  549. * @return the launch if found, null otherwise
  550. */
  551. protected PDFLaunch findLaunch(PDFLaunch compare) {
  552. return (PDFLaunch) findPDFObject(this.launches, compare);
  553. }
  554. /**
  555. * Looks for an existing GState to use
  556. *
  557. * @param wanted requested features
  558. * @param current currently active features
  559. * @return the GState if found, null otherwise
  560. */
  561. protected PDFGState findGState(PDFGState wanted, PDFGState current) {
  562. PDFGState poss;
  563. Iterator iter = this.gstates.iterator();
  564. while (iter.hasNext()) {
  565. PDFGState avail = (PDFGState)iter.next();
  566. poss = new PDFGState();
  567. poss.addValues(current);
  568. poss.addValues(avail);
  569. if (poss.equals(wanted)) {
  570. return avail;
  571. }
  572. }
  573. return null;
  574. }
  575. /**
  576. * Returns the PDF color space object.
  577. *
  578. * @return the color space
  579. */
  580. public PDFDeviceColorSpace getPDFColorSpace() {
  581. return this.colorspace;
  582. }
  583. /**
  584. * Returns the color space.
  585. *
  586. * @return the color space
  587. */
  588. public int getColorSpace() {
  589. return getPDFColorSpace().getColorSpace();
  590. }
  591. /**
  592. * Set the color space.
  593. * This is used when creating gradients.
  594. *
  595. * @param theColorspace the new color space
  596. */
  597. public void setColorSpace(int theColorspace) {
  598. this.colorspace.setColorSpace(theColorspace);
  599. }
  600. /**
  601. * Returns the font map for this document.
  602. *
  603. * @return the map of fonts used in this document
  604. */
  605. public Map getFontMap() {
  606. return this.fontMap;
  607. }
  608. /**
  609. * Resolve a URI.
  610. *
  611. * @param uri the uri to resolve
  612. * @throws java.io.FileNotFoundException if the URI could not be resolved
  613. * @return the InputStream from the URI.
  614. */
  615. protected InputStream resolveURI(String uri)
  616. throws java.io.FileNotFoundException {
  617. try {
  618. /* TODO: Temporary hack to compile, improve later */
  619. return new java.net.URL(uri).openStream();
  620. } catch (Exception e) {
  621. throw new java.io.FileNotFoundException(
  622. "URI could not be resolved (" + e.getMessage() + "): " + uri);
  623. }
  624. }
  625. /**
  626. * Get an image from the image map.
  627. *
  628. * @param key the image key to look for
  629. * @return the image or PDFXObject for the key if found
  630. * @deprecated Use getXObject instead (so forms are treated in the same way)
  631. */
  632. @Deprecated
  633. public PDFImageXObject getImage(String key) {
  634. return (PDFImageXObject)this.xObjectsMap.get(key);
  635. }
  636. /**
  637. * Get an XObject from the image map.
  638. *
  639. * @param key the XObject key to look for
  640. * @return the PDFXObject for the key if found
  641. */
  642. public PDFXObject getXObject(String key) {
  643. return (PDFXObject)this.xObjectsMap.get(key);
  644. }
  645. /**
  646. * Gets the PDFDests object (which represents the /Dests entry).
  647. *
  648. * @return the PDFDests object (which represents the /Dests entry).
  649. */
  650. public PDFDests getDests() {
  651. return this.dests;
  652. }
  653. /**
  654. * Adds a destination to the document.
  655. * @param destination the destination object
  656. */
  657. public void addDestination(PDFDestination destination) {
  658. if (this.destinations == null) {
  659. this.destinations = new ArrayList();
  660. }
  661. this.destinations.add(destination);
  662. }
  663. /**
  664. * Gets the list of named destinations.
  665. *
  666. * @return the list of named destinations.
  667. */
  668. public List getDestinationList() {
  669. if (hasDestinations()) {
  670. return this.destinations;
  671. } else {
  672. return Collections.EMPTY_LIST;
  673. }
  674. }
  675. /**
  676. * Gets whether the document has named destinations.
  677. *
  678. * @return whether the document has named destinations.
  679. */
  680. public boolean hasDestinations() {
  681. return this.destinations != null && !this.destinations.isEmpty();
  682. }
  683. /**
  684. * Add an image to the PDF document.
  685. * This adds an image to the PDF objects.
  686. * If an image with the same key already exists it will return the
  687. * old {@link PDFXObject}.
  688. *
  689. * @param res the PDF resource context to add to, may be null
  690. * @param img the PDF image to add
  691. * @return the PDF XObject that references the PDF image data
  692. */
  693. public PDFImageXObject addImage(PDFResourceContext res, PDFImage img) {
  694. // check if already created
  695. String key = img.getKey();
  696. PDFImageXObject xObject = (PDFImageXObject)this.xObjectsMap.get(key);
  697. if (xObject != null) {
  698. if (res != null) {
  699. res.getPDFResources().addXObject(xObject);
  700. }
  701. return xObject;
  702. }
  703. // setup image
  704. img.setup(this);
  705. // create a new XObject
  706. xObject = new PDFImageXObject(++this.xObjectCount, img);
  707. registerObject(xObject);
  708. this.resources.addXObject(xObject);
  709. if (res != null) {
  710. res.getPDFResources().addXObject(xObject);
  711. }
  712. this.xObjectsMap.put(key, xObject);
  713. return xObject;
  714. }
  715. /**
  716. * Add a form XObject to the PDF document.
  717. * This adds a Form XObject to the PDF objects.
  718. * If a Form XObject with the same key already exists it will return the
  719. * old {@link PDFFormXObject}.
  720. *
  721. * @param res the PDF resource context to add to, may be null
  722. * @param cont the PDF Stream contents of the Form XObject
  723. * @param formres a reference to the PDF Resources for the Form XObject data
  724. * @param key the key for the object
  725. * @return the PDF Form XObject that references the PDF data
  726. */
  727. public PDFFormXObject addFormXObject(
  728. PDFResourceContext res,
  729. PDFStream cont,
  730. PDFReference formres,
  731. String key) {
  732. // check if already created
  733. PDFFormXObject xObject = (PDFFormXObject)xObjectsMap.get(key);
  734. if (xObject != null) {
  735. if (res != null) {
  736. res.getPDFResources().addXObject(xObject);
  737. }
  738. return xObject;
  739. }
  740. xObject = new PDFFormXObject(
  741. ++this.xObjectCount,
  742. cont,
  743. formres);
  744. registerObject(xObject);
  745. this.resources.addXObject(xObject);
  746. if (res != null) {
  747. res.getPDFResources().addXObject(xObject);
  748. }
  749. this.xObjectsMap.put(key, xObject);
  750. return xObject;
  751. }
  752. /**
  753. * Get the root Outlines object. This method does not write
  754. * the outline to the PDF document, it simply creates a
  755. * reference for later.
  756. *
  757. * @return the PDF Outline root object
  758. */
  759. public PDFOutline getOutlineRoot() {
  760. if (this.outlineRoot != null) {
  761. return this.outlineRoot;
  762. }
  763. this.outlineRoot = new PDFOutline(null, null, true);
  764. assignObjectNumber(this.outlineRoot);
  765. addTrailerObject(this.outlineRoot);
  766. this.root.setRootOutline(this.outlineRoot);
  767. return this.outlineRoot;
  768. }
  769. /**
  770. * Get the /Resources object for the document
  771. *
  772. * @return the /Resources object
  773. */
  774. public PDFResources getResources() {
  775. return this.resources;
  776. }
  777. /**
  778. * Ensure there is room in the locations xref for the number of
  779. * objects that have been created.
  780. * @param objidx the object's index
  781. * @param position the position
  782. */
  783. private void setLocation(int objidx, long position) {
  784. while (this.location.size() <= objidx) {
  785. this.location.add(LOCATION_PLACEHOLDER);
  786. }
  787. this.location.set(objidx, position);
  788. }
  789. /**
  790. * Writes out the entire document
  791. *
  792. * @param stream the OutputStream to output the document to
  793. * @throws IOException if there is an exception writing to the output stream
  794. */
  795. public void output(OutputStream stream) throws IOException {
  796. //Write out objects until the list is empty. This approach (used with a
  797. //LinkedList) allows for output() methods to create and register objects
  798. //on the fly even during serialization.
  799. while (this.objects.size() > 0) {
  800. /* Retrieve first */
  801. PDFObject object = (PDFObject)this.objects.remove(0);
  802. /*
  803. * add the position of this object to the list of object
  804. * locations
  805. */
  806. setLocation(object.getObjectNumber() - 1, this.position);
  807. /*
  808. * output the object and increment the character position
  809. * by the object's length
  810. */
  811. this.position += object.output(stream);
  812. }
  813. //Clear all objects written to the file
  814. //this.objects.clear();
  815. }
  816. /**
  817. * Write the PDF header.
  818. *
  819. * This method must be called prior to formatting
  820. * and outputting AreaTrees.
  821. *
  822. * @param stream the OutputStream to write the header to
  823. * @throws IOException if there is an exception writing to the output stream
  824. */
  825. public void outputHeader(OutputStream stream) throws IOException {
  826. this.position = 0;
  827. getProfile().verifyPDFVersion();
  828. byte[] pdf = encode("%PDF-" + getPDFVersionString() + "\n");
  829. stream.write(pdf);
  830. this.position += pdf.length;
  831. // output a binary comment as recommended by the PDF spec (3.4.1)
  832. byte[] bin = {
  833. (byte)'%',
  834. (byte)0xAA,
  835. (byte)0xAB,
  836. (byte)0xAC,
  837. (byte)0xAD,
  838. (byte)'\n' };
  839. stream.write(bin);
  840. this.position += bin.length;
  841. }
  842. /**
  843. * Write the trailer
  844. *
  845. * @param stream the OutputStream to write the trailer to
  846. * @throws IOException if there is an exception writing to the output stream
  847. */
  848. public void outputTrailer(OutputStream stream) throws IOException {
  849. if (hasDestinations()) {
  850. Collections.sort(this.destinations, new DestinationComparator());
  851. this.dests = getFactory().makeDests(this.destinations);
  852. if (this.root.getNames() == null) {
  853. this.root.setNames(getFactory().makeNames());
  854. }
  855. this.root.getNames().setDests(dests);
  856. }
  857. output(stream);
  858. for (int count = 0; count < this.trailerObjects.size(); count++) {
  859. PDFObject o = (PDFObject)this.trailerObjects.get(count);
  860. setLocation(o.getObjectNumber() - 1, this.position);
  861. this.position += o.output(stream);
  862. }
  863. /* output the xref table and increment the character position
  864. by the table's length */
  865. this.position += outputXref(stream);
  866. /* construct the trailer */
  867. StringBuffer pdf = new StringBuffer(128);
  868. pdf.append("trailer\n<<\n/Size ")
  869. .append(this.objectcount + 1)
  870. .append("\n/Root ")
  871. .append(this.root.referencePDF())
  872. .append("\n/Info ")
  873. .append(this.info.referencePDF())
  874. .append('\n');
  875. if (this.isEncryptionActive()) {
  876. pdf.append(this.encryption.getTrailerEntry());
  877. } else {
  878. byte[] fileID = getFileIDGenerator().getOriginalFileID();
  879. String fileIDAsString = PDFText.toHex(fileID);
  880. pdf.append("/ID [" + fileIDAsString + " " + fileIDAsString + "]");
  881. }
  882. pdf.append("\n>>\nstartxref\n")
  883. .append(this.xref)
  884. .append("\n%%EOF\n");
  885. /* write the trailer */
  886. stream.write(encode(pdf.toString()));
  887. }
  888. /**
  889. * Write the xref table
  890. *
  891. * @param stream the OutputStream to write the xref table to
  892. * @return the number of characters written
  893. * @throws IOException in case of an error writing the result to
  894. * the parameter stream
  895. */
  896. private int outputXref(OutputStream stream) throws IOException {
  897. /* remember position of xref table */
  898. this.xref = this.position;
  899. /* construct initial part of xref */
  900. StringBuffer pdf = new StringBuffer(128);
  901. pdf.append("xref\n0 ");
  902. pdf.append(this.objectcount + 1);
  903. pdf.append("\n0000000000 65535 f \n");
  904. String s, loc;
  905. for (int count = 0; count < this.location.size(); count++) {
  906. final String padding = "0000000000";
  907. s = this.location.get(count).toString();
  908. if (s.length() > 10) {
  909. throw new IOException("PDF file too large. PDF cannot grow beyond approx. 9.3GB.");
  910. }
  911. /* contruct xref entry for object */
  912. loc = padding.substring(s.length()) + s;
  913. /* append to xref table */
  914. pdf = pdf.append(loc).append(" 00000 n \n");
  915. }
  916. /* write the xref table and return the character length */
  917. byte[] pdfBytes = encode(pdf.toString());
  918. stream.write(pdfBytes);
  919. return pdfBytes.length;
  920. }
  921. long getCurrentFileSize() {
  922. return position;
  923. }
  924. FileIDGenerator getFileIDGenerator() {
  925. if (fileIDGenerator == null) {
  926. try {
  927. fileIDGenerator = FileIDGenerator.getDigestFileIDGenerator(this);
  928. } catch (NoSuchAlgorithmException e) {
  929. fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator();
  930. }
  931. }
  932. return fileIDGenerator;
  933. }
  934. }