Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

AbstractPDFStream.java 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.util.Set;
  22. import org.apache.commons.io.output.CountingOutputStream;
  23. import org.apache.fop.util.CloseBlockerOutputStream;
  24. /**
  25. * This is an abstract base class for PDF streams.
  26. */
  27. public abstract class AbstractPDFStream extends PDFObject {
  28. private final PDFDictionary dictionary;
  29. /** The filters that should be applied */
  30. private PDFFilterList filters;
  31. private boolean encodeOnTheFly;
  32. private PDFNumber refLength = new PDFNumber();
  33. protected AbstractPDFStream() {
  34. this(true);
  35. }
  36. protected AbstractPDFStream(PDFDictionary dictionary) {
  37. this(dictionary, true);
  38. }
  39. protected AbstractPDFStream(boolean encodeOnTheFly) {
  40. this(new PDFDictionary(), encodeOnTheFly);
  41. }
  42. protected AbstractPDFStream(PDFDictionary dictionary, boolean encodeOnTheFly) {
  43. this.dictionary = dictionary;
  44. dictionary.setParent(this);
  45. this.encodeOnTheFly = encodeOnTheFly;
  46. }
  47. protected final PDFDictionary getDictionary() {
  48. return dictionary;
  49. }
  50. public Object get(String key) {
  51. return dictionary.get(key);
  52. }
  53. /**
  54. * Puts the given object in the dictionary associated to this stream.
  55. *
  56. * @param key the key in the dictionary
  57. * @param value the value to store
  58. */
  59. public void put(String key, Object value) {
  60. dictionary.put(key, value);
  61. }
  62. /**
  63. * Sets up the default filters for this stream if they haven't been set
  64. * from outside.
  65. */
  66. protected void setupFilterList() {
  67. if (multipleFiltersAllowed() && !getFilterList().isInitialized()) {
  68. getFilterList().addDefaultFilters(
  69. getDocumentSafely().getFilterMap(),
  70. getDefaultFilterName());
  71. }
  72. prepareImplicitFilters();
  73. getDocument().applyEncryption(this);
  74. }
  75. /**
  76. * Returns the name of a suitable filter for this PDF object.
  77. *
  78. * @return the default filter
  79. * @see PDFFilterList
  80. */
  81. protected String getDefaultFilterName() {
  82. return PDFFilterList.DEFAULT_FILTER;
  83. }
  84. /**
  85. * Returns the associated filter list.
  86. * @return the filter list
  87. */
  88. public PDFFilterList getFilterList() {
  89. if (this.filters == null) {
  90. if (getDocument() == null) {
  91. this.filters = new PDFFilterList();
  92. } else {
  93. this.filters = new PDFFilterList(getDocument().isEncryptionActive());
  94. }
  95. boolean hasFilterEntries = (get("Filter") != null);
  96. if (hasFilterEntries) {
  97. this.filters.setDisableAllFilters(true);
  98. }
  99. }
  100. return this.filters;
  101. }
  102. /**
  103. * Returns a value that hints at the size of the encoded stream. This is
  104. * used to optimize buffer allocation so fewer buffer reallocations are
  105. * necessary.
  106. * @return an estimated size (0 if no hint can be given)
  107. * @throws IOException in case of an I/O problem
  108. */
  109. protected abstract int getSizeHint() throws IOException;
  110. /**
  111. * Sends the raw stream data to the target OutputStream.
  112. * @param out OutputStream to write to
  113. * @throws IOException In case of an I/O problem
  114. */
  115. protected abstract void outputRawStreamData(OutputStream out)
  116. throws IOException;
  117. /**
  118. * Output just the stream data enclosed by stream/endstream markers
  119. * @param encodedStream already encoded/filtered stream to write
  120. * @param out OutputStream to write to
  121. * @return int number of bytes written
  122. * @throws IOException in case of an I/O problem
  123. */
  124. protected int outputStreamData(StreamCache encodedStream, OutputStream out) throws IOException {
  125. int length = 0;
  126. byte[] p = encode("\nstream\n");
  127. out.write(p);
  128. length += p.length;
  129. encodedStream.outputContents(out);
  130. length += encodedStream.getSize();
  131. p = encode("\nendstream");
  132. out.write(p);
  133. length += p.length;
  134. return length;
  135. }
  136. /**
  137. * Encodes the raw data stream for output to a PDF file.
  138. * @return the encoded stream
  139. * @throws IOException in case of an I/O problem
  140. */
  141. protected StreamCache encodeStream() throws IOException {
  142. //Allocate a temporary buffer to find out the size of the encoded stream
  143. final StreamCache encodedStream = StreamCacheFactory.getInstance()
  144. .createStreamCache(getSizeHint());
  145. OutputStream filteredOutput
  146. = getFilterList().applyFilters(encodedStream.getOutputStream());
  147. outputRawStreamData(filteredOutput);
  148. filteredOutput.flush();
  149. filteredOutput.close();
  150. return encodedStream;
  151. }
  152. /**
  153. * Encodes and writes a stream directly to an OutputStream. The length of
  154. * the stream, in this case, is set on a PDFNumber object that has to be
  155. * prepared beforehand.
  156. * @param out OutputStream to write to
  157. * @param refLength PDFNumber object to receive the stream length
  158. * @return number of bytes written (header and trailer included)
  159. * @throws IOException in case of an I/O problem
  160. */
  161. protected int encodeAndWriteStream(OutputStream out, PDFNumber refLength)
  162. throws IOException {
  163. int bytesWritten = 0;
  164. //Stream header
  165. byte[] buf = encode("\nstream\n");
  166. out.write(buf);
  167. bytesWritten += buf.length;
  168. //Stream contents
  169. CloseBlockerOutputStream cbout = new CloseBlockerOutputStream(out);
  170. CountingOutputStream cout = new CountingOutputStream(cbout);
  171. OutputStream filteredOutput = getFilterList().applyFilters(cout);
  172. outputRawStreamData(filteredOutput);
  173. filteredOutput.close();
  174. refLength.setNumber(cout.getCount());
  175. bytesWritten += cout.getCount();
  176. //Stream trailer
  177. buf = encode("\nendstream");
  178. out.write(buf);
  179. bytesWritten += buf.length;
  180. return bytesWritten;
  181. }
  182. /**
  183. * Overload the base object method so we don't have to copy
  184. * byte arrays around so much
  185. * {@inheritDoc}
  186. */
  187. @Override
  188. public int output(OutputStream stream) throws IOException {
  189. setupFilterList();
  190. CountingOutputStream cout = new CountingOutputStream(stream);
  191. StringBuilder textBuffer = new StringBuilder(64);
  192. StreamCache encodedStream = null;
  193. final Object lengthEntry;
  194. if (encodeOnTheFly) {
  195. if (!refLength.hasObjectNumber()) {
  196. registerChildren();
  197. }
  198. lengthEntry = refLength;
  199. } else {
  200. encodedStream = encodeStream();
  201. lengthEntry = encodedStream.getSize();
  202. }
  203. populateStreamDict(lengthEntry);
  204. dictionary.writeDictionary(cout, textBuffer);
  205. //Send encoded stream to target OutputStream
  206. PDFDocument.flushTextBuffer(textBuffer, cout);
  207. if (encodedStream == null) {
  208. encodeAndWriteStream(cout, refLength);
  209. } else {
  210. outputStreamData(encodedStream, cout);
  211. encodedStream.clear(); //Encoded stream can now be discarded
  212. }
  213. PDFDocument.flushTextBuffer(textBuffer, cout);
  214. return cout.getCount();
  215. }
  216. @Override
  217. public void setDocument(PDFDocument doc) {
  218. dictionary.setDocument(doc);
  219. super.setDocument(doc);
  220. }
  221. /**
  222. * Populates the dictionary with all necessary entries for the stream.
  223. * Override this method if you need additional entries.
  224. * @param lengthEntry value for the /Length entry
  225. */
  226. protected void populateStreamDict(Object lengthEntry) {
  227. put("Length", lengthEntry);
  228. if (!getFilterList().isDisableAllFilters()) {
  229. getFilterList().putFilterDictEntries(dictionary);
  230. }
  231. }
  232. /**
  233. * Prepares implicit filters (such as the DCTFilter for JPEG images). You
  234. * must make sure that the appropriate filters are in the filter list at
  235. * the right places.
  236. */
  237. protected void prepareImplicitFilters() {
  238. //nop: No default implicit filters
  239. }
  240. /**
  241. * Whether multiple filters can be applied.
  242. * @return true if multiple filters allowed
  243. */
  244. protected boolean multipleFiltersAllowed() {
  245. return true;
  246. }
  247. @Override
  248. public void getChildren(Set<PDFObject> children) {
  249. dictionary.getChildren(children);
  250. if (encodeOnTheFly) {
  251. children.add(refLength);
  252. }
  253. }
  254. public void registerChildren() {
  255. if (encodeOnTheFly) {
  256. getDocument().registerObject(refLength);
  257. }
  258. }
  259. }