aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/pdf/PDFTextUtil.java
blob: bb8816995f181e771781e279c8ea51fa27692a6c (plain)
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
 * 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.awt.geom.AffineTransform;

/**
 * Utility class for generating PDF text objects. It needs to be subclassed to add writing
 * functionality (see {@link #write(String)}).
 */
public abstract class PDFTextUtil {

    /** The number of decimal places. */
    private static final int DEC = 8;

    /** PDF text rendering mode: Fill text */
    public static final int TR_FILL = 0;
    /** PDF text rendering mode: Stroke text */
    public static final int TR_STROKE = 1;
    /** PDF text rendering mode: Fill, then stroke text */
    public static final int TR_FILL_STROKE = 2;
    /** PDF text rendering mode: Neither fill nor stroke text (invisible) */
    public static final int TR_INVISIBLE = 3;
    /** PDF text rendering mode: Fill text and add to path for clipping */
    public static final int TR_FILL_CLIP = 4;
    /** PDF text rendering mode: Stroke text and add to path for clipping */
    public static final int TR_STROKE_CLIP = 5;
    /** PDF text rendering mode: Fill, then stroke text and add to path for clipping */
    public static final int TR_FILL_STROKE_CLIP = 6;
    /** PDF text rendering mode: Add text to path for clipping */
    public static final int TR_CLIP = 7;

    private boolean inTextObject = false;
    private boolean artifactMode = false;
    private String startText;
    private String endText;
    private boolean useMultiByte;
    private StringBuffer bufTJ;
    private int textRenderingMode = TR_FILL;

    private String currentFontName;
    private double currentFontSize;

    /**
     * Main constructor.
     */
    public PDFTextUtil() {
        //nop
    }

    /**
     * Writes PDF code.
     * @param code the PDF code to write
     */
    protected abstract void write(String code);

    private void writeAffineTransform(AffineTransform at, StringBuffer sb) {
        double[] lt = new double[6];
        at.getMatrix(lt);
        sb.append(PDFNumber.doubleOut(lt[0], DEC)).append(" ");
        sb.append(PDFNumber.doubleOut(lt[1], DEC)).append(" ");
        sb.append(PDFNumber.doubleOut(lt[2], DEC)).append(" ");
        sb.append(PDFNumber.doubleOut(lt[3], DEC)).append(" ");
        sb.append(PDFNumber.doubleOut(lt[4], DEC)).append(" ");
        sb.append(PDFNumber.doubleOut(lt[5], DEC));
    }

    private void writeChar(char ch, StringBuffer sb) {
        if (!useMultiByte) {
            if (ch < 32 || ch > 127) {
                sb.append("\\").append(Integer.toOctalString((int)ch));
            } else {
                switch (ch) {
                case '(':
                case ')':
                case '\\':
                    sb.append("\\");
                    break;
                default:
                }
                sb.append(ch);
            }
        } else {
            sb.append(PDFText.toUnicodeHex(ch));
        }
    }

    private void checkInTextObject() {
        if (!inTextObject) {
            throw new IllegalStateException("Not in text object");
        }
    }

    /**
     * Indicates whether we are in a text object or not.
     * @return true if we are in a text object
     */
    public boolean isInTextObject() {
        return inTextObject;
    }

    /**
     * Indicates whether we are in a text object and if that text object represents
     * an artifact.
     * @return true if in artifact-mode text object
     */
    public boolean inArtifactMode() {
        return this.artifactMode;
    }

    /**
     * Called when a new text object should be started. Be sure to call setFont() before
     * issuing any text painting commands.
     */
    public void beginTextObject() {
        if (inTextObject) {
            throw new IllegalStateException("Already in text object");
        }
        write("BT\n");
        this.inTextObject = true;
    }

    /**
     * Begin of a regular text object, used for accessibility
     * @param mcid of text object
     * @param structElemType of parent
     */
    public void beginTextObjectAccess(int mcid, String structElemType) {
        if (inTextObject) {
            throw new IllegalStateException("Already in text object");
        }
           write(structElemType + " <</MCID "
                   + String.valueOf(mcid) + ">>\nBDC\nBT\n");
        this.inTextObject = true;
    }

    /**
     * Begin of a text object marked as artifact (fo:leader in XSL-FO) text object.
     * Used for accessibility.
     */
    public void beginArtifactTextObject() {
        if (inTextObject) {
            throw new IllegalStateException("Already in text object");
        }
        write("/Artifact\nBMC\nBT\n");
        this.inTextObject = true;
        this.artifactMode = true;
    }

    /**
     * Called when a text object should be ended.
     */
    public void endTextObject() {
        endTextObject(false);
    }

    /**
     * Called when a text object should be ended.
     * @param accessEnabled indicating if accessibility is turned on or not
     */
    public void endTextObject(boolean accessEnabled) {
        checkInTextObject();
        if (accessEnabled) {
            write("ET\nEMC\n");
        } else {
            write("ET\n");
        }
        this.artifactMode = false;
        this.inTextObject = false;
        initValues();
    }

    /**
     * Resets the state fields.
     */
    protected void initValues() {
        this.currentFontName = null;
        this.currentFontSize = 0.0;
        this.textRenderingMode = TR_FILL;
    }

    /**
     * Creates a "q" command, pushing a copy of the entire graphics state onto the stack.
     */
    public void saveGraphicsState() {
        write("q\n");
    }

    /**
     * Creates a "Q" command, restoring the entire graphics state to its former value by popping
     * it from the stack.
     */
    public void restoreGraphicsState() {
        write("Q\n");
    }

    /**
     * Creates a "cm" command.
     * @param at the transformation matrix
     */
    public void concatMatrix(AffineTransform at) {
        if (!at.isIdentity()) {
            writeTJ();
            StringBuffer sb = new StringBuffer();
            writeAffineTransform(at, sb);
            sb.append(" cm\n");
            write(sb.toString());
        }
    }

    /**
     * Writes a "Tf" command, setting a new current font.
     * @param fontName the name of the font to select
     * @param fontSize the font size (in points)
     */
    public void writeTf(String fontName, double fontSize) {
        checkInTextObject();
        write("/" + fontName + " " + PDFNumber.doubleOut(fontSize) + " Tf\n");

        this.startText = useMultiByte ? "<" : "(";
        this.endText = useMultiByte ? ">" : ")";
    }

    /**
     * Updates the current font. This method only writes a "Tf" if the current font changes.
     * @param fontName the name of the font to select
     * @param fontSize the font size (in points)
     * @param multiByte true indicates the font is a multi-byte font, false means single-byte
     */
    public void updateTf(String fontName, double fontSize, boolean multiByte) {
        checkInTextObject();
        if (!fontName.equals(this.currentFontName) || (fontSize != this.currentFontSize)) {
            writeTJ();
            this.currentFontName = fontName;
            this.currentFontSize = fontSize;
            this.useMultiByte = multiByte;
            writeTf(fontName, fontSize);
        }
    }

    /**
     * Sets the text rendering mode.
     * @param mode the rendering mode (value 0 to 7, see PDF Spec, constants: TR_*)
     */
    public void setTextRenderingMode(int mode) {
        if (mode < 0 || mode > 7) {
            throw new IllegalArgumentException(
                    "Illegal value for text rendering mode. Expected: 0-7");
        }
        if (mode != this.textRenderingMode) {
            writeTJ();
            this.textRenderingMode = mode;
            write(this.textRenderingMode + " Tr\n");
        }
    }

    /**
     * Sets the text rendering mode.
     * @param fill true if the text should be filled
     * @param stroke true if the text should be stroked
     * @param addToClip true if the path should be added for clipping
     */
    public void setTextRenderingMode(boolean fill, boolean stroke, boolean addToClip) {
        int mode;
        if (fill) {
            mode = (stroke ? 2 : 0);
        } else {
            mode = (stroke ? 1 : 3);
        }
        if (addToClip) {
            mode += 4;
        }
        setTextRenderingMode(mode);
    }

    /**
     * Writes a "Tm" command, setting a new text transformation matrix.
     * @param localTransform the new text transformation matrix
     */
    public void writeTextMatrix(AffineTransform localTransform) {
        StringBuffer sb = new StringBuffer();
        writeAffineTransform(localTransform, sb);
        sb.append(" Tm ");
        write(sb.toString());
    }

    /**
     * Writes a char to the "TJ-Buffer".
     * @param codepoint the mapped character (code point/character code)
     */
    public void writeTJMappedChar(char codepoint) {
        if (bufTJ == null) {
            bufTJ = new StringBuffer();
        }
        if (bufTJ.length() == 0) {
            bufTJ.append("[").append(startText);
        }
        writeChar(codepoint, bufTJ);
    }

    /**
     * Writes a glyph adjust value to the "TJ-Buffer".
     * @param adjust the glyph adjust value in thousands of text unit space.
     */
    public void adjustGlyphTJ(double adjust) {
        if (bufTJ == null) {
            bufTJ = new StringBuffer();
        }
        if (bufTJ.length() > 0) {
            bufTJ.append(endText).append(" ");
        }
        if (bufTJ.length() == 0) {
            bufTJ.append("[");
        }
        bufTJ.append(PDFNumber.doubleOut(adjust, DEC - 4));
        bufTJ.append(" ");
        bufTJ.append(startText);
    }

    /**
     * Writes a "TJ" command, writing out the accumulated buffer with the characters and glyph
     * positioning values. The buffer is reset afterwards.
     */
    public void writeTJ() {
        if (isInString()) {
            bufTJ.append(endText).append("] TJ\n");
            write(bufTJ.toString());
            bufTJ.setLength(0);
        }
    }

    private boolean isInString() {
        return bufTJ != null && bufTJ.length() > 0;
    }

}