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