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.

PDFObject.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.Writer;
  23. import org.apache.commons.logging.Log;
  24. import org.apache.commons.logging.LogFactory;
  25. /**
  26. * generic PDF object.
  27. *
  28. * A PDF Document is essentially a collection of these objects. A PDF
  29. * Object has a number and a generation (although the generation will always
  30. * be 0 in new documents).
  31. */
  32. public abstract class PDFObject implements PDFWritable {
  33. /** logger for all PDFObjects (and descendants) */
  34. protected static final Log log = LogFactory.getLog(PDFObject.class.getName());
  35. /**
  36. * the object's number
  37. */
  38. private int objnum;
  39. /**
  40. * the object's generation (0 in new documents)
  41. */
  42. private int generation = 0;
  43. /**
  44. * the parent PDFDocument
  45. */
  46. private PDFDocument document;
  47. /** the parent PDFObject (may be null and may not always be set, needed for encryption) */
  48. private PDFObject parent;
  49. /**
  50. * Returns the object's number.
  51. * @return the PDF Object number
  52. */
  53. public int getObjectNumber() {
  54. if (this.objnum == 0) {
  55. throw new IllegalStateException("Object has no number assigned: " + this.toString());
  56. }
  57. return this.objnum;
  58. }
  59. /**
  60. * Default constructor.
  61. */
  62. public PDFObject() {
  63. //nop
  64. }
  65. /**
  66. * Constructor for direct objects.
  67. * @param parent the containing PDFObject instance
  68. */
  69. public PDFObject(PDFObject parent) {
  70. setParent(parent);
  71. }
  72. /**
  73. * Indicates whether this PDFObject has already been assigned an
  74. * object number.
  75. * @return True if it has an object number
  76. */
  77. public boolean hasObjectNumber() {
  78. return this.objnum > 0;
  79. }
  80. /**
  81. * Sets the object number
  82. * @param objnum the object number
  83. */
  84. public void setObjectNumber(int objnum) {
  85. this.objnum = objnum;
  86. PDFDocument doc = getDocument();
  87. setParent(null);
  88. setDocument(doc); //Restore reference to PDFDocument after setting parent to null
  89. if (log.isTraceEnabled()) {
  90. log.trace("Assigning " + this + " object number " + objnum);
  91. }
  92. }
  93. /**
  94. * Returns this object's generation.
  95. * @return the PDF Object generation
  96. */
  97. public int getGeneration() {
  98. return this.generation;
  99. }
  100. /**
  101. * Returns the parent PDFDocument if assigned.
  102. * @return the parent PDFDocument (May be null if the parent PDFDocument
  103. * has not been assigned)
  104. */
  105. public final PDFDocument getDocument() {
  106. if (this.document != null) {
  107. return this.document;
  108. } else if (getParent() != null) {
  109. return getParent().getDocument();
  110. } else {
  111. return null;
  112. }
  113. }
  114. /**
  115. * Returns the parent PDFDocument, but unlike <code>getDocument()</code>
  116. * it throws an informative Exception if the parent document is unavailable
  117. * instead of having a NullPointerException somewhere without a message.
  118. * @return the parent PDFDocument
  119. */
  120. public final PDFDocument getDocumentSafely() {
  121. final PDFDocument doc = getDocument();
  122. if (doc == null) {
  123. throw new IllegalStateException("Parent PDFDocument is unavailable on "
  124. + getClass().getName());
  125. }
  126. return doc;
  127. }
  128. /**
  129. * Sets the parent PDFDocument.
  130. * @param doc the PDFDocument.
  131. */
  132. public void setDocument(PDFDocument doc) {
  133. this.document = doc;
  134. }
  135. /**
  136. * Returns this objects's parent. The parent is null if it is a "direct object".
  137. * @return the parent or null if there's no parent (or it hasn't been set)
  138. */
  139. public PDFObject getParent() {
  140. return this.parent;
  141. }
  142. /**
  143. * Sets the direct parent object.
  144. * @param parent the direct parent
  145. */
  146. public void setParent(PDFObject parent) {
  147. this.parent = parent;
  148. }
  149. /**
  150. * Returns the PDF representation of the Object ID.
  151. * @return the Object ID
  152. */
  153. public String getObjectID() {
  154. return getObjectNumber() + " " + getGeneration() + " obj\n";
  155. }
  156. /**
  157. * Returns the PDF representation of a reference to this object.
  158. * @return the reference string
  159. */
  160. public String referencePDF() {
  161. if (!hasObjectNumber()) {
  162. throw new IllegalArgumentException(
  163. "Cannot reference this object. It doesn't have an object number");
  164. }
  165. String ref = getObjectNumber() + " " + getGeneration() + " R";
  166. return ref;
  167. }
  168. /**
  169. * Creates and returns a reference to this object.
  170. * @return the object reference
  171. */
  172. public PDFReference makeReference() {
  173. return new PDFReference(this);
  174. }
  175. /**
  176. * Write the PDF represention of this object
  177. *
  178. * @param stream the stream to write the PDF to
  179. * @throws IOException if there is an error writing to the stream
  180. * @return the number of bytes written
  181. */
  182. public int output(OutputStream stream) throws IOException {
  183. byte[] pdf = this.toPDF();
  184. stream.write(pdf);
  185. return pdf.length;
  186. }
  187. /** {@inheritDoc} */
  188. public void outputInline(OutputStream out, Writer writer) throws IOException {
  189. throw new UnsupportedOperationException("Don't use anymore: " + getClass().getName());
  190. }
  191. /** {@inheritDoc} */
  192. public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException {
  193. if (hasObjectNumber()) {
  194. textBuffer.append(referencePDF());
  195. } else {
  196. PDFDocument.flushTextBuffer(textBuffer, out);
  197. output(out);
  198. }
  199. }
  200. /**
  201. * Encodes the object as a byte array for output to a PDF file.
  202. *
  203. * @return PDF string
  204. */
  205. protected byte[] toPDF() {
  206. return encode(toPDFString());
  207. }
  208. /**
  209. * This method returns a String representation of the PDF object. The result
  210. * is normally converted/encoded to a byte array by toPDF(). Only use
  211. * this method to implement the serialization if the object can be fully
  212. * represented as text. If the PDF representation of the object contains
  213. * binary content use toPDF() or output(OutputStream) instead. This applies
  214. * to any object potentially containing a string object because string object
  215. * are encrypted and therefore need to be binary.
  216. * @return String the String representation
  217. */
  218. protected String toPDFString() {
  219. throw new UnsupportedOperationException("Not implemented. "
  220. + "Use output(OutputStream) instead.");
  221. }
  222. /**
  223. * Converts text to a byte array for writing to a PDF file.
  224. * @param text text to convert/encode
  225. * @return byte[] the resulting byte array
  226. */
  227. public static final byte[] encode(String text) {
  228. return PDFDocument.encode(text);
  229. }
  230. /**
  231. * Encodes a Text String (3.8.1 in PDF 1.4 specs)
  232. * @param text the text to encode
  233. * @return byte[] the encoded text
  234. */
  235. protected byte[] encodeText(String text) {
  236. if (getDocumentSafely().isEncryptionActive()) {
  237. final byte[] buf = PDFText.toUTF16(text);
  238. return PDFText.escapeByteArray(
  239. getDocument().getEncryption().encrypt(buf, this));
  240. } else {
  241. return encode(PDFText.escapeText(text, false));
  242. }
  243. }
  244. /**
  245. * Encodes a String (3.2.3 in PDF 1.4 specs)
  246. * @param string the string to encode
  247. * @return byte[] the encoded string
  248. */
  249. protected byte[] encodeString(String string) {
  250. return encodeText(string);
  251. }
  252. /**
  253. * Encodes binary data as hexadecimal string object.
  254. * @param data the binary data
  255. * @param out the OutputStream to write the encoded object to
  256. * @throws IOException if an I/O error occurs
  257. */
  258. protected void encodeBinaryToHexString(byte[] data, OutputStream out) throws IOException {
  259. out.write('<');
  260. if (getDocumentSafely().isEncryptionActive()) {
  261. data = getDocument().getEncryption().encrypt(data, this);
  262. }
  263. String hex = PDFText.toHex(data, false);
  264. byte[] encoded = hex.getBytes("US-ASCII");
  265. out.write(encoded);
  266. out.write('>');
  267. }
  268. /**
  269. * Formats an object for serialization to PDF.
  270. * <p>
  271. * IMPORTANT: If you need to write out binary output, call
  272. * {@link PDFDocument#flushTextBuffer(StringBuilder, OutputStream)} before writing any content
  273. * to the {@link OutputStream}!
  274. * @param obj the object
  275. * @param out the OutputStream to write to
  276. * @param textBuffer a text buffer for text output
  277. * @throws IOException If an I/O error occurs
  278. */
  279. protected void formatObject(Object obj, OutputStream out, StringBuilder textBuffer)
  280. throws IOException {
  281. if (obj == null) {
  282. textBuffer.append("null");
  283. } else if (obj instanceof PDFWritable) {
  284. ((PDFWritable)obj).outputInline(out, textBuffer);
  285. } else if (obj instanceof Number) {
  286. if (obj instanceof Double || obj instanceof Float) {
  287. textBuffer.append(PDFNumber.doubleOut(((Number)obj).doubleValue()));
  288. } else {
  289. textBuffer.append(obj.toString());
  290. }
  291. } else if (obj instanceof Boolean) {
  292. textBuffer.append(obj.toString());
  293. } else if (obj instanceof byte[]) {
  294. PDFDocument.flushTextBuffer(textBuffer, out);
  295. encodeBinaryToHexString((byte[])obj, out);
  296. } else {
  297. PDFDocument.flushTextBuffer(textBuffer, out);
  298. out.write(encodeText(obj.toString()));
  299. }
  300. }
  301. /**
  302. * Check if the other PDFObject has the same content as the current object.
  303. * <p>
  304. * Note: This function has a contract which is less binding than
  305. * {@link #equals(Object)}. Whereas equals would require all values to be
  306. * identical, this method is not required to check everything. In the case
  307. * of PDFObjects, this means that the overriding function does not have to
  308. * check for {@link #getObjectID()}.
  309. *
  310. * @param o
  311. * object to compare to.
  312. * @return true if the other object has the same content.
  313. */
  314. protected boolean contentEquals(PDFObject o) {
  315. return this.equals(o);
  316. }
  317. }