Coverage Report

Created: 2025-10-12 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFAcroFormDocumentHelper.cc
Line
Count
Source
1
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
2
3
#include <qpdf/Pl_Buffer.hh>
4
#include <qpdf/QPDFObjectHandle_private.hh>
5
#include <qpdf/QPDFPageDocumentHelper.hh>
6
#include <qpdf/QPDF_private.hh>
7
#include <qpdf/QTC.hh>
8
#include <qpdf/QUtil.hh>
9
#include <qpdf/ResourceFinder.hh>
10
11
#include <deque>
12
#include <utility>
13
14
using namespace qpdf;
15
using namespace std::literals;
16
17
class QPDFAcroFormDocumentHelper::Members
18
{
19
  public:
20
0
    Members() = default;
21
    Members(Members const&) = delete;
22
0
    ~Members() = default;
23
24
    struct FieldData
25
    {
26
        std::vector<QPDFAnnotationObjectHelper> annotations;
27
        std::string name;
28
    };
29
30
    bool cache_valid{false};
31
    std::map<QPDFObjGen, FieldData> field_to;
32
    std::map<QPDFObjGen, QPDFFormFieldObjectHelper> annotation_to_field;
33
    std::map<std::string, std::set<QPDFObjGen>> name_to_fields;
34
};
35
36
QPDFAcroFormDocumentHelper::QPDFAcroFormDocumentHelper(QPDF& qpdf) :
37
0
    QPDFDocumentHelper(qpdf),
38
0
    m(std::make_shared<Members>())
39
0
{
40
    // We have to analyze up front. Otherwise, when we are adding annotations and fields, we are in
41
    // a temporarily unstable configuration where some widget annotations are not reachable.
42
0
    analyze();
43
0
}
44
45
QPDFAcroFormDocumentHelper&
46
QPDFAcroFormDocumentHelper::get(QPDF& qpdf)
47
0
{
48
0
    return qpdf.doc().acroform();
49
0
}
50
51
void
52
QPDFAcroFormDocumentHelper::validate(bool repair)
53
0
{
54
0
    invalidateCache();
55
0
    analyze();
56
0
}
57
58
void
59
QPDFAcroFormDocumentHelper::invalidateCache()
60
0
{
61
0
    m->cache_valid = false;
62
0
    m->field_to.clear();
63
0
    m->annotation_to_field.clear();
64
0
}
65
66
bool
67
QPDFAcroFormDocumentHelper::hasAcroForm()
68
0
{
69
0
    return qpdf.getRoot().hasKey("/AcroForm");
70
0
}
71
72
QPDFObjectHandle
73
QPDFAcroFormDocumentHelper::getOrCreateAcroForm()
74
0
{
75
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
76
0
    if (!acroform.isDictionary()) {
77
0
        acroform = qpdf.getRoot().replaceKeyAndGetNew(
78
0
            "/AcroForm", qpdf.makeIndirectObject(QPDFObjectHandle::newDictionary()));
79
0
    }
80
0
    return acroform;
81
0
}
82
83
void
84
QPDFAcroFormDocumentHelper::addFormField(QPDFFormFieldObjectHelper ff)
85
0
{
86
0
    auto acroform = getOrCreateAcroForm();
87
0
    auto fields = acroform.getKey("/Fields");
88
0
    if (!fields.isArray()) {
89
0
        fields = acroform.replaceKeyAndGetNew("/Fields", QPDFObjectHandle::newArray());
90
0
    }
91
0
    fields.appendItem(ff.getObjectHandle());
92
0
    QPDFObjGen::set visited;
93
0
    traverseField(ff.getObjectHandle(), QPDFObjectHandle::newNull(), 0, visited);
94
0
}
95
96
void
97
QPDFAcroFormDocumentHelper::addAndRenameFormFields(std::vector<QPDFObjectHandle> fields)
98
0
{
99
0
    analyze();
100
0
    std::map<std::string, std::string> renames;
101
0
    QPDFObjGen::set seen;
102
0
    for (std::list<QPDFObjectHandle> queue{fields.begin(), fields.end()}; !queue.empty();
103
0
         queue.pop_front()) {
104
0
        auto& obj = queue.front();
105
0
        if (seen.add(obj)) {
106
0
            auto kids = obj.getKey("/Kids");
107
0
            if (kids.isArray()) {
108
0
                for (auto const& kid: kids.aitems()) {
109
0
                    queue.push_back(kid);
110
0
                }
111
0
            }
112
113
0
            if (obj.hasKey("/T")) {
114
                // Find something we can append to the partial name that makes the fully qualified
115
                // name unique. When we find something, reuse the same suffix for all fields in this
116
                // group with the same name. We can only change the name of fields that have /T, and
117
                // this field's /T is always at the end of the fully qualified name, appending to /T
118
                // has the effect of appending the same thing to the fully qualified name.
119
0
                std::string old_name = QPDFFormFieldObjectHelper(obj).getFullyQualifiedName();
120
0
                if (!renames.contains(old_name)) {
121
0
                    std::string new_name = old_name;
122
0
                    int suffix = 0;
123
0
                    std::string append;
124
0
                    while (!getFieldsWithQualifiedName(new_name).empty()) {
125
0
                        ++suffix;
126
0
                        append = "+" + std::to_string(suffix);
127
0
                        new_name = old_name + append;
128
0
                    }
129
0
                    renames[old_name] = append;
130
0
                }
131
0
                std::string append = renames[old_name];
132
0
                if (!append.empty()) {
133
0
                    obj.replaceKey(
134
0
                        "/T",
135
0
                        QPDFObjectHandle::newUnicodeString(
136
0
                            obj.getKey("/T").getUTF8Value() + append));
137
0
                }
138
0
            }
139
0
        }
140
0
    }
141
142
0
    for (auto const& i: fields) {
143
0
        addFormField(i);
144
0
    }
145
0
}
146
147
void
148
QPDFAcroFormDocumentHelper::removeFormFields(std::set<QPDFObjGen> const& to_remove)
149
0
{
150
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
151
0
    if (!acroform.isDictionary()) {
152
0
        return;
153
0
    }
154
0
    auto fields = acroform.getKey("/Fields");
155
0
    if (!fields.isArray()) {
156
0
        return;
157
0
    }
158
159
0
    for (auto const& og: to_remove) {
160
0
        auto it = m->field_to.find(og);
161
0
        if (it != m->field_to.end()) {
162
0
            for (auto aoh: it->second.annotations) {
163
0
                m->annotation_to_field.erase(aoh.getObjectHandle().getObjGen());
164
0
            }
165
0
            auto const& name = it->second.name;
166
0
            if (!name.empty()) {
167
0
                m->name_to_fields[name].erase(og);
168
0
                if (m->name_to_fields[name].empty()) {
169
0
                    m->name_to_fields.erase(name);
170
0
                }
171
0
            }
172
0
            m->field_to.erase(og);
173
0
        }
174
0
    }
175
176
0
    int i = 0;
177
0
    while (std::cmp_less(i, fields.size())) {
178
0
        auto field = fields.getArrayItem(i);
179
0
        if (to_remove.contains(field.getObjGen())) {
180
0
            fields.eraseItem(i);
181
0
        } else {
182
0
            ++i;
183
0
        }
184
0
    }
185
0
}
186
187
void
188
QPDFAcroFormDocumentHelper::setFormFieldName(QPDFFormFieldObjectHelper ff, std::string const& name)
189
0
{
190
0
    ff.setFieldAttribute("/T", name);
191
0
    QPDFObjGen::set visited;
192
0
    auto ff_oh = ff.getObjectHandle();
193
0
    traverseField(ff_oh, ff_oh.getKey("/Parent"), 0, visited);
194
0
}
195
196
std::vector<QPDFFormFieldObjectHelper>
197
QPDFAcroFormDocumentHelper::getFormFields()
198
0
{
199
0
    analyze();
200
0
    std::vector<QPDFFormFieldObjectHelper> result;
201
0
    for (auto const& [og, data]: m->field_to) {
202
0
        if (!(data.annotations.empty())) {
203
0
            result.emplace_back(qpdf.getObject(og));
204
0
        }
205
0
    }
206
0
    return result;
207
0
}
208
209
std::set<QPDFObjGen>
210
QPDFAcroFormDocumentHelper::getFieldsWithQualifiedName(std::string const& name)
211
0
{
212
0
    analyze();
213
    // Keep from creating an empty entry
214
0
    auto iter = m->name_to_fields.find(name);
215
0
    if (iter != m->name_to_fields.end()) {
216
0
        return iter->second;
217
0
    }
218
0
    return {};
219
0
}
220
221
std::vector<QPDFAnnotationObjectHelper>
222
QPDFAcroFormDocumentHelper::getAnnotationsForField(QPDFFormFieldObjectHelper h)
223
0
{
224
0
    analyze();
225
0
    std::vector<QPDFAnnotationObjectHelper> result;
226
0
    QPDFObjGen og(h.getObjectHandle().getObjGen());
227
0
    if (m->field_to.contains(og)) {
228
0
        result = m->field_to[og].annotations;
229
0
    }
230
0
    return result;
231
0
}
232
233
std::vector<QPDFAnnotationObjectHelper>
234
QPDFAcroFormDocumentHelper::getWidgetAnnotationsForPage(QPDFPageObjectHelper h)
235
0
{
236
0
    return h.getAnnotations("/Widget");
237
0
}
238
239
std::vector<QPDFFormFieldObjectHelper>
240
QPDFAcroFormDocumentHelper::getFormFieldsForPage(QPDFPageObjectHelper ph)
241
0
{
242
0
    analyze();
243
0
    QPDFObjGen::set todo;
244
0
    std::vector<QPDFFormFieldObjectHelper> result;
245
0
    for (auto& annot: getWidgetAnnotationsForPage(ph)) {
246
0
        auto field = getFieldForAnnotation(annot).getTopLevelField();
247
0
        if (todo.add(field) && field.getObjectHandle().isDictionary()) {
248
0
            result.push_back(field);
249
0
        }
250
0
    }
251
0
    return result;
252
0
}
253
254
QPDFFormFieldObjectHelper
255
QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h)
256
0
{
257
0
    QPDFObjectHandle oh = h.getObjectHandle();
258
0
    QPDFFormFieldObjectHelper result(QPDFObjectHandle::newNull());
259
0
    if (!oh.isDictionaryOfType("", "/Widget")) {
260
0
        return result;
261
0
    }
262
0
    analyze();
263
0
    QPDFObjGen og(oh.getObjGen());
264
0
    if (m->annotation_to_field.contains(og)) {
265
0
        result = m->annotation_to_field[og];
266
0
    }
267
0
    return result;
268
0
}
269
270
void
271
QPDFAcroFormDocumentHelper::analyze()
272
0
{
273
0
    if (m->cache_valid) {
274
0
        return;
275
0
    }
276
0
    m->cache_valid = true;
277
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
278
0
    if (!(acroform.isDictionary() && acroform.hasKey("/Fields"))) {
279
0
        return;
280
0
    }
281
0
    QPDFObjectHandle fields = acroform.getKey("/Fields");
282
0
    if (auto fa = fields.as_array(strict)) {
283
        // Traverse /AcroForm to find annotations and map them bidirectionally to fields.
284
285
0
        QPDFObjGen::set visited;
286
0
        QPDFObjectHandle null(QPDFObjectHandle::newNull());
287
0
        for (auto const& field: fa) {
288
0
            traverseField(field, null, 0, visited);
289
0
        }
290
0
    } else {
291
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper fields not array");
292
0
        acroform.warn("/Fields key of /AcroForm dictionary is not an array; ignoring");
293
0
        fields = QPDFObjectHandle::newArray();
294
0
    }
295
296
    // All Widget annotations should have been encountered by traversing /AcroForm, but in case any
297
    // weren't, find them by walking through pages, and treat any widget annotation that is not
298
    // associated with a field as its own field. This just ensures that requesting the field for any
299
    // annotation we find through a page's /Annots list will have some associated field. Note that
300
    // a file that contains this kind of error will probably not
301
    // actually work with most viewers.
302
303
0
    for (auto const& ph: QPDFPageDocumentHelper(qpdf).getAllPages()) {
304
0
        for (auto const& iter: getWidgetAnnotationsForPage(ph)) {
305
0
            QPDFObjectHandle annot(iter.getObjectHandle());
306
0
            QPDFObjGen og(annot.getObjGen());
307
0
            if (!m->annotation_to_field.contains(og)) {
308
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper orphaned widget");
309
                // This is not supposed to happen, but it's easy enough for us to handle this case.
310
                // Treat the annotation as its own field. This could allow qpdf to sensibly handle a
311
                // case such as a PDF creator adding a self-contained annotation (merged with the
312
                // field dictionary) to the page's /Annots array and forgetting to also put it in
313
                // /AcroForm.
314
0
                annot.warn(
315
0
                    "this widget annotation is not reachable from /AcroForm in the document "
316
0
                    "catalog");
317
0
                m->annotation_to_field[og] = QPDFFormFieldObjectHelper(annot);
318
0
                m->field_to[og].annotations.emplace_back(annot);
319
0
            }
320
0
        }
321
0
    }
322
0
}
323
324
void
325
QPDFAcroFormDocumentHelper::traverseField(
326
    QPDFObjectHandle field, QPDFObjectHandle parent, int depth, QPDFObjGen::set& visited)
327
0
{
328
0
    if (depth > 100) {
329
        // Arbitrarily cut off recursion at a fixed depth to avoid specially crafted files that
330
        // could cause stack overflow.
331
0
        return;
332
0
    }
333
0
    if (!field.indirect()) {
334
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper direct field");
335
0
        field.warn(
336
0
            "encountered a direct object as a field or annotation while "
337
0
            "traversing /AcroForm; ignoring field or annotation");
338
0
        return;
339
0
    }
340
0
    if (!field.isDictionary()) {
341
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper non-dictionary field");
342
0
        field.warn(
343
0
            "encountered a non-dictionary as a field or annotation while"
344
0
            " traversing /AcroForm; ignoring field or annotation");
345
0
        return;
346
0
    }
347
0
    QPDFObjGen og(field.getObjGen());
348
0
    if (!visited.add(og)) {
349
0
        QTC::TC("qpdf", "QPDFAcroFormDocumentHelper loop");
350
0
        field.warn("loop detected while traversing /AcroForm");
351
0
        return;
352
0
    }
353
354
    // A dictionary encountered while traversing the /AcroForm field may be a form field, an
355
    // annotation, or the merger of the two. A field that has no fields below it is a terminal. If a
356
    // terminal field looks like an annotation, it is an annotation because annotation dictionary
357
    // fields can be merged with terminal field dictionaries. Otherwise, the annotation fields might
358
    // be there to be inherited by annotations below it.
359
360
0
    bool is_annotation = false;
361
0
    bool is_field = (0 == depth);
362
0
    if (auto a = field.getKey("/Kids").as_array(strict)) {
363
0
        is_field = true;
364
0
        for (auto const& item: a) {
365
0
            traverseField(item, field, 1 + depth, visited);
366
0
        }
367
0
    } else {
368
0
        if (field.hasKey("/Parent")) {
369
0
            is_field = true;
370
0
        }
371
0
        if (field.hasKey("/Subtype") || field.hasKey("/Rect") || field.hasKey("/AP")) {
372
0
            is_annotation = true;
373
0
        }
374
0
    }
375
376
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field found", (depth == 0) ? 0 : 1);
377
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper annotation found", (is_field ? 0 : 1));
378
379
0
    if (is_annotation) {
380
0
        QPDFObjectHandle our_field = (is_field ? field : parent);
381
0
        m->field_to[our_field.getObjGen()].annotations.emplace_back(field);
382
0
        m->annotation_to_field[og] = QPDFFormFieldObjectHelper(our_field);
383
0
    }
384
385
0
    if (is_field && (field.hasKey("/T"))) {
386
0
        QPDFFormFieldObjectHelper foh(field);
387
0
        auto f_og = field.getObjGen();
388
0
        std::string name = foh.getFullyQualifiedName();
389
0
        auto old = m->field_to.find(f_og);
390
0
        if (old != m->field_to.end() && !old->second.name.empty()) {
391
            // We might be updating after a name change, so remove any old information
392
0
            m->name_to_fields[old->second.name].erase(f_og);
393
0
        }
394
0
        m->field_to[f_og].name = name;
395
0
        m->name_to_fields[name].insert(f_og);
396
0
    }
397
0
}
398
399
bool
400
QPDFAcroFormDocumentHelper::getNeedAppearances()
401
0
{
402
0
    bool result = false;
403
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
404
0
    if (acroform.isDictionary() && acroform.getKey("/NeedAppearances").isBool()) {
405
0
        result = acroform.getKey("/NeedAppearances").getBoolValue();
406
0
    }
407
0
    return result;
408
0
}
409
410
void
411
QPDFAcroFormDocumentHelper::setNeedAppearances(bool val)
412
0
{
413
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
414
0
    if (!acroform.isDictionary()) {
415
0
        qpdf.getRoot().warn(
416
0
            "ignoring call to QPDFAcroFormDocumentHelper::setNeedAppearances"
417
0
            " on a file that lacks an /AcroForm dictionary");
418
0
        return;
419
0
    }
420
0
    if (val) {
421
0
        acroform.replaceKey("/NeedAppearances", QPDFObjectHandle::newBool(true));
422
0
    } else {
423
0
        acroform.removeKey("/NeedAppearances");
424
0
    }
425
0
}
426
427
void
428
QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded()
429
0
{
430
0
    if (!getNeedAppearances()) {
431
0
        return;
432
0
    }
433
434
0
    for (auto const& page: QPDFPageDocumentHelper(qpdf).getAllPages()) {
435
0
        for (auto& aoh: getWidgetAnnotationsForPage(page)) {
436
0
            QPDFFormFieldObjectHelper ffh = getFieldForAnnotation(aoh);
437
0
            if (ffh.getFieldType() == "/Btn") {
438
                // Rather than generating appearances for button fields, rely on what's already
439
                // there. Just make sure /AS is consistent with /V, which we can do by resetting the
440
                // value of the field back to itself. This code is referenced in a comment in
441
                // QPDFFormFieldObjectHelper::generateAppearance.
442
0
                if (ffh.isRadioButton() || ffh.isCheckbox()) {
443
0
                    ffh.setV(ffh.getValue());
444
0
                }
445
0
            } else {
446
0
                ffh.generateAppearance(aoh);
447
0
            }
448
0
        }
449
0
    }
450
0
    setNeedAppearances(false);
451
0
}
452
453
void
454
QPDFAcroFormDocumentHelper::disableDigitalSignatures()
455
0
{
456
0
    qpdf.removeSecurityRestrictions();
457
0
    std::set<QPDFObjGen> to_remove;
458
0
    auto fields = getFormFields();
459
0
    for (auto& f: fields) {
460
0
        auto ft = f.getFieldType();
461
0
        if (ft == "/Sig") {
462
0
            auto oh = f.getObjectHandle();
463
0
            to_remove.insert(oh.getObjGen());
464
            // Make this no longer a form field. If it's also an annotation, the annotation will
465
            // survive. If it's only a field and is no longer referenced, it will disappear.
466
0
            oh.removeKey("/FT");
467
            // Remove fields that are specific to signature fields.
468
0
            oh.removeKey("/V");
469
0
            oh.removeKey("/SV");
470
0
            oh.removeKey("/Lock");
471
0
        }
472
0
    }
473
0
    removeFormFields(to_remove);
474
0
}
475
476
void
477
QPDFAcroFormDocumentHelper::adjustInheritedFields(
478
    QPDFObjectHandle obj,
479
    bool override_da,
480
    std::string const& from_default_da,
481
    bool override_q,
482
    int from_default_q)
483
0
{
484
0
    if (!(override_da || override_q)) {
485
0
        return;
486
0
    }
487
    // Override /Q or /DA if needed. If this object has a field type, directly or inherited, it is a
488
    // field and not just an annotation. In that case, we need to override if we are getting a value
489
    // from the document that is different from the value we would have gotten from the old
490
    // document. We must take care not to override an explicit value. It's possible that /FT may be
491
    // inherited by lower fields that may explicitly set /DA or /Q or that this is a field whose
492
    // type does not require /DA or /Q and we may be put a value on the field that is unused. This
493
    // is harmless, so it's not worth trying to work around.
494
495
0
    auto has_explicit = [](QPDFFormFieldObjectHelper& field, std::string const& key) {
496
0
        if (field.getObjectHandle().hasKey(key)) {
497
0
            return true;
498
0
        }
499
0
        return !field.getInheritableFieldValue(key).null();
500
0
    };
501
502
0
    if (override_da || override_q) {
503
0
        QPDFFormFieldObjectHelper cur_field(obj);
504
0
        if (override_da && (!has_explicit(cur_field, "/DA"))) {
505
0
            std::string da = cur_field.getDefaultAppearance();
506
0
            if (da != from_default_da) {
507
0
                obj.replaceKey("/DA", QPDFObjectHandle::newUnicodeString(from_default_da));
508
0
            }
509
0
        }
510
0
        if (override_q && (!has_explicit(cur_field, "/Q"))) {
511
0
            int q = cur_field.getQuadding();
512
0
            if (q != from_default_q) {
513
0
                obj.replaceKey("/Q", QPDFObjectHandle::newInteger(from_default_q));
514
0
            }
515
0
        }
516
0
    }
517
0
}
518
519
namespace
520
{
521
    class ResourceReplacer: public QPDFObjectHandle::TokenFilter
522
    {
523
      public:
524
        ResourceReplacer(
525
            std::map<std::string, std::map<std::string, std::string>> const& dr_map,
526
            std::map<std::string, std::map<std::string, std::vector<size_t>>> const& rnames);
527
0
        ~ResourceReplacer() override = default;
528
        void handleToken(QPDFTokenizer::Token const&) override;
529
530
      private:
531
        size_t offset{0};
532
        std::map<std::string, std::map<size_t, std::string>> to_replace;
533
    };
534
} // namespace
535
536
ResourceReplacer::ResourceReplacer(
537
    std::map<std::string, std::map<std::string, std::string>> const& dr_map,
538
    std::map<std::string, std::map<std::string, std::vector<size_t>>> const& rnames)
539
0
{
540
    // We have:
541
    // * dr_map[resource_type][key] == new_key
542
    // * rnames[resource_type][key] == set of offsets
543
    //
544
    // We want:
545
    // * to_replace[key][offset] = new_key
546
547
0
    for (auto const& [rtype, key_offsets]: rnames) {
548
0
        auto dr_map_rtype = dr_map.find(rtype);
549
0
        if (dr_map_rtype == dr_map.end()) {
550
0
            continue;
551
0
        }
552
0
        for (auto const& [old_key, offsets]: key_offsets) {
553
0
            auto dr_map_rtype_old = dr_map_rtype->second.find(old_key);
554
0
            if (dr_map_rtype_old == dr_map_rtype->second.end()) {
555
0
                continue;
556
0
            }
557
0
            for (auto const& offs: offsets) {
558
0
                to_replace[old_key][offs] = dr_map_rtype_old->second;
559
0
            }
560
0
        }
561
0
    }
562
0
}
563
564
void
565
ResourceReplacer::handleToken(QPDFTokenizer::Token const& token)
566
0
{
567
0
    if (token.getType() == QPDFTokenizer::tt_name) {
568
0
        auto it1 = to_replace.find(token.getValue());
569
0
        if (it1 != to_replace.end()) {
570
0
            auto it2 = it1->second.find(offset);
571
0
            if (it2 != it1->second.end()) {
572
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper replaced DA token");
573
0
                write(it2->second);
574
0
                offset += token.getRawValue().length();
575
0
                return;
576
0
            }
577
0
        }
578
0
    }
579
0
    offset += token.getRawValue().length();
580
0
    writeToken(token);
581
0
}
582
583
void
584
QPDFAcroFormDocumentHelper::adjustDefaultAppearances(
585
    QPDFObjectHandle obj, std::map<std::string, std::map<std::string, std::string>> const& dr_map)
586
0
{
587
    // This method is called on a field that has been copied from another file but whose /DA still
588
    // refers to resources in the original file's /DR.
589
590
    // When appearance streams are generated for variable text fields (see ISO 32000 PDF spec
591
    // section 12.7.3.3), the field's /DA is used to generate content of the appearance stream. /DA
592
    // contains references to resources that may be resolved in the document's /DR dictionary, which
593
    // appears in the document's /AcroForm dictionary. For fields that we copied from other
594
    // documents, we need to ensure that resources are mapped correctly in the case of conflicting
595
    // names. For example, if a.pdf's /DR has /F1 pointing to one font and b.pdf's /DR also has /F1
596
    // but it points elsewhere, we need to make sure appearance streams of fields copied from b.pdf
597
    // into a.pdf use whatever font /F1 meant in b.pdf, not whatever it means in a.pdf. This method
598
    // takes care of that. It is only called on fields copied from foreign files.
599
600
    // A few notes:
601
    //
602
    // * If the from document's /DR and the current document's /DR have conflicting keys, we have
603
    //   already resolved the conflicts before calling this method. The dr_map parameter contains
604
    //   the mapping from old keys to new keys.
605
    //
606
    // * /DA may be inherited from the document's /AcroForm dictionary. By the time this method has
607
    //   been called, we have already copied any document-level values into the fields to avoid
608
    //   having them inherit from the new document. This was done in adjustInheritedFields.
609
610
0
    auto DA = obj.getKey("/DA");
611
0
    if (!DA.isString()) {
612
0
        return;
613
0
    }
614
615
    // Find names in /DA. /DA is a string that contains content stream-like code, so we create a
616
    // stream out of the string and then filter it. We don't attach the stream to anything, so it
617
    // will get discarded.
618
0
    ResourceFinder rf;
619
0
    auto da_stream = QPDFObjectHandle::newStream(&qpdf, DA.getUTF8Value());
620
0
    try {
621
0
        auto nwarnings = qpdf.numWarnings();
622
0
        da_stream.parseAsContents(&rf);
623
0
        if (qpdf.numWarnings() > nwarnings) {
624
0
            QTC::TC("qpdf", "QPDFAcroFormDocumentHelper /DA parse error");
625
0
        }
626
0
    } catch (std::exception& e) {
627
        // No way to reproduce in test suite right now since error conditions are converted to
628
        // warnings.
629
0
        obj.warn("Unable to parse /DA: "s + e.what() + "; this form field may not update properly");
630
0
        return;
631
0
    }
632
633
    // Regenerate /DA by filtering its tokens.
634
0
    ResourceReplacer rr(dr_map, rf.getNamesByResourceType());
635
0
    Pl_Buffer buf_pl("filtered DA");
636
0
    da_stream.filterAsContents(&rr, &buf_pl);
637
0
    std::string new_da = buf_pl.getString();
638
0
    obj.replaceKey("/DA", QPDFObjectHandle::newString(new_da));
639
0
}
640
641
void
642
QPDFAcroFormDocumentHelper::adjustAppearanceStream(
643
    QPDFObjectHandle stream, std::map<std::string, std::map<std::string, std::string>> dr_map)
644
0
{
645
    // We don't have to modify appearance streams or their resource dictionaries for them to display
646
    // properly, but we need to do so to make them save to regenerate. Suppose an appearance stream
647
    // as a font /F1 that is different from /F1 in /DR, and that when we copy the field, /F1 is
648
    // remapped to /F1_1. When the field is regenerated, /F1_1 won't appear in the stream's resource
649
    // dictionary, so the regenerated appearance stream will revert to the /F1_1 in /DR. If we
650
    // adjust existing appearance streams, we are protected from this problem.
651
652
0
    auto dict = stream.getDict();
653
0
    auto resources = dict.getKey("/Resources");
654
655
    // Make sure this stream has its own private resource dictionary.
656
0
    bool was_indirect = resources.isIndirect();
657
0
    resources = resources.shallowCopy();
658
0
    if (was_indirect) {
659
0
        resources = qpdf.makeIndirectObject(resources);
660
0
    }
661
0
    dict.replaceKey("/Resources", resources);
662
    // Create a dictionary with top-level keys so we can use mergeResources to force them to be
663
    // unshared. We will also use this to resolve conflicts that may already be in the resource
664
    // dictionary.
665
0
    auto merge_with = QPDFObjectHandle::newDictionary();
666
0
    for (auto const& top_key: dr_map) {
667
0
        merge_with.replaceKey(top_key.first, QPDFObjectHandle::newDictionary());
668
0
    }
669
0
    resources.mergeResources(merge_with);
670
    // Rename any keys in the resource dictionary that we remapped.
671
0
    for (auto const& i1: dr_map) {
672
0
        std::string const& top_key = i1.first;
673
0
        auto subdict = resources.getKey(top_key);
674
0
        if (!subdict.isDictionary()) {
675
0
            continue;
676
0
        }
677
0
        for (auto const& i2: i1.second) {
678
0
            std::string const& old_key = i2.first;
679
0
            std::string const& new_key = i2.second;
680
0
            auto existing_new = subdict.getKey(new_key);
681
0
            if (!existing_new.null()) {
682
                // The resource dictionary already has a key in it matching what we remapped an old
683
                // key to, so we'll have to move it out of the way. Stick it in merge_with, which we
684
                // will re-merge with the dictionary when we're done. We know merge_with already has
685
                // dictionaries for all the top keys.
686
0
                merge_with.getKey(top_key).replaceKey(new_key, existing_new);
687
0
            }
688
0
            auto existing_old = subdict.getKey(old_key);
689
0
            if (!existing_old.null()) {
690
0
                subdict.replaceKey(new_key, existing_old);
691
0
                subdict.removeKey(old_key);
692
0
            }
693
0
        }
694
0
    }
695
    // Deal with any any conflicts by re-merging with merge_with and updating our local copy of
696
    // dr_map, which we will use to modify the stream contents.
697
0
    resources.mergeResources(merge_with, &dr_map);
698
    // Remove empty subdictionaries
699
0
    for (auto iter: resources.ditems()) {
700
0
        if (iter.second.isDictionary() && iter.second.getKeys().empty()) {
701
0
            resources.removeKey(iter.first);
702
0
        }
703
0
    }
704
705
    // Now attach a token filter to replace the actual resources.
706
0
    ResourceFinder rf;
707
0
    try {
708
0
        auto nwarnings = qpdf.numWarnings();
709
0
        stream.parseAsContents(&rf);
710
0
        QTC::TC(
711
0
            "qpdf",
712
0
            "QPDFAcroFormDocumentHelper AP parse error",
713
0
            qpdf.numWarnings() > nwarnings ? 0 : 1);
714
0
        auto rr = new ResourceReplacer(dr_map, rf.getNamesByResourceType());
715
0
        auto tf = std::shared_ptr<QPDFObjectHandle::TokenFilter>(rr);
716
0
        stream.addTokenFilter(tf);
717
0
    } catch (std::exception& e) {
718
        // No way to reproduce in test suite right now since error conditions are converted to
719
        // warnings.
720
0
        stream.warn("Unable to parse appearance stream: "s + e.what());
721
0
    }
722
0
}
723
724
void
725
QPDFAcroFormDocumentHelper::transformAnnotations(
726
    QPDFObjectHandle a_old_annots,
727
    std::vector<QPDFObjectHandle>& new_annots,
728
    std::vector<QPDFObjectHandle>& new_fields,
729
    std::set<QPDFObjGen>& old_fields,
730
    QPDFMatrix const& cm,
731
    QPDF* from_qpdf,
732
    QPDFAcroFormDocumentHelper* from_afdh)
733
0
{
734
0
    Array old_annots = std::move(a_old_annots);
735
0
    if (!from_qpdf) {
736
        // Assume these are from the same QPDF.
737
0
        from_qpdf = &qpdf;
738
0
        from_afdh = this;
739
0
    } else if (from_qpdf != &qpdf && !from_afdh) {
740
0
        from_afdh = &QPDFAcroFormDocumentHelper::get(*from_qpdf);
741
0
    }
742
0
    const bool foreign = from_qpdf != &qpdf;
743
744
    // It's possible that we will transform annotations that don't include any form fields. This
745
    // code takes care not to muck around with /AcroForm unless we have to.
746
747
0
    Dictionary acroform = qpdf.getRoot()["/AcroForm"];
748
0
    Dictionary from_acroform = from_qpdf->getRoot()["/AcroForm"];
749
750
    // /DA and /Q may be inherited from the document-level /AcroForm dictionary. If we are copying a
751
    // foreign stream and the stream is getting one of these values from its document's /AcroForm,
752
    // we will need to copy the value explicitly so that it doesn't start getting its default from
753
    // the destination document.
754
0
    std::string from_default_da;
755
0
    int from_default_q = 0;
756
    // If we copy any form fields, we will need to merge the source document's /DR into this
757
    // document's /DR.
758
0
    Dictionary from_dr;
759
0
    std::string default_da;
760
0
    int default_q = 0;
761
0
    if (foreign) {
762
0
        if (acroform) {
763
0
            if (acroform["/DA"].isString()) {
764
0
                default_da = acroform["/DA"].getUTF8Value();
765
0
            }
766
0
            if (Integer Q = acroform["/Q"]) {
767
0
                default_q = Q;
768
0
            }
769
0
        }
770
0
        if (from_acroform) {
771
0
            from_dr = from_acroform["/DR"];
772
0
            if (from_dr) {
773
0
                if (!from_dr.indirect()) {
774
0
                    from_dr = from_qpdf->makeIndirectObject(from_dr);
775
0
                }
776
0
                from_dr = qpdf.copyForeignObject(from_dr);
777
0
            }
778
0
            if (from_acroform["/DA"].isString()) {
779
0
                from_default_da = from_acroform["/DA"].getUTF8Value();
780
0
            }
781
0
            if (Integer Q = from_acroform["/Q"]) {
782
0
                from_default_q = Q;
783
0
            }
784
0
        }
785
0
    }
786
0
    const bool override_da = from_acroform ? from_default_da != default_da : false;
787
0
    const bool override_q = from_acroform ? from_default_q != default_q : false;
788
789
    // If we have to merge /DR, we will need a mapping of conflicting keys for rewriting /DA. Set
790
    // this up for lazy initialization in case we encounter any form fields.
791
0
    std::map<std::string, std::map<std::string, std::string>> dr_map;
792
0
    Dictionary dr;
793
794
0
    auto init_dr_map = [&]() {
795
0
        if (!dr) {
796
            // Ensure that we have a /DR that is an indirect
797
            // dictionary object.
798
0
            if (!acroform) {
799
0
                acroform = getOrCreateAcroForm();
800
0
            }
801
0
            dr = acroform["/DR"];
802
0
            if (!dr) {
803
0
                dr = Dictionary::empty();
804
0
            }
805
0
            QPDFObjectHandle(dr).makeResourcesIndirect(qpdf);
806
0
            if (!dr.indirect()) {
807
0
                acroform.replaceKey("/DR", qpdf.makeIndirectObject(dr));
808
0
                dr = acroform["/DR"];
809
0
            }
810
            // Merge the other document's /DR, creating a conflict map. mergeResources checks to
811
            // make sure both objects are dictionaries. By this point, if this is foreign, from_dr
812
            // has been copied, so we use the target qpdf as the owning qpdf.
813
0
            QPDFObjectHandle(from_dr).makeResourcesIndirect(qpdf);
814
0
            QPDFObjectHandle(dr).mergeResources(from_dr, &dr_map);
815
816
0
            if (from_afdh->getNeedAppearances()) {
817
0
                setNeedAppearances(true);
818
0
            }
819
0
        }
820
0
    };
821
822
    // This helper prevents us from copying the same object multiple times.
823
0
    std::map<QPDFObjGen, QPDFObjectHandle> orig_to_copy;
824
0
    auto maybe_copy_object = [&](QPDFObjectHandle& to_copy) {
825
0
        auto og = to_copy.getObjGen();
826
0
        if (orig_to_copy.contains(og)) {
827
0
            to_copy = orig_to_copy[og];
828
0
            return false;
829
0
        } else {
830
0
            to_copy = qpdf.makeIndirectObject(to_copy.shallowCopy());
831
0
            orig_to_copy[og] = to_copy;
832
0
            return true;
833
0
        }
834
0
    };
835
836
    // Traverse the field, copying kids, and preserving integrity.
837
0
    auto traverse_field = [&](QPDFObjectHandle& top_field) -> void {
838
0
        std::deque<Dictionary> queue({top_field});
839
0
        QPDFObjGen::set seen;
840
0
        for (auto it = queue.begin(); it != queue.end(); ++it) {
841
0
            auto& obj = *it;
842
0
            if (seen.add(obj)) {
843
0
                Dictionary parent = obj["/Parent"];
844
0
                if (parent.indirect()) {
845
0
                    auto parent_og = parent.id_gen();
846
0
                    if (orig_to_copy.contains(parent_og)) {
847
0
                        obj.replaceKey("/Parent", orig_to_copy[parent_og]);
848
0
                    } else {
849
0
                        parent.warn(
850
0
                            "while traversing field " + obj.id_gen().unparse(',') +
851
0
                            ", found parent (" + parent_og.unparse(',') +
852
0
                            ") that had not been seen, indicating likely invalid field structure");
853
0
                    }
854
0
                }
855
0
                size_t i = 0;
856
0
                Array Kids = obj["/Kids"];
857
0
                for (auto& kid: Kids) {
858
0
                    if (maybe_copy_object(kid)) {
859
0
                        Kids.set(i, kid);
860
0
                        queue.emplace_back(kid);
861
0
                    }
862
0
                    ++i;
863
0
                }
864
0
                adjustInheritedFields(
865
0
                    obj, override_da, from_default_da, override_q, from_default_q);
866
0
                if (foreign) {
867
                    // Lazily initialize our /DR and the conflict map.
868
0
                    init_dr_map();
869
                    // The spec doesn't say anything about /DR on the field, but lots of writers
870
                    // put one there, and it is frequently the same as the document-level /DR.
871
                    // To avoid having the field's /DR point to information that we are not
872
                    // maintaining, just reset it to that if it exists. Empirical evidence
873
                    // suggests that many readers, including Acrobat, Adobe Acrobat Reader,
874
                    // chrome, firefox, the mac Preview application, and several of the free
875
                    // readers on Linux all ignore /DR at the field level.
876
0
                    if (obj.contains("/DR")) {
877
0
                        obj.replaceKey("/DR", dr);
878
0
                    }
879
0
                    if (obj["/DA"].isString() && !dr_map.empty()) {
880
0
                        adjustDefaultAppearances(obj, dr_map);
881
0
                    }
882
0
                }
883
0
            }
884
0
        }
885
0
    };
886
887
0
    auto transform_annotation =
888
0
        [&](QPDFObjectHandle& annot) -> std::tuple<QPDFObjectHandle, bool, bool> {
889
        // Make copies of annotations and fields down to the appearance streams, preserving all
890
        // internal referential integrity. When the incoming annotations are from a different file,
891
        // we first copy them locally. Then, whether local or foreign, we copy them again so that if
892
        // we bring the same annotation in multiple times (e.g. overlaying a foreign page onto
893
        // multiple local pages or a local page onto multiple other local pages), we don't create
894
        // annotations that are referenced in more than one place. If we did that, the effect of
895
        // applying transformations would be cumulative, which is definitely not what we want.
896
        // Besides, annotations and fields are not intended to be referenced in multiple places.
897
898
        // Determine if this annotation is attached to a form field. If so, the annotation may be
899
        // the same object as the form field, or the form field may have the annotation as a kid. In
900
        // either case, we have to walk up the field structure to find the top-level field. Within
901
        // one iteration through a set of annotations, we don't want to copy the same item more than
902
        // once. For example, suppose we have field A with kids B, C, and D, each of which has
903
        // annotations BA, CA, and DA. When we get to BA, we will find that BA is a kid of B which
904
        // is under A. When we do a copyForeignObject of A, it will also copy everything else
905
        // because of the indirect references. When we clone BA, we will want to clone A and then
906
        // update A's clone's kid to point B's clone and B's clone's parent to point to A's clone.
907
        // The same thing holds for annotations. Next, when we get to CA, we will again discover
908
        // that A is the top, but we don't want to re-copy A. We want CA's clone to be linked to the
909
        // same clone as BA's. Failure to do this will break up things like radio button groups,
910
        // which all have to kids of the same parent.
911
912
0
        auto ffield = from_afdh->getFieldForAnnotation(annot);
913
0
        auto ffield_oh = ffield.getObjectHandle();
914
0
        if (ffield.null()) {
915
0
            return {{}, false, false};
916
0
        }
917
0
        if (ffield_oh.isStream()) {
918
0
            ffield.warn("ignoring form field that's a stream");
919
0
            return {{}, false, false};
920
0
        }
921
0
        if (!ffield_oh.isIndirect()) {
922
0
            ffield.warn("ignoring form field not indirect");
923
0
            return {{}, false, false};
924
0
        }
925
        // A field and its associated annotation can be the same object. This matters because we
926
        // don't want to clone the annotation and field separately in this case.
927
        // Find the top-level field. It may be the field itself.
928
0
        bool have_parent = false;
929
0
        QPDFObjectHandle top_field = ffield.getTopLevelField(&have_parent).getObjectHandle();
930
0
        if (foreign) {
931
            // copyForeignObject returns the same value if called multiple times with the same
932
            // field. Create/retrieve the local copy of the original field. This pulls over
933
            // everything the field references including annotations and appearance streams, but
934
            // it's harmless to call copyForeignObject on them too. They will already be copied,
935
            // so we'll get the right object back.
936
937
            // top_field and ffield_oh are known to be indirect.
938
0
            top_field = qpdf.copyForeignObject(top_field);
939
0
            ffield_oh = qpdf.copyForeignObject(ffield_oh);
940
0
        } else {
941
            // We don't need to add top_field to old_fields if it's foreign because the new copy
942
            // of the foreign field won't be referenced anywhere. It's just the starting point
943
            // for us to make an additional local copy of.
944
0
            old_fields.insert(top_field.getObjGen());
945
0
        }
946
947
0
        if (maybe_copy_object(top_field)) {
948
0
            traverse_field(top_field);
949
0
        }
950
951
        // Now switch to copies. We already switched for top_field
952
0
        maybe_copy_object(ffield_oh);
953
0
        return {top_field, true, have_parent};
954
0
    };
955
956
    // Now do the actual copies.
957
958
0
    QPDFObjGen::set added_new_fields;
959
0
    for (auto annot: old_annots) {
960
0
        if (annot.isStream()) {
961
0
            annot.warn("ignoring annotation that's a stream");
962
0
            continue;
963
0
        }
964
0
        auto [top_field, have_field, have_parent] = transform_annotation(annot);
965
966
0
        QTC::TC(
967
0
            "qpdf",
968
0
            "QPDFAcroFormDocumentHelper copy annotation",
969
0
            (have_field ? 1 : 0) | (foreign ? 2 : 0));
970
0
        if (have_field) {
971
0
            QTC::TC(
972
0
                "qpdf",
973
0
                "QPDFAcroFormDocumentHelper field with parent",
974
0
                (have_parent ? 1 : 0) | (foreign ? 2 : 0));
975
0
        }
976
0
        if (foreign) {
977
0
            if (!annot.isIndirect()) {
978
0
                annot = from_qpdf->makeIndirectObject(annot);
979
0
            }
980
0
            annot = qpdf.copyForeignObject(annot);
981
0
        }
982
0
        maybe_copy_object(annot);
983
984
        // Now we have copies, so we can safely mutate.
985
0
        if (have_field && added_new_fields.add(top_field)) {
986
0
            new_fields.emplace_back(top_field);
987
0
        }
988
0
        new_annots.emplace_back(annot);
989
990
        // Identify and copy any appearance streams
991
992
0
        auto ah = QPDFAnnotationObjectHelper(annot);
993
0
        Dictionary apdict = ah.getAppearanceDictionary();
994
0
        std::vector<QPDFObjectHandle> streams;
995
0
        auto replace_stream = [](auto& dict, auto& key, auto& old) {
996
0
            dict.replaceKey(key, old.copyStream());
997
0
            return dict[key];
998
0
        };
Unexecuted instantiation: QPDFAcroFormDocumentHelper.cc:auto QPDFAcroFormDocumentHelper::transformAnnotations(QPDFObjectHandle, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::set<QPDFObjGen, std::__1::less<QPDFObjGen>, std::__1::allocator<QPDFObjGen> >&, QPDFMatrix const&, QPDF*, QPDFAcroFormDocumentHelper*)::$_0::operator()<qpdf::Dictionary, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, QPDFObjectHandle>(qpdf::Dictionary&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, QPDFObjectHandle&) const
Unexecuted instantiation: QPDFAcroFormDocumentHelper.cc:auto QPDFAcroFormDocumentHelper::transformAnnotations(QPDFObjectHandle, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::set<QPDFObjGen, std::__1::less<QPDFObjGen>, std::__1::allocator<QPDFObjGen> >&, QPDFMatrix const&, QPDF*, QPDFAcroFormDocumentHelper*)::$_0::operator()<QPDFObjectHandle, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, QPDFObjectHandle>(QPDFObjectHandle&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, QPDFObjectHandle&) const
999
1000
0
        for (auto& [key1, value1]: apdict) {
1001
0
            if (value1.isStream()) {
1002
0
                streams.emplace_back(replace_stream(apdict, key1, value1));
1003
0
            } else {
1004
0
                for (auto& [key2, value2]: Dictionary(value1)) {
1005
0
                    if (value2.isStream()) {
1006
0
                        streams.emplace_back(replace_stream(value1, key2, value2));
1007
0
                    }
1008
0
                }
1009
0
            }
1010
0
        }
1011
1012
        // Now we can safely mutate the annotation and its appearance streams.
1013
0
        for (auto& stream: streams) {
1014
0
            Dictionary dict = stream.getDict();
1015
1016
0
            QPDFMatrix apcm;
1017
0
            Array omatrix = dict["/Matrix"];
1018
0
            if (omatrix) {
1019
0
                apcm = QPDFMatrix(QPDFObjectHandle(omatrix).getArrayAsMatrix());
1020
0
            }
1021
0
            apcm.concat(cm);
1022
0
            if (omatrix || apcm != QPDFMatrix()) {
1023
0
                dict.replaceKey("/Matrix", QPDFObjectHandle::newFromMatrix(apcm));
1024
0
            }
1025
0
            Dictionary resources = dict["/Resources"];
1026
0
            if (!dr_map.empty() && resources) {
1027
0
                adjustAppearanceStream(stream, dr_map);
1028
0
            }
1029
0
        }
1030
0
        auto rect = cm.transformRectangle(annot["/Rect"].getArrayAsRectangle());
1031
0
        annot.replaceKey("/Rect", QPDFObjectHandle::newFromRectangle(rect));
1032
0
    }
1033
0
}
1034
1035
void
1036
QPDFAcroFormDocumentHelper::fixCopiedAnnotations(
1037
    QPDFObjectHandle to_page,
1038
    QPDFObjectHandle from_page,
1039
    QPDFAcroFormDocumentHelper& from_afdh,
1040
    std::set<QPDFObjGen>* added_fields)
1041
0
{
1042
0
    auto old_annots = from_page.getKey("/Annots");
1043
0
    if (old_annots.empty() || !old_annots.isArray()) {
1044
0
        return;
1045
0
    }
1046
1047
0
    std::vector<QPDFObjectHandle> new_annots;
1048
0
    std::vector<QPDFObjectHandle> new_fields;
1049
0
    std::set<QPDFObjGen> old_fields;
1050
0
    transformAnnotations(
1051
0
        old_annots,
1052
0
        new_annots,
1053
0
        new_fields,
1054
0
        old_fields,
1055
0
        QPDFMatrix(),
1056
0
        &(from_afdh.getQPDF()),
1057
0
        &from_afdh);
1058
1059
0
    to_page.replaceKey("/Annots", QPDFObjectHandle::newArray(new_annots));
1060
0
    addAndRenameFormFields(new_fields);
1061
0
    if (added_fields) {
1062
0
        for (auto const& f: new_fields) {
1063
0
            added_fields->insert(f.getObjGen());
1064
0
        }
1065
0
    }
1066
0
}