summaryrefslogtreecommitdiff
path: root/core/fpdfapi/edit/fpdf_edit_create.cpp
blob: d0482173bb62ff04331328180d4e8502c6c8af7c (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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/edit/editint.h"

#include <memory>
#include <vector>

#include "core/fpdfapi/edit/cpdf_creator.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_crypto_handler.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
#include "core/fpdfapi/parser/cpdf_name.h"
#include "core/fpdfapi/parser/cpdf_number.h"
#include "core/fpdfapi/parser/cpdf_parser.h"
#include "core/fpdfapi/parser/cpdf_reference.h"
#include "core/fpdfapi/parser/cpdf_security_handler.h"
#include "core/fpdfapi/parser/cpdf_stream.h"
#include "core/fpdfapi/parser/cpdf_stream_acc.h"
#include "core/fpdfapi/parser/cpdf_string.h"
#include "core/fpdfapi/parser/fpdf_parser_decode.h"
#include "core/fpdfapi/parser/fpdf_parser_utility.h"
#include "core/fxcrt/cfx_maybe_owned.h"
#include "core/fxcrt/fx_extension.h"
#include "third_party/base/ptr_util.h"
#include "third_party/base/stl_util.h"

#define PDF_OBJECTSTREAM_MAXLENGTH (256 * 1024)
#define PDF_XREFSTREAM_MAXSIZE 10000

#define FX_GETBYTEOFFSET32(a) 0
#define FX_GETBYTEOFFSET40(a) 0
#define FX_GETBYTEOFFSET48(a) 0
#define FX_GETBYTEOFFSET56(a) 0
#define FX_GETBYTEOFFSET24(a) ((uint8_t)(a >> 24))
#define FX_GETBYTEOFFSET16(a) ((uint8_t)(a >> 16))
#define FX_GETBYTEOFFSET8(a) ((uint8_t)(a >> 8))
#define FX_GETBYTEOFFSET0(a) ((uint8_t)(a))

// TODO(ochang): Make helper for appending "objnum 0 R ".

namespace {

int32_t PDF_CreatorAppendObject(const CPDF_Object* pObj,
                                CFX_FileBufferArchive* pFile,
                                FX_FILESIZE& offset) {
  int32_t len = 0;
  if (!pObj) {
    if (pFile->AppendString(" null") < 0) {
      return -1;
    }
    offset += 5;
    return 1;
  }
  switch (pObj->GetType()) {
    case CPDF_Object::NULLOBJ:
      if (pFile->AppendString(" null") < 0) {
        return -1;
      }
      offset += 5;
      break;
    case CPDF_Object::BOOLEAN:
    case CPDF_Object::NUMBER:
      if (pFile->AppendString(" ") < 0) {
        return -1;
      }
      if ((len = pFile->AppendString(pObj->GetString().AsStringC())) < 0) {
        return -1;
      }
      offset += len + 1;
      break;
    case CPDF_Object::STRING: {
      CFX_ByteString str = pObj->GetString();
      bool bHex = pObj->AsString()->IsHex();
      if ((len = pFile->AppendString(PDF_EncodeString(str, bHex).AsStringC())) <
          0) {
        return -1;
      }
      offset += len;
      break;
    }
    case CPDF_Object::NAME: {
      if (pFile->AppendString("/") < 0) {
        return -1;
      }
      CFX_ByteString str = pObj->GetString();
      if ((len = pFile->AppendString(PDF_NameEncode(str).AsStringC())) < 0) {
        return -1;
      }
      offset += len + 1;
      break;
    }
    case CPDF_Object::REFERENCE: {
      if (pFile->AppendString(" ") < 0)
        return -1;
      if ((len = pFile->AppendDWord(pObj->AsReference()->GetRefObjNum())) < 0)
        return -1;
      if (pFile->AppendString(" 0 R ") < 0)
        return -1;
      offset += len + 6;
      break;
    }
    case CPDF_Object::ARRAY: {
      if (pFile->AppendString("[") < 0) {
        return -1;
      }
      offset += 1;
      const CPDF_Array* p = pObj->AsArray();
      for (size_t i = 0; i < p->GetCount(); i++) {
        CPDF_Object* pElement = p->GetObjectAt(i);
        if (!pElement->IsInline()) {
          if (pFile->AppendString(" ") < 0) {
            return -1;
          }
          if ((len = pFile->AppendDWord(pElement->GetObjNum())) < 0) {
            return -1;
          }
          if (pFile->AppendString(" 0 R") < 0) {
            return -1;
          }
          offset += len + 5;
        } else {
          if (PDF_CreatorAppendObject(pElement, pFile, offset) < 0) {
            return -1;
          }
        }
      }
      if (pFile->AppendString("]") < 0) {
        return -1;
      }
      offset += 1;
      break;
    }
    case CPDF_Object::DICTIONARY: {
      if (pFile->AppendString("<<") < 0) {
        return -1;
      }
      offset += 2;
      const CPDF_Dictionary* p = pObj->AsDictionary();
      for (const auto& it : *p) {
        const CFX_ByteString& key = it.first;
        CPDF_Object* pValue = it.second.get();
        if (pFile->AppendString("/") < 0) {
          return -1;
        }
        if ((len = pFile->AppendString(PDF_NameEncode(key).AsStringC())) < 0) {
          return -1;
        }
        offset += len + 1;
        if (!pValue->IsInline()) {
          if (pFile->AppendString(" ") < 0) {
            return -1;
          }
          if ((len = pFile->AppendDWord(pValue->GetObjNum())) < 0) {
            return -1;
          }
          if (pFile->AppendString(" 0 R") < 0) {
            return -1;
          }
          offset += len + 5;
        } else {
          if (PDF_CreatorAppendObject(pValue, pFile, offset) < 0) {
            return -1;
          }
        }
      }
      if (pFile->AppendString(">>") < 0) {
        return -1;
      }
      offset += 2;
      break;
    }
    case CPDF_Object::STREAM: {
      const CPDF_Stream* p = pObj->AsStream();
      if (PDF_CreatorAppendObject(p->GetDict(), pFile, offset) < 0) {
        return -1;
      }
      if (pFile->AppendString("stream\r\n") < 0) {
        return -1;
      }
      offset += 8;
      auto pAcc = pdfium::MakeRetain<CPDF_StreamAcc>(p);
      pAcc->LoadAllData(true);
      if (pFile->AppendBlock(pAcc->GetData(), pAcc->GetSize()) < 0) {
        return -1;
      }
      offset += pAcc->GetSize();
      if ((len = pFile->AppendString("\r\nendstream")) < 0) {
        return -1;
      }
      offset += len;
      break;
    }
    default:
      ASSERT(false);
      break;
  }
  return 1;
}

int32_t PDF_CreatorWriteTrailer(CPDF_Document* pDocument,
                                CFX_FileBufferArchive* pFile,
                                CPDF_Array* pIDArray) {
  FX_FILESIZE offset = 0;
  int32_t len = 0;
  CPDF_Parser* pParser = pDocument->GetParser();
  if (pParser) {
    CPDF_Dictionary* p = pParser->GetTrailer();
    for (const auto& it : *p) {
      const CFX_ByteString& key = it.first;
      CPDF_Object* pValue = it.second.get();
      if (key == "Encrypt" || key == "Size" || key == "Filter" ||
          key == "Index" || key == "Length" || key == "Prev" || key == "W" ||
          key == "XRefStm" || key == "Type" || key == "ID") {
        continue;
      }
      if (key == "DecodeParms")
        continue;

      if (pFile->AppendString(("/")) < 0) {
        return -1;
      }
      if ((len = pFile->AppendString(PDF_NameEncode(key).AsStringC())) < 0) {
        return -1;
      }
      offset += len + 1;
      if (!pValue->IsInline()) {
        if (pFile->AppendString(" ") < 0) {
          return -1;
        }
        if ((len = pFile->AppendDWord(pValue->GetObjNum())) < 0) {
          return -1;
        }
        if (pFile->AppendString(" 0 R ") < 0) {
          return -1;
        }
        offset += len + 6;
      } else {
        if (PDF_CreatorAppendObject(pValue, pFile, offset) < 0) {
          return -1;
        }
      }
    }
    if (pIDArray) {
      if (pFile->AppendString(("/ID")) < 0) {
        return -1;
      }
      offset += 3;
      if (PDF_CreatorAppendObject(pIDArray, pFile, offset) < 0) {
        return -1;
      }
    }
    return offset;
  }
  if (pFile->AppendString("\r\n/Root ") < 0) {
    return -1;
  }
  if ((len = pFile->AppendDWord(pDocument->GetRoot()->GetObjNum())) < 0) {
    return -1;
  }
  if (pFile->AppendString(" 0 R\r\n") < 0) {
    return -1;
  }
  offset += len + 14;
  if (pDocument->GetInfo()) {
    if (pFile->AppendString("/Info ") < 0) {
      return -1;
    }
    if ((len = pFile->AppendDWord(pDocument->GetInfo()->GetObjNum())) < 0) {
      return -1;
    }
    if (pFile->AppendString(" 0 R\r\n") < 0) {
      return -1;
    }
    offset += len + 12;
  }
  if (pIDArray) {
    if (pFile->AppendString(("/ID")) < 0) {
      return -1;
    }
    offset += 3;
    if (PDF_CreatorAppendObject(pIDArray, pFile, offset) < 0) {
      return -1;
    }
  }
  return offset;
}

int32_t PDF_CreatorWriteEncrypt(const CPDF_Dictionary* pEncryptDict,
                                uint32_t dwObjNum,
                                CFX_FileBufferArchive* pFile) {
  if (!pEncryptDict) {
    return 0;
  }
  ASSERT(pFile);
  FX_FILESIZE offset = 0;
  int32_t len = 0;
  if (pFile->AppendString("/Encrypt") < 0) {
    return -1;
  }
  offset += 8;
  if (pFile->AppendString(" ") < 0) {
    return -1;
  }
  if ((len = pFile->AppendDWord(dwObjNum)) < 0) {
    return -1;
  }
  if (pFile->AppendString(" 0 R ") < 0) {
    return -1;
  }
  offset += len + 6;
  return offset;
}

std::vector<uint8_t> PDF_GenerateFileID(uint32_t dwSeed1, uint32_t dwSeed2) {
  std::vector<uint8_t> buffer(sizeof(uint32_t) * 4);
  uint32_t* pBuffer = reinterpret_cast<uint32_t*>(buffer.data());
  void* pContext = FX_Random_MT_Start(dwSeed1);
  for (int i = 0; i < 2; ++i)
    *pBuffer++ = FX_Random_MT_Generate(pContext);
  FX_Random_MT_Close(pContext);
  pContext = FX_Random_MT_Start(dwSeed2);
  for (int i = 0; i < 2; ++i)
    *pBuffer++ = FX_Random_MT_Generate(pContext);
  FX_Random_MT_Close(pContext);
  return buffer;
}

void AppendIndex0(CFX_ByteTextBuf& buffer, bool bFirstObject) {
  buffer.AppendByte(0);
  buffer.AppendByte(0);
  buffer.AppendByte(0);
  buffer.AppendByte(0);
  buffer.AppendByte(0);
  const uint8_t byte = bFirstObject ? 0xFF : 0;
  buffer.AppendByte(byte);
  buffer.AppendByte(byte);
}

void AppendIndex1(CFX_ByteTextBuf& buffer, FX_FILESIZE offset) {
  buffer.AppendByte(1);
  buffer.AppendByte(FX_GETBYTEOFFSET24(offset));
  buffer.AppendByte(FX_GETBYTEOFFSET16(offset));
  buffer.AppendByte(FX_GETBYTEOFFSET8(offset));
  buffer.AppendByte(FX_GETBYTEOFFSET0(offset));
  buffer.AppendByte(0);
  buffer.AppendByte(0);
}

void AppendIndex2(CFX_ByteTextBuf& buffer, uint32_t objnum, int32_t index) {
  buffer.AppendByte(2);
  buffer.AppendByte(FX_GETBYTEOFFSET24(objnum));
  buffer.AppendByte(FX_GETBYTEOFFSET16(objnum));
  buffer.AppendByte(FX_GETBYTEOFFSET8(objnum));
  buffer.AppendByte(FX_GETBYTEOFFSET0(objnum));
  buffer.AppendByte(FX_GETBYTEOFFSET8(index));
  buffer.AppendByte(FX_GETBYTEOFFSET0(index));
}

bool IsXRefNeedEnd(CPDF_XRefStream* pXRef, uint32_t flag) {
  if (!(flag & FPDFCREATE_INCREMENTAL))
    return false;

  uint32_t iCount = 0;
  for (const auto& pair : pXRef->m_IndexArray)
    iCount += pair.count;

  return iCount >= PDF_XREFSTREAM_MAXSIZE;
}

int32_t OutputIndex(CFX_FileBufferArchive* pFile, FX_FILESIZE offset) {
  if (sizeof(offset) > 4) {
    if (FX_GETBYTEOFFSET32(offset)) {
      if (pFile->AppendByte(FX_GETBYTEOFFSET56(offset)) < 0)
        return -1;
      if (pFile->AppendByte(FX_GETBYTEOFFSET48(offset)) < 0)
        return -1;
      if (pFile->AppendByte(FX_GETBYTEOFFSET40(offset)) < 0)
        return -1;
      if (pFile->AppendByte(FX_GETBYTEOFFSET32(offset)) < 0)
        return -1;
    }
  }
  if (pFile->AppendByte(FX_GETBYTEOFFSET24(offset)) < 0)
    return -1;
  if (pFile->AppendByte(FX_GETBYTEOFFSET16(offset)) < 0)
    return -1;
  if (pFile->AppendByte(FX_GETBYTEOFFSET8(offset)) < 0)
    return -1;
  if (pFile->AppendByte(FX_GETBYTEOFFSET0(offset)) < 0)
    return -1;
  if (pFile->AppendByte(0) < 0)
    return -1;
  return 0;
}

class CPDF_FlateEncoder {
 public:
  CPDF_FlateEncoder(CPDF_Stream* pStream, bool bFlateEncode);
  CPDF_FlateEncoder(const uint8_t* pBuffer,
                    uint32_t size,
                    bool bFlateEncode,
                    bool bXRefStream);
  ~CPDF_FlateEncoder();

  void CloneDict();

  uint32_t m_dwSize;
  CFX_MaybeOwned<uint8_t, FxFreeDeleter> m_pData;
  CFX_MaybeOwned<CPDF_Dictionary> m_pDict;
  CFX_RetainPtr<CPDF_StreamAcc> m_pAcc;
};

void CPDF_FlateEncoder::CloneDict() {
  if (m_pDict.IsOwned())
    return;
  m_pDict = ToDictionary(m_pDict->Clone());
  ASSERT(m_pDict.IsOwned());
}

CPDF_FlateEncoder::CPDF_FlateEncoder(CPDF_Stream* pStream, bool bFlateEncode)
    : m_dwSize(0), m_pAcc(pdfium::MakeRetain<CPDF_StreamAcc>(pStream)) {
  m_pAcc->LoadAllData(true);
  bool bHasFilter = pStream && pStream->HasFilter();
  if (bHasFilter && !bFlateEncode) {
    auto pDestAcc = pdfium::MakeRetain<CPDF_StreamAcc>(pStream);
    pDestAcc->LoadAllData();
    m_dwSize = pDestAcc->GetSize();
    m_pData = pDestAcc->DetachData();
    m_pDict = ToDictionary(pStream->GetDict()->Clone());
    m_pDict->RemoveFor("Filter");
    return;
  }
  if (bHasFilter || !bFlateEncode) {
    m_pData = const_cast<uint8_t*>(m_pAcc->GetData());
    m_dwSize = m_pAcc->GetSize();
    m_pDict = pStream->GetDict();
    return;
  }
  // TODO(thestig): Move to Init() and check return value.
  uint8_t* buffer = nullptr;
  ::FlateEncode(m_pAcc->GetData(), m_pAcc->GetSize(), &buffer, &m_dwSize);
  m_pData = std::unique_ptr<uint8_t, FxFreeDeleter>(buffer);
  m_pDict = ToDictionary(pStream->GetDict()->Clone());
  m_pDict->SetNewFor<CPDF_Number>("Length", static_cast<int>(m_dwSize));
  m_pDict->SetNewFor<CPDF_Name>("Filter", "FlateDecode");
  m_pDict->RemoveFor("DecodeParms");
}

CPDF_FlateEncoder::CPDF_FlateEncoder(const uint8_t* pBuffer,
                                     uint32_t size,
                                     bool bFlateEncode,
                                     bool bXRefStream)
    : m_dwSize(0) {
  if (!bFlateEncode) {
    m_pData = const_cast<uint8_t*>(pBuffer);
    m_dwSize = size;
    return;
  }
  uint8_t* buffer = nullptr;
  // TODO(thestig): Move to Init() and check return value.
  if (bXRefStream)
    ::PngEncode(pBuffer, size, &buffer, &m_dwSize);
  else
    ::FlateEncode(pBuffer, size, &buffer, &m_dwSize);
  m_pData = std::unique_ptr<uint8_t, FxFreeDeleter>(buffer);
}

CPDF_FlateEncoder::~CPDF_FlateEncoder() {}

class CPDF_Encryptor {
 public:
  CPDF_Encryptor(CPDF_CryptoHandler* pHandler,
                 int objnum,
                 uint8_t* src_data,
                 uint32_t src_size);
  ~CPDF_Encryptor();

  uint8_t* m_pData;
  uint32_t m_dwSize;
  bool m_bNewBuf;
};

CPDF_Encryptor::CPDF_Encryptor(CPDF_CryptoHandler* pHandler,
                               int objnum,
                               uint8_t* src_data,
                               uint32_t src_size)
    : m_pData(nullptr), m_dwSize(0), m_bNewBuf(false) {
  if (src_size == 0)
    return;

  if (!pHandler) {
    m_pData = (uint8_t*)src_data;
    m_dwSize = src_size;
    return;
  }
  m_dwSize = pHandler->EncryptGetSize(objnum, 0, src_data, src_size);
  m_pData = FX_Alloc(uint8_t, m_dwSize);
  pHandler->EncryptContent(objnum, 0, src_data, src_size, m_pData, m_dwSize);
  m_bNewBuf = true;
}

CPDF_Encryptor::~CPDF_Encryptor() {
  if (m_bNewBuf)
    FX_Free(m_pData);
}

}  // namespace

CPDF_ObjectStream::CPDF_ObjectStream() : m_dwObjNum(0), m_index(0) {}

CPDF_ObjectStream::~CPDF_ObjectStream() {}

void CPDF_ObjectStream::Start() {
  m_Items.clear();
  m_Buffer.Clear();
  m_dwObjNum = 0;
  m_index = 0;
}

void CPDF_ObjectStream::CompressIndirectObject(uint32_t dwObjNum,
                                               const CPDF_Object* pObj) {
  m_Items.push_back({dwObjNum, m_Buffer.GetLength()});
  m_Buffer << pObj;
}

void CPDF_ObjectStream::CompressIndirectObject(uint32_t dwObjNum,
                                               const uint8_t* pBuffer,
                                               uint32_t dwSize) {
  m_Items.push_back({dwObjNum, m_Buffer.GetLength()});
  m_Buffer.AppendBlock(pBuffer, dwSize);
}

FX_FILESIZE CPDF_ObjectStream::End(CPDF_Creator* pCreator) {
  ASSERT(pCreator);
  if (m_Items.empty())
    return 0;

  CFX_FileBufferArchive* pFile = &pCreator->m_File;
  FX_FILESIZE ObjOffset = pCreator->m_Offset;
  if (!m_dwObjNum) {
    m_dwObjNum = ++pCreator->m_dwLastObjNum;
  }
  CFX_ByteTextBuf tempBuffer;
  for (const auto& pair : m_Items)
    tempBuffer << pair.objnum << " " << pair.offset << " ";

  FX_FILESIZE& offset = pCreator->m_Offset;
  int32_t len = pFile->AppendDWord(m_dwObjNum);
  if (len < 0) {
    return -1;
  }
  offset += len;
  if ((len = pFile->AppendString(" 0 obj\r\n<</Type /ObjStm /N ")) < 0) {
    return -1;
  }
  offset += len;
  uint32_t iCount = pdfium::CollectionSize<uint32_t>(m_Items);
  if ((len = pFile->AppendDWord(iCount)) < 0) {
    return -1;
  }
  offset += len;
  if (pFile->AppendString("/First ") < 0) {
    return -1;
  }
  if ((len = pFile->AppendDWord((uint32_t)tempBuffer.GetLength())) < 0) {
    return -1;
  }
  if (pFile->AppendString("/Length ") < 0) {
    return -1;
  }
  offset += len + 15;

  tempBuffer << m_Buffer;
  CPDF_FlateEncoder encoder(tempBuffer.GetBuffer(), tempBuffer.GetLength(),
                            true, false);
  CPDF_Encryptor encryptor(pCreator->m_pCryptoHandler.Get(), m_dwObjNum,
                           encoder.m_pData.Get(), encoder.m_dwSize);
  if ((len = pFile->AppendDWord(encryptor.m_dwSize)) < 0) {
    return -1;
  }
  offset += len;
  if (pFile->AppendString("/Filter /FlateDecode") < 0) {
    return -1;
  }
  offset += 20;
  if ((len = pFile->AppendString(">>stream\r\n")) < 0) {
    return -1;
  }
  if (pFile->AppendBlock(encryptor.m_pData, encryptor.m_dwSize) < 0) {
    return -1;
  }
  offset += len + encryptor.m_dwSize;
  if ((len = pFile->AppendString("\r\nendstream\r\nendobj\r\n")) < 0) {
    return -1;
  }
  offset += len;
  return ObjOffset;
}

CPDF_XRefStream::CPDF_XRefStream()
    : m_PrevOffset(0), m_dwTempObjNum(0), m_iSeg(0) {}

CPDF_XRefStream::~CPDF_XRefStream() {}

bool CPDF_XRefStream::Start() {
  m_IndexArray.clear();
  m_Buffer.Clear();
  m_iSeg = 0;
  return true;
}
int32_t CPDF_XRefStream::CompressIndirectObject(uint32_t dwObjNum,
                                                const CPDF_Object* pObj,
                                                CPDF_Creator* pCreator) {
  if (!pCreator)
    return 0;

  m_ObjStream.CompressIndirectObject(dwObjNum, pObj);
  if (pdfium::CollectionSize<int32_t>(m_ObjStream.m_Items) <
          pCreator->m_ObjectStreamSize &&
      m_ObjStream.m_Buffer.GetLength() < PDF_OBJECTSTREAM_MAXLENGTH) {
    return 1;
  }
  return EndObjectStream(pCreator);
}
int32_t CPDF_XRefStream::CompressIndirectObject(uint32_t dwObjNum,
                                                const uint8_t* pBuffer,
                                                uint32_t dwSize,
                                                CPDF_Creator* pCreator) {
  if (!pCreator)
    return 0;

  m_ObjStream.CompressIndirectObject(dwObjNum, pBuffer, dwSize);
  if (pdfium::CollectionSize<int32_t>(m_ObjStream.m_Items) <
          pCreator->m_ObjectStreamSize &&
      m_ObjStream.m_Buffer.GetLength() < PDF_OBJECTSTREAM_MAXLENGTH) {
    return 1;
  }
  return EndObjectStream(pCreator);
}

int32_t CPDF_XRefStream::EndObjectStream(CPDF_Creator* pCreator, bool bEOF) {
  FX_FILESIZE objOffset = 0;
  if (bEOF) {
    objOffset = m_ObjStream.End(pCreator);
    if (objOffset < 0) {
      return -1;
    }
  }
  uint32_t& dwObjStmNum = m_ObjStream.m_dwObjNum;
  if (!dwObjStmNum) {
    dwObjStmNum = ++pCreator->m_dwLastObjNum;
  }
  int32_t iSize = pdfium::CollectionSize<int32_t>(m_ObjStream.m_Items);
  size_t iSeg = m_IndexArray.size();
  if (!(pCreator->m_dwFlags & FPDFCREATE_INCREMENTAL)) {
    if (m_dwTempObjNum == 0) {
      AppendIndex0(m_Buffer, true);
      m_dwTempObjNum++;
    }
    uint32_t end_num = m_IndexArray.back().objnum + m_IndexArray.back().count;
    int index = 0;
    for (; m_dwTempObjNum < end_num; m_dwTempObjNum++) {
      auto it = pCreator->m_ObjectOffsets.find(m_dwTempObjNum);
      if (it != pCreator->m_ObjectOffsets.end()) {
        if (index >= iSize ||
            m_dwTempObjNum != m_ObjStream.m_Items[index].objnum) {
          AppendIndex1(m_Buffer, it->second);
        } else {
          AppendIndex2(m_Buffer, dwObjStmNum, index++);
        }
      } else {
        AppendIndex0(m_Buffer, false);
      }
    }
    if (iSize > 0 && bEOF)
      pCreator->m_ObjectOffsets[dwObjStmNum] = objOffset;

    m_iSeg = iSeg;
    if (bEOF) {
      m_ObjStream.Start();
    }
    return 1;
  }
  for (auto it = m_IndexArray.begin() + m_iSeg; it != m_IndexArray.end();
       ++it) {
    for (uint32_t m = it->objnum; m < it->objnum + it->count; ++m) {
      if (m_ObjStream.m_index >= iSize ||
          m != m_ObjStream.m_Items[it - m_IndexArray.begin()].objnum) {
        AppendIndex1(m_Buffer, pCreator->m_ObjectOffsets[m]);
      } else {
        AppendIndex2(m_Buffer, dwObjStmNum, m_ObjStream.m_index++);
      }
    }
  }
  if (iSize > 0 && bEOF) {
    AppendIndex1(m_Buffer, objOffset);
    m_IndexArray.push_back({dwObjStmNum, 1});
    iSeg += 1;
  }
  m_iSeg = iSeg;
  if (bEOF) {
    m_ObjStream.Start();
  }
  return 1;
}
bool CPDF_XRefStream::GenerateXRefStream(CPDF_Creator* pCreator, bool bEOF) {
  FX_FILESIZE offset_tmp = pCreator->m_Offset;
  uint32_t objnum = ++pCreator->m_dwLastObjNum;
  CFX_FileBufferArchive* pFile = &pCreator->m_File;
  bool bIncremental = (pCreator->m_dwFlags & FPDFCREATE_INCREMENTAL) != 0;
  if (bIncremental) {
    AddObjectNumberToIndexArray(objnum);
  } else {
    for (; m_dwTempObjNum < pCreator->m_dwLastObjNum; m_dwTempObjNum++) {
      auto it = pCreator->m_ObjectOffsets.find(m_dwTempObjNum);
      if (it != pCreator->m_ObjectOffsets.end())
        AppendIndex1(m_Buffer, it->second);
      else
        AppendIndex0(m_Buffer, false);
    }
  }

  AppendIndex1(m_Buffer, offset_tmp);
  FX_FILESIZE& offset = pCreator->m_Offset;
  int32_t len = pFile->AppendDWord(objnum);
  if (len < 0) {
    return false;
  }
  offset += len;
  if ((len = pFile->AppendString(" 0 obj\r\n<</Type /XRef/W[1 4 2]/Index[")) <
      0) {
    return false;
  }
  offset += len;
  if (!bIncremental) {
    if ((len = pFile->AppendDWord(0)) < 0) {
      return false;
    }
    if ((len = pFile->AppendString(" ")) < 0) {
      return false;
    }
    offset += len + 1;
    if ((len = pFile->AppendDWord(objnum + 1)) < 0) {
      return false;
    }
    offset += len;
  } else {
    for (const auto& pair : m_IndexArray) {
      if ((len = pFile->AppendDWord(pair.objnum)) < 0) {
        return false;
      }
      if (pFile->AppendString(" ") < 0) {
        return false;
      }
      offset += len + 1;
      if ((len = pFile->AppendDWord(pair.count)) < 0) {
        return false;
      }
      if (pFile->AppendString(" ") < 0) {
        return false;
      }
      offset += len + 1;
    }
  }
  if (pFile->AppendString("]/Size ") < 0) {
    return false;
  }
  if ((len = pFile->AppendDWord(objnum + 1)) < 0) {
    return false;
  }
  offset += len + 7;
  if (m_PrevOffset > 0) {
    if (pFile->AppendString("/Prev ") < 0) {
      return false;
    }
    char offset_buf[20];
    memset(offset_buf, 0, sizeof(offset_buf));
    FXSYS_i64toa(m_PrevOffset, offset_buf, 10);
    int32_t offset_len = (int32_t)FXSYS_strlen(offset_buf);
    if (pFile->AppendBlock(offset_buf, offset_len) < 0) {
      return false;
    }
    offset += offset_len + 6;
  }
  CPDF_FlateEncoder encoder(m_Buffer.GetBuffer(), m_Buffer.GetLength(), true,
                            true);
  if (pFile->AppendString("/Filter /FlateDecode") < 0)
    return false;

  offset += 20;
  if ((len = pFile->AppendString("/DecodeParms<</Columns 7/Predictor 12>>")) <
      0) {
    return false;
  }

  offset += len;
  if (pFile->AppendString("/Length ") < 0)
    return false;

  if ((len = pFile->AppendDWord(encoder.m_dwSize)) < 0)
    return false;

  offset += len + 8;
  if (bEOF) {
    if ((len = PDF_CreatorWriteTrailer(pCreator->m_pDocument, pFile,
                                       pCreator->m_pIDArray.get())) < 0) {
      return false;
    }
    offset += len;
    if (pCreator->m_pEncryptDict) {
      uint32_t dwEncryptObjNum = pCreator->m_pEncryptDict->GetObjNum();
      if (dwEncryptObjNum == 0) {
        dwEncryptObjNum = pCreator->m_dwEncryptObjNum;
      }
      if ((len = PDF_CreatorWriteEncrypt(pCreator->m_pEncryptDict,
                                         dwEncryptObjNum, pFile)) < 0) {
        return false;
      }
      offset += len;
    }
  }
  if ((len = pFile->AppendString(">>stream\r\n")) < 0)
    return false;

  offset += len;
  if (pFile->AppendBlock(encoder.m_pData.Get(), encoder.m_dwSize) < 0)
    return false;

  if ((len = pFile->AppendString("\r\nendstream\r\nendobj\r\n")) < 0)
    return false;

  offset += encoder.m_dwSize + len;
  m_PrevOffset = offset_tmp;
  return true;
}

bool CPDF_XRefStream::End(CPDF_Creator* pCreator, bool bEOF) {
  if (EndObjectStream(pCreator, bEOF) < 0) {
    return false;
  }
  return GenerateXRefStream(pCreator, bEOF);
}
bool CPDF_XRefStream::EndXRefStream(CPDF_Creator* pCreator) {
  if (!(pCreator->m_dwFlags & FPDFCREATE_INCREMENTAL)) {
    AppendIndex0(m_Buffer, true);
    for (uint32_t i = 1; i < pCreator->m_dwLastObjNum + 1; i++) {
      auto it = pCreator->m_ObjectOffsets.find(i);
      if (it != pCreator->m_ObjectOffsets.end())
        AppendIndex1(m_Buffer, it->second);
      else
        AppendIndex0(m_Buffer, false);
    }
  } else {
    for (const auto& pair : m_IndexArray) {
      for (uint32_t j = pair.objnum; j < pair.objnum + pair.count; ++j)
        AppendIndex1(m_Buffer, pCreator->m_ObjectOffsets[j]);
    }
  }
  return GenerateXRefStream(pCreator, false);
}
void CPDF_XRefStream::AddObjectNumberToIndexArray(uint32_t objnum) {
  if (m_IndexArray.empty()) {
    m_IndexArray.push_back({objnum, 1});
    return;
  }
  uint32_t next_objnum = m_IndexArray.back().objnum + m_IndexArray.back().count;
  if (objnum == next_objnum)
    m_IndexArray.back().count += 1;
  else
    m_IndexArray.push_back({objnum, 1});
}

CPDF_Creator::CPDF_Creator(CPDF_Document* pDoc)
    : m_pDocument(pDoc),
      m_pParser(pDoc->GetParser()),
      m_bSecurityChanged(false),
      m_pEncryptDict(m_pParser ? m_pParser->GetEncryptDict() : nullptr),
      m_dwEncryptObjNum(0),
      m_pCryptoHandler(m_pParser ? m_pParser->GetCryptoHandler() : nullptr),
      m_pMetadata(nullptr),
      m_ObjectStreamSize(200),
      m_dwLastObjNum(m_pDocument->GetLastObjNum()),
      m_Offset(0),
      m_SavedOffset(0),
      m_iStage(-1),
      m_dwFlags(0),
      m_CurObjNum(0),
      m_XrefStart(0),
      m_pIDArray(nullptr),
      m_FileVersion(0) {}

CPDF_Creator::~CPDF_Creator() {
  Clear();
}

int32_t CPDF_Creator::WriteIndirectObjectToStream(const CPDF_Object* pObj) {
  if (!m_pXRefStream)
    return 1;

  uint32_t objnum = pObj->GetObjNum();
  if (m_pParser && m_pParser->GetObjectGenNum(objnum) > 0)
    return 1;

  if (pObj->IsNumber())
    return 1;

  CPDF_Dictionary* pDict = pObj->GetDict();
  if (pObj->IsStream()) {
    if (pDict && pDict->GetStringFor("Type") == "XRef")
      return 0;
    return 1;
  }

  if (pDict) {
    if (pDict == m_pDocument->GetRoot() || pDict == m_pEncryptDict)
      return 1;
    if (pDict->IsSignatureDict())
      return 1;
    if (pDict->GetStringFor("Type") == "Page")
      return 1;
  }

  m_pXRefStream->AddObjectNumberToIndexArray(objnum);
  if (m_pXRefStream->CompressIndirectObject(objnum, pObj, this) < 0)
    return -1;
  if (!IsXRefNeedEnd(m_pXRefStream.get(), m_dwFlags))
    return 0;
  if (!m_pXRefStream->End(this))
    return -1;
  if (!m_pXRefStream->Start())
    return -1;
  return 0;
}
int32_t CPDF_Creator::WriteIndirectObjectToStream(uint32_t objnum,
                                                  const uint8_t* pBuffer,
                                                  uint32_t dwSize) {
  if (!m_pXRefStream) {
    return 1;
  }
  m_pXRefStream->AddObjectNumberToIndexArray(objnum);
  int32_t iRet =
      m_pXRefStream->CompressIndirectObject(objnum, pBuffer, dwSize, this);
  if (iRet < 1) {
    return iRet;
  }
  if (!IsXRefNeedEnd(m_pXRefStream.get(), m_dwFlags)) {
    return 0;
  }
  if (!m_pXRefStream->End(this)) {
    return -1;
  }
  if (!m_pXRefStream->Start()) {
    return -1;
  }
  return 0;
}
int32_t CPDF_Creator::AppendObjectNumberToXRef(uint32_t objnum) {
  if (!m_pXRefStream) {
    return 1;
  }
  m_pXRefStream->AddObjectNumberToIndexArray(objnum);
  if (!IsXRefNeedEnd(m_pXRefStream.get(), m_dwFlags)) {
    return 0;
  }
  if (!m_pXRefStream->End(this)) {
    return -1;
  }
  if (!m_pXRefStream->Start()) {
    return -1;
  }
  return 0;
}
int32_t CPDF_Creator::WriteStream(const CPDF_Object* pStream,
                                  uint32_t objnum,
                                  CPDF_CryptoHandler* pCrypto) {
  CPDF_FlateEncoder encoder(const_cast<CPDF_Stream*>(pStream->AsStream()),
                            pStream != m_pMetadata);
  CPDF_Encryptor encryptor(pCrypto, objnum, encoder.m_pData.Get(),
                           encoder.m_dwSize);
  if (static_cast<uint32_t>(encoder.m_pDict->GetIntegerFor("Length")) !=
      encryptor.m_dwSize) {
    encoder.CloneDict();
    encoder.m_pDict->SetNewFor<CPDF_Number>(
        "Length", static_cast<int>(encryptor.m_dwSize));
  }
  if (WriteDirectObj(objnum, encoder.m_pDict.Get()) < 0)
    return -1;

  int len = m_File.AppendString("stream\r\n");
  if (len < 0)
    return -1;

  m_Offset += len;
  if (m_File.AppendBlock(encryptor.m_pData, encryptor.m_dwSize) < 0)
    return -1;

  m_Offset += encryptor.m_dwSize;
  if ((len = m_File.AppendString("\r\nendstream")) < 0)
    return -1;

  m_Offset += len;
  return 1;
}
int32_t CPDF_Creator::WriteIndirectObj(uint32_t objnum,
                                       const CPDF_Object* pObj) {
  int32_t len = m_File.AppendDWord(objnum);
  if (len < 0)
    return -1;

  m_Offset += len;
  if ((len = m_File.AppendString(" 0 obj\r\n")) < 0)
    return -1;

  m_Offset += len;
  if (pObj->IsStream()) {
    CPDF_CryptoHandler* pHandler =
        pObj != m_pMetadata ? m_pCryptoHandler.Get() : nullptr;
    if (WriteStream(pObj, objnum, pHandler) < 0)
      return -1;
  } else {
    if (WriteDirectObj(objnum, pObj) < 0)
      return -1;
  }
  if ((len = m_File.AppendString("\r\nendobj\r\n")) < 0)
    return -1;

  m_Offset += len;
  if (AppendObjectNumberToXRef(objnum) < 0)
    return -1;
  return 0;
}
int32_t CPDF_Creator::WriteIndirectObj(const CPDF_Object* pObj) {
  int32_t iRet = WriteIndirectObjectToStream(pObj);
  if (iRet < 1) {
    return iRet;
  }
  return WriteIndirectObj(pObj->GetObjNum(), pObj);
}
int32_t CPDF_Creator::WriteDirectObj(uint32_t objnum,
                                     const CPDF_Object* pObj,
                                     bool bEncrypt) {
  int32_t len = 0;
  if (!pObj) {
    if (m_File.AppendString(" null") < 0) {
      return -1;
    }
    m_Offset += 5;
    return 1;
  }
  switch (pObj->GetType()) {
    case CPDF_Object::NULLOBJ:
      if (m_File.AppendString(" null") < 0) {
        return -1;
      }
      m_Offset += 5;
      break;
    case CPDF_Object::BOOLEAN:
    case CPDF_Object::NUMBER:
      if (m_File.AppendString(" ") < 0) {
        return -1;
      }
      if ((len = m_File.AppendString(pObj->GetString().AsStringC())) < 0) {
        return -1;
      }
      m_Offset += len + 1;
      break;
    case CPDF_Object::STRING: {
      CFX_ByteString str = pObj->GetString();
      bool bHex = pObj->AsString()->IsHex();
      if (!m_pCryptoHandler || !bEncrypt) {
        CFX_ByteString content = PDF_EncodeString(str, bHex);
        if ((len = m_File.AppendString(content.AsStringC())) < 0) {
          return -1;
        }
        m_Offset += len;
        break;
      }
      CPDF_Encryptor encryptor(m_pCryptoHandler.Get(), objnum,
                               (uint8_t*)str.c_str(), str.GetLength());
      CFX_ByteString content = PDF_EncodeString(
          CFX_ByteString((const char*)encryptor.m_pData, encryptor.m_dwSize),
          bHex);
      if ((len = m_File.AppendString(content.AsStringC())) < 0) {
        return -1;
      }
      m_Offset += len;
      break;
    }
    case CPDF_Object::STREAM: {
      CPDF_FlateEncoder encoder(const_cast<CPDF_Stream*>(pObj->AsStream()),
                                true);
      CPDF_Encryptor encryptor(m_pCryptoHandler.Get(), objnum,
                               encoder.m_pData.Get(), encoder.m_dwSize);
      if (static_cast<uint32_t>(encoder.m_pDict->GetIntegerFor("Length")) !=
          encryptor.m_dwSize) {
        encoder.CloneDict();
        encoder.m_pDict->SetNewFor<CPDF_Number>(
            "Length", static_cast<int>(encryptor.m_dwSize));
      }
      if (WriteDirectObj(objnum, encoder.m_pDict.Get()) < 0)
        return -1;

      if ((len = m_File.AppendString("stream\r\n")) < 0)
        return -1;

      m_Offset += len;
      if (m_File.AppendBlock(encryptor.m_pData, encryptor.m_dwSize) < 0)
        return -1;

      m_Offset += encryptor.m_dwSize;
      if ((len = m_File.AppendString("\r\nendstream")) < 0)
        return -1;

      m_Offset += len;
      break;
    }
    case CPDF_Object::NAME: {
      if (m_File.AppendString("/") < 0) {
        return -1;
      }
      CFX_ByteString str = pObj->GetString();
      if ((len = m_File.AppendString(PDF_NameEncode(str).AsStringC())) < 0) {
        return -1;
      }
      m_Offset += len + 1;
      break;
    }
    case CPDF_Object::REFERENCE: {
      if (m_File.AppendString(" ") < 0)
        return -1;
      if ((len = m_File.AppendDWord(pObj->AsReference()->GetRefObjNum())) < 0)
        return -1;
      if (m_File.AppendString(" 0 R") < 0)
        return -1;
      m_Offset += len + 5;
      break;
    }
    case CPDF_Object::ARRAY: {
      if (m_File.AppendString("[") < 0) {
        return -1;
      }
      m_Offset += 1;
      const CPDF_Array* p = pObj->AsArray();
      for (size_t i = 0; i < p->GetCount(); i++) {
        CPDF_Object* pElement = p->GetObjectAt(i);
        if (!pElement->IsInline()) {
          if (m_File.AppendString(" ") < 0) {
            return -1;
          }
          if ((len = m_File.AppendDWord(pElement->GetObjNum())) < 0) {
            return -1;
          }
          if (m_File.AppendString(" 0 R") < 0) {
            return -1;
          }
          m_Offset += len + 5;
        } else {
          if (WriteDirectObj(objnum, pElement) < 0) {
            return -1;
          }
        }
      }
      if (m_File.AppendString("]") < 0) {
        return -1;
      }
      m_Offset += 1;
      break;
    }
    case CPDF_Object::DICTIONARY: {
      if (!m_pCryptoHandler || pObj == m_pEncryptDict)
        return PDF_CreatorAppendObject(pObj, &m_File, m_Offset);
      if (m_File.AppendString("<<") < 0)
        return -1;

      m_Offset += 2;
      const CPDF_Dictionary* p = pObj->AsDictionary();
      bool bSignDict = p->IsSignatureDict();
      for (const auto& it : *p) {
        bool bSignValue = false;
        const CFX_ByteString& key = it.first;
        CPDF_Object* pValue = it.second.get();
        if (m_File.AppendString("/") < 0) {
          return -1;
        }
        if ((len = m_File.AppendString(PDF_NameEncode(key).AsStringC())) < 0) {
          return -1;
        }
        m_Offset += len + 1;
        if (bSignDict && key == "Contents") {
          bSignValue = true;
        }
        if (!pValue->IsInline()) {
          if (m_File.AppendString(" ") < 0) {
            return -1;
          }
          if ((len = m_File.AppendDWord(pValue->GetObjNum())) < 0) {
            return -1;
          }
          if (m_File.AppendString(" 0 R ") < 0) {
            return -1;
          }
          m_Offset += len + 6;
        } else {
          if (WriteDirectObj(objnum, pValue, !bSignValue) < 0) {
            return -1;
          }
        }
      }
      if (m_File.AppendString(">>") < 0) {
        return -1;
      }
      m_Offset += 2;
      break;
    }
  }
  return 1;
}
int32_t CPDF_Creator::WriteOldIndirectObject(uint32_t objnum) {
  if (m_pParser->IsObjectFreeOrNull(objnum))
    return 0;

  m_ObjectOffsets[objnum] = m_Offset;
  bool bExistInMap = !!m_pDocument->GetIndirectObject(objnum);
  const uint8_t object_type = m_pParser->GetObjectType(objnum);
  bool bObjStm = (object_type == 2) && m_pEncryptDict && !m_pXRefStream;
  if (m_pParser->IsVersionUpdated() || m_bSecurityChanged || bExistInMap ||
      bObjStm) {
    CPDF_Object* pObj = m_pDocument->GetOrParseIndirectObject(objnum);
    if (!pObj) {
      m_ObjectOffsets.erase(objnum);
      return 0;
    }
    if (WriteIndirectObj(pObj)) {
      return -1;
    }
    if (!bExistInMap) {
      m_pDocument->DeleteIndirectObject(objnum);
    }
  } else {
    uint8_t* pBuffer;
    uint32_t size;
    m_pParser->GetIndirectBinary(objnum, pBuffer, size);
    if (!pBuffer) {
      return 0;
    }
    if (object_type == 2) {
      if (m_pXRefStream) {
        if (WriteIndirectObjectToStream(objnum, pBuffer, size) < 0) {
          FX_Free(pBuffer);
          return -1;
        }
      } else {
        int32_t len = m_File.AppendDWord(objnum);
        if (len < 0) {
          return -1;
        }
        if (m_File.AppendString(" 0 obj ") < 0) {
          return -1;
        }
        m_Offset += len + 7;
        if (m_File.AppendBlock(pBuffer, size) < 0) {
          return -1;
        }
        m_Offset += size;
        if (m_File.AppendString("\r\nendobj\r\n") < 0) {
          return -1;
        }
        m_Offset += 10;
      }
    } else {
      if (m_File.AppendBlock(pBuffer, size) < 0) {
        return -1;
      }
      m_Offset += size;
      if (AppendObjectNumberToXRef(objnum) < 0) {
        return -1;
      }
    }
    FX_Free(pBuffer);
  }
  return 1;
}
int32_t CPDF_Creator::WriteOldObjs(IFX_Pause* pPause) {
  uint32_t nLastObjNum = m_pParser->GetLastObjNum();
  if (!m_pParser->IsValidObjectNumber(nLastObjNum))
    return 0;

  for (uint32_t objnum = m_CurObjNum; objnum <= nLastObjNum; ++objnum) {
    int32_t iRet = WriteOldIndirectObject(objnum);
    if (iRet < 0)
      return iRet;

    if (!iRet)
      continue;

    if (pPause && pPause->NeedToPauseNow()) {
      m_CurObjNum = objnum + 1;
      return 1;
    }
  }
  return 0;
}

int32_t CPDF_Creator::WriteNewObjs(bool bIncremental, IFX_Pause* pPause) {
  uint32_t iCount = pdfium::CollectionSize<uint32_t>(m_NewObjNumArray);
  uint32_t index = m_CurObjNum;
  while (index < iCount) {
    uint32_t objnum = m_NewObjNumArray[index];
    CPDF_Object* pObj = m_pDocument->GetIndirectObject(objnum);
    if (!pObj) {
      ++index;
      continue;
    }
    m_ObjectOffsets[objnum] = m_Offset;
    if (WriteIndirectObj(pObj))
      return -1;

    index++;
    if (pPause && pPause->NeedToPauseNow()) {
      m_CurObjNum = index;
      return 1;
    }
  }
  return 0;
}

void CPDF_Creator::InitOldObjNumOffsets() {
  if (!m_pParser)
    return;

  uint32_t j = 0;
  uint32_t dwStart = 0;
  uint32_t dwEnd = m_pParser->GetLastObjNum();
  while (dwStart <= dwEnd) {
    while (dwStart <= dwEnd && m_pParser->IsObjectFreeOrNull(dwStart))
      dwStart++;

    if (dwStart > dwEnd)
      break;

    j = dwStart;
    while (j <= dwEnd && !m_pParser->IsObjectFreeOrNull(j))
      j++;

    dwStart = j;
  }
}

void CPDF_Creator::InitNewObjNumOffsets() {
  bool bIncremental = (m_dwFlags & FPDFCREATE_INCREMENTAL) != 0;
  for (const auto& pair : *m_pDocument) {
    const uint32_t objnum = pair.first;
    const CPDF_Object* pObj = pair.second.get();
    if (bIncremental || pObj->GetObjNum() == CPDF_Object::kInvalidObjNum)
      continue;
    if (m_pParser && m_pParser->IsValidObjectNumber(objnum) &&
        m_pParser->GetObjectType(objnum)) {
      continue;
    }
    m_NewObjNumArray.insert(std::lower_bound(m_NewObjNumArray.begin(),
                                             m_NewObjNumArray.end(), objnum),
                            objnum);
  }
}

int32_t CPDF_Creator::WriteDoc_Stage1(IFX_Pause* pPause) {
  ASSERT(m_iStage > -1 || m_iStage < 20);
  if (m_iStage == 0) {
    if (!m_pParser) {
      m_dwFlags &= ~FPDFCREATE_INCREMENTAL;
    }
    if (m_bSecurityChanged && (m_dwFlags & FPDFCREATE_NO_ORIGINAL) == 0) {
      m_dwFlags &= ~FPDFCREATE_INCREMENTAL;
    }
    CPDF_Dictionary* pDict = m_pDocument->GetRoot();
    m_pMetadata = pDict ? pDict->GetDirectObjectFor("Metadata") : nullptr;
    if (m_dwFlags & FPDFCREATE_OBJECTSTREAM) {
      m_pXRefStream = pdfium::MakeUnique<CPDF_XRefStream>();
      m_pXRefStream->Start();
      if ((m_dwFlags & FPDFCREATE_INCREMENTAL) != 0 && m_pParser) {
        FX_FILESIZE prev = m_pParser->GetLastXRefOffset();
        m_pXRefStream->m_PrevOffset = prev;
      }
    }
    m_iStage = 10;
  }
  if (m_iStage == 10) {
    if ((m_dwFlags & FPDFCREATE_INCREMENTAL) == 0) {
      if (m_File.AppendString("%PDF-1.") < 0) {
        return -1;
      }
      m_Offset += 7;
      int32_t version = 7;
      if (m_FileVersion) {
        version = m_FileVersion;
      } else if (m_pParser) {
        version = m_pParser->GetFileVersion();
      }
      int32_t len = m_File.AppendDWord(version % 10);
      if (len < 0) {
        return -1;
      }
      m_Offset += len;
      if ((len = m_File.AppendString("\r\n%\xA1\xB3\xC5\xD7\r\n")) < 0) {
        return -1;
      }
      m_Offset += len;
      InitOldObjNumOffsets();
      m_iStage = 20;
    } else {
      CFX_RetainPtr<IFX_SeekableReadStream> pSrcFile =
          m_pParser->GetFileAccess();
      m_Offset = pSrcFile->GetSize();
      m_SavedOffset = m_Offset;
      m_iStage = 15;
    }
  }
  if (m_iStage == 15) {
    if ((m_dwFlags & FPDFCREATE_NO_ORIGINAL) == 0 && m_SavedOffset > 0) {
      CFX_RetainPtr<IFX_SeekableReadStream> pSrcFile =
          m_pParser->GetFileAccess();
      std::vector<uint8_t> buffer(4096);
      FX_FILESIZE src_size = m_SavedOffset;
      while (src_size) {
        uint32_t block_size = src_size > 4096 ? 4096 : src_size;
        if (!pSrcFile->ReadBlock(buffer.data(), m_Offset - src_size,
                                 block_size)) {
          return -1;
        }
        if (m_File.AppendBlock(buffer.data(), block_size) < 0)
          return -1;

        src_size -= block_size;
        if (pPause && pPause->NeedToPauseNow()) {
          m_SavedOffset = src_size;
          return 1;
        }
      }
    }
    if ((m_dwFlags & FPDFCREATE_NO_ORIGINAL) == 0 &&
        m_pParser->GetLastXRefOffset() == 0) {
      InitOldObjNumOffsets();
      uint32_t dwEnd = m_pParser->GetLastObjNum();
      bool bObjStm = (m_dwFlags & FPDFCREATE_OBJECTSTREAM) != 0;
      for (uint32_t objnum = 0; objnum <= dwEnd; objnum++) {
        if (m_pParser->IsObjectFreeOrNull(objnum))
          continue;

        m_ObjectOffsets[objnum] = m_pParser->GetObjectPositionOrZero(objnum);
        if (bObjStm) {
          m_pXRefStream->AddObjectNumberToIndexArray(objnum);
        }
      }
      if (bObjStm) {
        m_pXRefStream->EndXRefStream(this);
        m_pXRefStream->Start();
      }
    }
    m_iStage = 20;
  }
  InitNewObjNumOffsets();
  return m_iStage;
}
int32_t CPDF_Creator::WriteDoc_Stage2(IFX_Pause* pPause) {
  ASSERT(m_iStage >= 20 || m_iStage < 30);
  if (m_iStage == 20) {
    if ((m_dwFlags & FPDFCREATE_INCREMENTAL) == 0 && m_pParser) {
      m_CurObjNum = 0;
      m_iStage = 21;
    } else {
      m_iStage = 25;
    }
  }
  if (m_iStage == 21) {
    int32_t iRet = WriteOldObjs(pPause);
    if (iRet) {
      return iRet;
    }
    m_iStage = 25;
  }
  if (m_iStage == 25) {
    m_CurObjNum = 0;
    m_iStage = 26;
  }
  if (m_iStage == 26) {
    int32_t iRet =
        WriteNewObjs((m_dwFlags & FPDFCREATE_INCREMENTAL) != 0, pPause);
    if (iRet) {
      return iRet;
    }
    m_iStage = 27;
  }
  if (m_iStage == 27) {
    if (m_pEncryptDict && m_pEncryptDict->IsInline()) {
      m_dwLastObjNum += 1;
      FX_FILESIZE saveOffset = m_Offset;
      if (WriteIndirectObj(m_dwLastObjNum, m_pEncryptDict) < 0)
        return -1;

      m_ObjectOffsets[m_dwLastObjNum] = saveOffset;
      m_dwEncryptObjNum = m_dwLastObjNum;
      if (m_dwFlags & FPDFCREATE_INCREMENTAL)
        m_NewObjNumArray.push_back(m_dwLastObjNum);
    }
    m_iStage = 80;
  }
  return m_iStage;
}
int32_t CPDF_Creator::WriteDoc_Stage3(IFX_Pause* pPause) {
  ASSERT(m_iStage >= 80 || m_iStage < 90);
  uint32_t dwLastObjNum = m_dwLastObjNum;
  if (m_iStage == 80) {
    m_XrefStart = m_Offset;
    if (m_dwFlags & FPDFCREATE_OBJECTSTREAM) {
      m_pXRefStream->End(this, true);
      m_XrefStart = m_pXRefStream->m_PrevOffset;
      m_iStage = 90;
    } else if ((m_dwFlags & FPDFCREATE_INCREMENTAL) == 0 ||
               !m_pParser->IsXRefStream()) {
      if ((m_dwFlags & FPDFCREATE_INCREMENTAL) == 0 ||
          m_pParser->GetLastXRefOffset() == 0) {
        CFX_ByteString str;
        str = pdfium::ContainsKey(m_ObjectOffsets, 1)
                  ? "xref\r\n"
                  : "xref\r\n0 1\r\n0000000000 65535 f\r\n";
        if (m_File.AppendString(str.AsStringC()) < 0) {
          return -1;
        }
        m_CurObjNum = 1;
        m_iStage = 81;
      } else {
        if (m_File.AppendString("xref\r\n") < 0) {
          return -1;
        }
        m_CurObjNum = 0;
        m_iStage = 82;
      }
    } else {
      m_iStage = 90;
    }
  }
  if (m_iStage == 81) {
    CFX_ByteString str;
    uint32_t i = m_CurObjNum;
    uint32_t j;
    while (i <= dwLastObjNum) {
      while (i <= dwLastObjNum && !pdfium::ContainsKey(m_ObjectOffsets, i))
        i++;

      if (i > dwLastObjNum)
        break;

      j = i;
      while (j <= dwLastObjNum && pdfium::ContainsKey(m_ObjectOffsets, j))
        j++;

      if (i == 1)
        str.Format("0 %d\r\n0000000000 65535 f\r\n", j);
      else
        str.Format("%d %d\r\n", i, j - i);

      if (m_File.AppendBlock(str.c_str(), str.GetLength()) < 0)
        return -1;

      while (i < j) {
        str.Format("%010d 00000 n\r\n", m_ObjectOffsets[i++]);
        if (m_File.AppendBlock(str.c_str(), str.GetLength()) < 0) {
          return -1;
        }
      }
      if (i > dwLastObjNum) {
        break;
      }
      if (pPause && pPause->NeedToPauseNow()) {
        m_CurObjNum = i;
        return 1;
      }
    }
    m_iStage = 90;
  }
  if (m_iStage == 82) {
    CFX_ByteString str;
    uint32_t iCount = pdfium::CollectionSize<uint32_t>(m_NewObjNumArray);
    uint32_t i = m_CurObjNum;
    while (i < iCount) {
      size_t j = i;
      uint32_t objnum = m_NewObjNumArray[i];
      while (j < iCount) {
        if (++j == iCount)
          break;
        uint32_t dwCurrent = m_NewObjNumArray[j];
        if (dwCurrent - objnum > 1)
          break;
        objnum = dwCurrent;
      }
      objnum = m_NewObjNumArray[i];
      if (objnum == 1) {
        str.Format("0 %d\r\n0000000000 65535 f\r\n", j - i + 1);
      } else {
        str.Format("%d %d\r\n", objnum, j - i);
      }
      if (m_File.AppendBlock(str.c_str(), str.GetLength()) < 0) {
        return -1;
      }
      while (i < j) {
        objnum = m_NewObjNumArray[i++];
        str.Format("%010d 00000 n\r\n", m_ObjectOffsets[objnum]);
        if (m_File.AppendBlock(str.c_str(), str.GetLength()) < 0)
          return -1;
      }
      if (pPause && (i % 100) == 0 && pPause->NeedToPauseNow()) {
        m_CurObjNum = i;
        return 1;
      }
    }
    m_iStage = 90;
  }
  return m_iStage;
}

int32_t CPDF_Creator::WriteDoc_Stage4(IFX_Pause* pPause) {
  ASSERT(m_iStage >= 90);
  if ((m_dwFlags & FPDFCREATE_OBJECTSTREAM) == 0) {
    bool bXRefStream =
        (m_dwFlags & FPDFCREATE_INCREMENTAL) != 0 && m_pParser->IsXRefStream();
    if (!bXRefStream) {
      if (m_File.AppendString("trailer\r\n<<") < 0) {
        return -1;
      }
    } else {
      if (m_File.AppendDWord(m_pDocument->GetLastObjNum() + 1) < 0) {
        return -1;
      }
      if (m_File.AppendString(" 0 obj <<") < 0) {
        return -1;
      }
    }
    if (m_pParser) {
      CPDF_Dictionary* p = m_pParser->GetTrailer();
      for (const auto& it : *p) {
        const CFX_ByteString& key = it.first;
        CPDF_Object* pValue = it.second.get();
        // TODO(ochang): Consolidate with similar check in
        // PDF_CreatorWriteTrailer.
        if (key == "Encrypt" || key == "Size" || key == "Filter" ||
            key == "Index" || key == "Length" || key == "Prev" || key == "W" ||
            key == "XRefStm" || key == "ID") {
          continue;
        }
        if (m_File.AppendString(("/")) < 0)
          return -1;
        if (m_File.AppendString(PDF_NameEncode(key).AsStringC()) < 0)
          return -1;
        if (!pValue->IsInline()) {
          if (m_File.AppendString(" ") < 0)
            return -1;
          if (m_File.AppendDWord(pValue->GetObjNum()) < 0)
            return -1;
          if (m_File.AppendString(" 0 R ") < 0)
            return -1;
        } else {
          FX_FILESIZE offset = 0;
          if (PDF_CreatorAppendObject(pValue, &m_File, offset) < 0)
            return -1;
        }
      }
    } else {
      if (m_File.AppendString("\r\n/Root ") < 0)
        return -1;
      if (m_File.AppendDWord(m_pDocument->GetRoot()->GetObjNum()) < 0)
        return -1;
      if (m_File.AppendString(" 0 R\r\n") < 0)
        return -1;
      if (m_pDocument->GetInfo()) {
        if (m_File.AppendString("/Info ") < 0)
          return -1;
        if (m_File.AppendDWord(m_pDocument->GetInfo()->GetObjNum()) < 0)
          return -1;
        if (m_File.AppendString(" 0 R\r\n") < 0)
          return -1;
      }
    }
    if (m_pEncryptDict) {
      if (m_File.AppendString("/Encrypt") < 0)
        return -1;

      uint32_t dwObjNum = m_pEncryptDict->GetObjNum();
      if (dwObjNum == 0)
        dwObjNum = m_pDocument->GetLastObjNum() + 1;
      if (m_File.AppendString(" ") < 0)
        return -1;
      if (m_File.AppendDWord(dwObjNum) < 0)
        return -1;
      if (m_File.AppendString(" 0 R ") < 0)
        return -1;
    }

    if (m_File.AppendString("/Size ") < 0)
      return -1;
    if (m_File.AppendDWord(m_dwLastObjNum + (bXRefStream ? 2 : 1)) < 0)
      return -1;
    if ((m_dwFlags & FPDFCREATE_INCREMENTAL) != 0) {
      FX_FILESIZE prev = m_pParser->GetLastXRefOffset();
      if (prev) {
        if (m_File.AppendString("/Prev ") < 0)
          return -1;

        char offset_buf[20];
        memset(offset_buf, 0, sizeof(offset_buf));
        FXSYS_i64toa(prev, offset_buf, 10);
        if (m_File.AppendBlock(offset_buf, FXSYS_strlen(offset_buf)) < 0)
          return -1;
      }
    }
    if (m_pIDArray) {
      if (m_File.AppendString(("/ID")) < 0)
        return -1;

      FX_FILESIZE offset = 0;
      if (PDF_CreatorAppendObject(m_pIDArray.get(), &m_File, offset) < 0)
        return -1;
    }
    if (!bXRefStream) {
      if (m_File.AppendString(">>") < 0)
        return -1;
    } else {
      if (m_File.AppendString("/W[0 4 1]/Index[") < 0)
        return -1;
      if ((m_dwFlags & FPDFCREATE_INCREMENTAL) != 0 && m_pParser &&
          m_pParser->GetLastXRefOffset() == 0) {
        uint32_t i = 0;
        for (i = 0; i < m_dwLastObjNum; i++) {
          if (!pdfium::ContainsKey(m_ObjectOffsets, i))
            continue;
          if (m_File.AppendDWord(i) < 0)
            return -1;
          if (m_File.AppendString(" 1 ") < 0)
            return -1;
        }
        if (m_File.AppendString("]/Length ") < 0)
          return -1;
        if (m_File.AppendDWord(m_dwLastObjNum * 5) < 0)
          return -1;
        if (m_File.AppendString(">>stream\r\n") < 0)
          return -1;
        for (i = 0; i < m_dwLastObjNum; i++) {
          auto it = m_ObjectOffsets.find(i);
          if (it == m_ObjectOffsets.end())
            continue;
          OutputIndex(&m_File, it->second);
        }
      } else {
        size_t count = m_NewObjNumArray.size();
        size_t i = 0;
        for (i = 0; i < count; i++) {
          if (m_File.AppendDWord(m_NewObjNumArray[i]) < 0)
            return -1;
          if (m_File.AppendString(" 1 ") < 0)
            return -1;
        }
        if (m_File.AppendString("]/Length ") < 0)
          return -1;
        if (m_File.AppendDWord(count * 5) < 0)
          return -1;
        if (m_File.AppendString(">>stream\r\n") < 0)
          return -1;
        for (i = 0; i < count; i++)
          OutputIndex(&m_File, m_ObjectOffsets[m_NewObjNumArray[i]]);
      }
      if (m_File.AppendString("\r\nendstream") < 0)
        return -1;
    }
  }

  if (m_File.AppendString("\r\nstartxref\r\n") < 0)
    return -1;

  char offset_buf[20];
  memset(offset_buf, 0, sizeof(offset_buf));
  FXSYS_i64toa(m_XrefStart, offset_buf, 10);
  if (m_File.AppendBlock(offset_buf, FXSYS_strlen(offset_buf)) < 0)
    return -1;
  if (m_File.AppendString("\r\n%%EOF\r\n") < 0)
    return -1;

  m_File.Flush();
  return m_iStage = 100;
}

void CPDF_Creator::Clear() {
  m_pXRefStream.reset();
  m_File.Clear();
  m_NewObjNumArray.clear();
  m_pIDArray.reset();
}

bool CPDF_Creator::Create(const CFX_RetainPtr<IFX_WriteStream>& pFile,
                          uint32_t flags) {
  m_File.AttachFile(pFile);
  return Create(flags);
}

bool CPDF_Creator::Create(uint32_t flags) {
  m_dwFlags = flags;
  m_iStage = 0;
  m_Offset = 0;
  m_dwLastObjNum = m_pDocument->GetLastObjNum();
  m_ObjectOffsets.clear();
  m_NewObjNumArray.clear();
  InitID();
  if (flags & FPDFCREATE_PROGRESSIVE)
    return true;
  return Continue(nullptr) > -1;
}

void CPDF_Creator::InitID(bool bDefault) {
  CPDF_Array* pOldIDArray = m_pParser ? m_pParser->GetIDArray() : nullptr;
  bool bNewId = !m_pIDArray;
  if (bNewId) {
    m_pIDArray = pdfium::MakeUnique<CPDF_Array>();
    CPDF_Object* pID1 = pOldIDArray ? pOldIDArray->GetObjectAt(0) : nullptr;
    if (pID1) {
      m_pIDArray->Add(pID1->Clone());
    } else {
      std::vector<uint8_t> buffer =
          PDF_GenerateFileID((uint32_t)(uintptr_t) this, m_dwLastObjNum);
      CFX_ByteString bsBuffer(buffer.data(), buffer.size());
      m_pIDArray->AddNew<CPDF_String>(bsBuffer, true);
    }
  }
  if (!bDefault) {
    return;
  }
  if (pOldIDArray) {
    CPDF_Object* pID2 = pOldIDArray->GetObjectAt(1);
    if ((m_dwFlags & FPDFCREATE_INCREMENTAL) && m_pEncryptDict && pID2) {
      m_pIDArray->Add(pID2->Clone());
      return;
    }
    std::vector<uint8_t> buffer =
        PDF_GenerateFileID((uint32_t)(uintptr_t) this, m_dwLastObjNum);
    CFX_ByteString bsBuffer(buffer.data(), buffer.size());
    m_pIDArray->AddNew<CPDF_String>(bsBuffer, true);
    return;
  }
  m_pIDArray->Add(m_pIDArray->GetObjectAt(0)->Clone());
  if (m_pEncryptDict && !pOldIDArray && m_pParser && bNewId) {
    if (m_pEncryptDict->GetStringFor("Filter") == "Standard") {
      CFX_ByteString user_pass = m_pParser->GetPassword();
      uint32_t flag = PDF_ENCRYPT_CONTENT;
      CPDF_SecurityHandler handler;
      handler.OnCreate(m_pEncryptDict, m_pIDArray.get(), user_pass.raw_str(),
                       user_pass.GetLength(), flag);
      m_pCryptoHandler = pdfium::MakeRetain<CPDF_CryptoHandler>();
      m_pCryptoHandler->Init(m_pEncryptDict, &handler);
      m_bSecurityChanged = true;
    }
  }
}
int32_t CPDF_Creator::Continue(IFX_Pause* pPause) {
  if (m_iStage < 0) {
    return m_iStage;
  }
  int32_t iRet = 0;
  while (m_iStage < 100) {
    if (m_iStage < 20) {
      iRet = WriteDoc_Stage1(pPause);
    } else if (m_iStage < 30) {
      iRet = WriteDoc_Stage2(pPause);
    } else if (m_iStage < 90) {
      iRet = WriteDoc_Stage3(pPause);
    } else {
      iRet = WriteDoc_Stage4(pPause);
    }
    if (iRet < m_iStage) {
      break;
    }
  }
  if (iRet < 1 || m_iStage == 100) {
    m_iStage = -1;
    Clear();
    return iRet > 99 ? 0 : (iRet < 1 ? -1 : iRet);
  }
  return m_iStage;
}
bool CPDF_Creator::SetFileVersion(int32_t fileVersion) {
  if (fileVersion < 10 || fileVersion > 17) {
    return false;
  }
  m_FileVersion = fileVersion;
  return true;
}

void CPDF_Creator::RemoveSecurity() {
  m_pCryptoHandler.Reset();
  m_bSecurityChanged = true;
  m_pEncryptDict = nullptr;
}