aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/QPDFAnnotationObjectHelper.cc
blob: 5e4be79532a9c0179d7b913b95773673eb722859 (plain) (blame)
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
#include <qpdf/QPDFAnnotationObjectHelper.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QPDFMatrix.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFNameTreeObjectHelper.hh>
#include <algorithm>

QPDFAnnotationObjectHelper::Members::~Members()
{
}

QPDFAnnotationObjectHelper::Members::Members()
{
}

QPDFAnnotationObjectHelper::QPDFAnnotationObjectHelper(QPDFObjectHandle oh) :
    QPDFObjectHelper(oh)
{
}

std::string
QPDFAnnotationObjectHelper::getSubtype()
{
    return this->oh.getKey("/Subtype").getName();
}

QPDFObjectHandle::Rectangle
QPDFAnnotationObjectHelper::getRect()
{
    return this->oh.getKey("/Rect").getArrayAsRectangle();
}

QPDFObjectHandle
QPDFAnnotationObjectHelper::getAppearanceDictionary()
{
    return this->oh.getKey("/AP");
}

std::string
QPDFAnnotationObjectHelper::getAppearanceState()
{
    if (this->oh.getKey("/AS").isName())
    {
        QTC::TC("qpdf", "QPDFAnnotationObjectHelper AS present");
        return this->oh.getKey("/AS").getName();
    }
    QTC::TC("qpdf", "QPDFAnnotationObjectHelper AS absent");
    return "";
}

int
QPDFAnnotationObjectHelper::getFlags()
{
    QPDFObjectHandle flags_obj = this->oh.getKey("/F");
    return flags_obj.isInteger() ? flags_obj.getIntValue() : 0;
}

QPDFObjectHandle
QPDFAnnotationObjectHelper::getAppearanceStream(
    std::string const& which,
    std::string const& state)
{
    QPDFObjectHandle ap = getAppearanceDictionary();
    std::string desired_state = state.empty() ? getAppearanceState() : state;
    if (ap.isDictionary())
    {
        QPDFObjectHandle ap_sub = ap.getKey(which);
        if (ap_sub.isStream() && desired_state.empty())
        {
            QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP stream");
            return ap_sub;
        }
        if (ap_sub.isDictionary() && (! desired_state.empty()))
        {
            QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP dictionary");
            QPDFObjectHandle ap_sub_val = ap_sub.getKey(desired_state);
            if (ap_sub_val.isStream())
            {
                QTC::TC("qpdf", "QPDFAnnotationObjectHelper AN sub stream");
                return ap_sub_val;
            }
        }
    }
    QTC::TC("qpdf", "QPDFAnnotationObjectHelper AN null");
    return QPDFObjectHandle::newNull();
}

std::string
QPDFAnnotationObjectHelper::getPageContentForAppearance(
    std::string const& name, int rotate,
    int required_flags, int forbidden_flags)
{
    if (! getAppearanceStream("/N").isStream())
    {
        return "";
    }

    // The appearance matrix computed by this method is the
    // transformation matrix that needs to be in effect when drawing
    // this annotation's appearance stream on the page. The algorithm
    // for computing the appearance matrix described in section 12.5.5
    // of the ISO-32000 PDF spec is similar but not identical to what
    // we are doing here.

    // When rendering an appearance stream associated with an
    // annotation, there are four relevant components:
    //
    // * The appearance stream's bounding box (/BBox)
    // * The appearance stream's matrix (/Matrix)
    // * The annotation's rectangle (/Rect)
    // * In the case of form fields with the NoRotate flag, the
    //   page's rotation

    // When rendering a form xobject in isolation, just drawn with a
    // /Do operator, the is no form field, so page rotation is not
    // relevant, and there is no annotation, so /Rect is not relevant,
    // so only /BBox and /Matrix are relevant. The effect of these are
    // as follows:

    // * /BBox is treated as a clipping region
    // * /Matrix is applied as a transformation prior to rendering the
    //   appearance stream.

    // There is no relationship between /BBox and /Matrix in this
    // case.

    // When rendering a form xobject in the context of an annotation,
    // things are a little different. In particular, a matrix is
    // established such that /BBox, when transformed by /Matrix, would
    // fit completely inside of /Rect. /BBox is no longer a clipping
    // region. To illustrate the difference, consider a /Matrix of
    // [2 0 0 2 0 0], which is scaling by a factor of two along both
    // axes. If the appearance stream drew a rectangle equal to /BBox,
    // in the case of the form xobject in isolation, this matrix would
    // cause only the lower-left quadrant of the rectangle to be
    // visible since the scaling would cause the rest of it to fall
    // outside of the clipping region. In the case of the form xobject
    // displayed in the context of an annotation, such a matrix would
    // have no effect at all because it would be applied to the
    // bounding box first, and then when the resulting enclosing
    // quadrilateral was transformed to fit into /Rect, the effect of
    // the scaling would be undone.

    // Our job is to create a transformation matrix that compensates
    // for these differences so that the appearance stream of an
    // annotation can be drawn as a regular form xobject.

    // To do this, we perform the following steps, which overlap
    // significantly with the algorithm in 12.5.5:

    // 1. Transform the four corners of /BBox by applying /Matrix to
    //    them, creating an arbitrarily transformed quadrilateral.

    // 2. Find the minimum upright rectangle that encompasses the
    //    resulting quadrilateral. This is the "transformed appearance
    //    box", T.

    // 3. Compute matrix A that maps the lower left and upper right
    //    corners of T to the annotation's /Rect. This can be done by
    //    scaling so that the sizes match and translating so that the
    //    scaled T exactly overlaps /Rect.

    // If the annotation's /F flag has bit 4 set, this means that
    // annotation is to be rotated about its upper left corner to
    // counteract any rotation of the page so it remains upright. To
    // achieve this effect, we do the following extra steps:

    // 1. Perform the rotation on /BBox box prior to transforming it
    //    with /Matrix (by replacing matrix with concatenation of
    //    matrix onto the rotation)

    // 2. Rotate the destination rectangle by the specified amount

    // 3. Apply the rotation to A as computed above to get the final
    //    appearance matrix.

    QPDFObjectHandle rect_obj = this->oh.getKey("/Rect");
    QPDFObjectHandle as = getAppearanceStream("/N").getDict();
    QPDFObjectHandle bbox_obj = as.getKey("/BBox");
    QPDFObjectHandle matrix_obj = as.getKey("/Matrix");

    int flags = getFlags();
    if (flags & forbidden_flags)
    {
        QTC::TC("qpdf", "QPDFAnnotationObjectHelper forbidden flags");
        return "";
    }
    if ((flags & required_flags) != required_flags)
    {
        QTC::TC("qpdf", "QPDFAnnotationObjectHelper missing required flags");
        return "";
    }

    if (! (bbox_obj.isRectangle() && rect_obj.isRectangle()))
    {
        return "";
    }
    QPDFMatrix matrix;
    if (matrix_obj.isMatrix())
    {
        QTC::TC("qpdf", "QPDFAnnotationObjectHelper explicit matrix");
        matrix = QPDFMatrix(matrix_obj.getArrayAsMatrix());
    }
    else
    {
        QTC::TC("qpdf", "QPDFAnnotationObjectHelper default matrix");
    }
    QPDFObjectHandle::Rectangle rect = rect_obj.getArrayAsRectangle();
    bool do_rotate = (rotate && (flags & an_no_rotate));
    if (do_rotate)
    {
        // If the the annotation flags include the NoRotate bit and
        // the page is rotated, we have to rotate the annotation about
        // its upper left corner by the same amount in the opposite
        // direction so that it will remain upright in absolute
        // coordinates. Since the semantics of /Rotate for a page are
        // to rotate the page, while the effect of rotating using a
        // transformation matrix is to rotate the coordinate system,
        // the opposite directionality is explicit in the code.
        QPDFMatrix mr;
        mr.rotatex90(rotate);
        mr.concat(matrix);
        matrix = mr;
        double rect_w = rect.urx - rect.llx;
        double rect_h = rect.ury - rect.lly;
        switch (rotate)
        {
          case 90:
            QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 90");
            rect = QPDFObjectHandle::Rectangle(
                rect.llx,
                rect.ury,
                rect.llx + rect_h,
                rect.ury + rect_w);
            break;
          case 180:
            QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 180");
            rect = QPDFObjectHandle::Rectangle(
                rect.llx - rect_w,
                rect.ury,
                rect.llx,
                rect.ury + rect_h);
            break;
          case 270:
            QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 270");
            rect = QPDFObjectHandle::Rectangle(
                rect.llx - rect_h,
                rect.ury - rect_w,
                rect.llx,
                rect.ury);
            break;
          default:
            // ignore
            break;
        }
    }

    // Transform bounding box by matrix to get T
    QPDFObjectHandle::Rectangle bbox = bbox_obj.getArrayAsRectangle();
    std::vector<double> bx(4);
    std::vector<double> by(4);
    matrix.transform(bbox.llx, bbox.lly, bx.at(0), by.at(0));
    matrix.transform(bbox.llx, bbox.ury, bx.at(1), by.at(1));
    matrix.transform(bbox.urx, bbox.lly, bx.at(2), by.at(2));
    matrix.transform(bbox.urx, bbox.ury, bx.at(3), by.at(3));
    // Find the transformed appearance box
    double t_llx = *std::min_element(bx.begin(), bx.end());
    double t_urx = *std::max_element(bx.begin(), bx.end());
    double t_lly = *std::min_element(by.begin(), by.end());
    double t_ury = *std::max_element(by.begin(), by.end());
    if ((t_urx == t_llx) || (t_ury == t_lly))
    {
        // avoid division by zero
        return "";
    }
    // Compute a matrix to transform the appearance box to the rectangle
    QPDFMatrix AA;
    AA.translate(rect.llx, rect.lly);
    AA.scale((rect.urx - rect.llx) / (t_urx - t_llx),
             (rect.ury - rect.lly) / (t_ury - t_lly));
    AA.translate(-t_llx, -t_lly);
    if (do_rotate)
    {
        AA.rotatex90(rotate);
    }

    as.replaceKey("/Subtype", QPDFObjectHandle::newName("/Form"));
    return (
        "q\n" +
        AA.unparse() + " cm\n" +
        name + " Do\n" +
        "Q\n");
}