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

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