oxidize-pdf 2.4.3

A pure Rust PDF generation and manipulation library with zero external dependencies
Documentation
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
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
use crate::annotations::Annotation;
use crate::error::Result;
use crate::fonts::type0_parsing::{detect_type0_font, resolve_type0_hierarchy};
use crate::forms::Widget;
use crate::graphics::{GraphicsContext, Image};
use crate::objects::{Array, Dictionary, Object, ObjectReference};
use crate::text::{HeaderFooter, Table, TextContext, TextFlowContext};
use std::collections::{HashMap, HashSet};

/// Page margins in points (1/72 inch).
#[derive(Clone, Debug)]
pub struct Margins {
    /// Left margin
    pub left: f64,
    /// Right margin
    pub right: f64,
    /// Top margin
    pub top: f64,
    /// Bottom margin
    pub bottom: f64,
}

impl Default for Margins {
    fn default() -> Self {
        Self {
            left: 72.0,   // 1 inch
            right: 72.0,  // 1 inch
            top: 72.0,    // 1 inch
            bottom: 72.0, // 1 inch
        }
    }
}

/// A single page in a PDF document.
///
/// Pages have a size (width and height in points), margins, and can contain
/// graphics, text, and images.
///
/// # Example
///
/// ```rust
/// use oxidize_pdf::{Page, Font, Color};
///
/// let mut page = Page::a4();
///
/// // Add text
/// page.text()
///     .set_font(Font::Helvetica, 12.0)
///     .at(100.0, 700.0)
///     .write("Hello World")?;
///
/// // Add graphics
/// page.graphics()
///     .set_fill_color(Color::red())
///     .rect(100.0, 100.0, 200.0, 150.0)
///     .fill();
/// # Ok::<(), oxidize_pdf::PdfError>(())
/// ```
#[derive(Clone)]
pub struct Page {
    width: f64,
    height: f64,
    margins: Margins,
    content: Vec<u8>,
    graphics_context: GraphicsContext,
    text_context: TextContext,
    images: HashMap<String, Image>,
    form_xobjects: HashMap<String, crate::graphics::FormXObject>,
    header: Option<HeaderFooter>,
    footer: Option<HeaderFooter>,
    annotations: Vec<Annotation>,
    coordinate_system: crate::coordinate_system::CoordinateSystem,
    rotation: i32, // Page rotation in degrees (0, 90, 180, 270)
    /// Next MCID (Marked Content ID) for tagged PDF
    next_mcid: u32,
    /// Currently open marked content tags (for nesting validation)
    marked_content_stack: Vec<String>,
    /// Preserved resources from original PDF (for overlay operations)
    /// Contains fonts, XObjects, ColorSpaces, etc. from parsed pages
    preserved_resources: Option<crate::pdf_objects::Dictionary>,
}

impl Page {
    /// Creates a new page with the specified width and height in points.
    ///
    /// Points are 1/72 of an inch.
    pub fn new(width: f64, height: f64) -> Self {
        Self {
            width,
            height,
            margins: Margins::default(),
            content: Vec::new(),
            graphics_context: GraphicsContext::new(),
            text_context: TextContext::new(),
            images: HashMap::new(),
            form_xobjects: HashMap::new(),
            header: None,
            footer: None,
            annotations: Vec::new(),
            coordinate_system: crate::coordinate_system::CoordinateSystem::PdfStandard,
            rotation: 0, // Default to no rotation
            next_mcid: 0,
            marked_content_stack: Vec::new(),
            preserved_resources: None,
        }
    }

    /// Creates a writable Page from a parsed page dictionary.
    ///
    /// This method bridges the gap between the parser (read-only) and writer (writable)
    /// by converting a parsed page into a Page structure that can be modified and saved.
    ///
    /// **IMPORTANT**: This method preserves the existing content stream and resources,
    /// allowing you to overlay new content on top of the existing page content without
    /// manual recreation.
    ///
    /// # Arguments
    ///
    /// * `parsed_page` - Reference to a parsed page from the PDF parser
    ///
    /// # Returns
    ///
    /// A writable `Page` with existing content preserved, ready for modification
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::{PdfReader, PdfDocument};
    /// use oxidize_pdf::Page;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Load existing PDF
    /// let reader = PdfReader::open("input.pdf")?;
    /// let document = PdfDocument::new(reader);
    /// let parsed_page = document.get_page(0)?;
    ///
    /// // Convert to writable page
    /// let mut page = Page::from_parsed(&parsed_page)?;
    ///
    /// // Now you can add content on top of existing content
    /// page.text()
    ///     .set_font(oxidize_pdf::text::Font::Helvetica, 12.0)
    ///     .at(100.0, 100.0)
    ///     .write("Overlaid text")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_parsed(parsed_page: &crate::parser::page_tree::ParsedPage) -> Result<Self> {
        // Extract dimensions from MediaBox
        let media_box = parsed_page.media_box;
        let width = media_box[2] - media_box[0];
        let height = media_box[3] - media_box[1];

        // Extract rotation
        let rotation = parsed_page.rotation;

        // Create base page
        let mut page = Self::new(width, height);
        page.rotation = rotation;

        // TODO: Extract and preserve Resources (fonts, images, XObjects)
        // This requires deeper integration with the parser's resource manager

        // Extract and preserve existing content streams
        // Note: This requires a PdfDocument reference to resolve content streams
        // For now, we mark the content field to indicate it should be preserved
        // The actual content stream extraction will be done when we have access to the reader

        Ok(page)
    }

    /// Creates a writable Page from a parsed page with content stream preservation.
    ///
    /// This is an extended version of `from_parsed()` that requires access to the
    /// PdfDocument to extract and preserve the original content streams.
    ///
    /// # Arguments
    ///
    /// * `parsed_page` - Reference to a parsed page
    /// * `document` - Reference to the PDF document (for content stream resolution)
    ///
    /// # Returns
    ///
    /// A writable `Page` with original content streams preserved
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::{PdfReader, PdfDocument};
    /// use oxidize_pdf::Page;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let reader = PdfReader::open("input.pdf")?;
    /// let document = PdfDocument::new(reader);
    /// let parsed_page = document.get_page(0)?;
    ///
    /// // Convert with content preservation
    /// let mut page = Page::from_parsed_with_content(&parsed_page, &document)?;
    ///
    /// // Original content is preserved, overlay will be added on top
    /// page.text()
    ///     .set_font(oxidize_pdf::text::Font::Helvetica, 12.0)
    ///     .at(100.0, 100.0)
    ///     .write("Overlay text")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_parsed_with_content<R: std::io::Read + std::io::Seek>(
        parsed_page: &crate::parser::page_tree::ParsedPage,
        document: &crate::parser::document::PdfDocument<R>,
    ) -> Result<Self> {
        // Extract dimensions from MediaBox
        let media_box = parsed_page.media_box;
        let width = media_box[2] - media_box[0];
        let height = media_box[3] - media_box[1];

        // Extract rotation
        let rotation = parsed_page.rotation;

        // Create base page
        let mut page = Self::new(width, height);
        page.rotation = rotation;

        // Extract and preserve existing content streams
        let content_streams = parsed_page.content_streams_with_document(document)?;

        // Concatenate all content streams
        let mut preserved_content = Vec::new();
        for stream in content_streams {
            preserved_content.extend_from_slice(&stream);
            // Add a newline between streams for safety
            preserved_content.push(b'\n');
        }

        // Store the original content
        // We'll need to wrap it with q/Q to isolate it when overlaying
        page.content = preserved_content;

        // Extract and preserve Resources (fonts, images, XObjects, etc.)
        if let Some(resources) = parsed_page.get_resources() {
            let mut unified_resources = Self::convert_parser_dict_to_unified(resources);

            // Phase 3.2: Resolve embedded font streams
            // For each font in resources, resolve FontDescriptor and font stream references
            // and embed the stream data directly so writer doesn't need to resolve references
            if let Some(crate::pdf_objects::Object::Dictionary(fonts)) =
                unified_resources.get("Font")
            {
                let fonts_clone = fonts.clone();
                let mut resolved_fonts = crate::pdf_objects::Dictionary::new();

                for (font_name, font_obj) in fonts_clone.iter() {
                    // Step 1: Resolve reference if needed to get actual font dictionary
                    let font_dict = match font_obj {
                        crate::pdf_objects::Object::Reference(id) => {
                            // Resolve reference to get actual font dictionary from document
                            match document.get_object(id.number(), id.generation()) {
                                Ok(resolved_obj) => {
                                    // Convert parser object to unified format
                                    match Self::convert_parser_object_to_unified(&resolved_obj) {
                                        crate::pdf_objects::Object::Dictionary(dict) => dict,
                                        _ => {
                                            // Not a dictionary, keep original reference
                                            resolved_fonts.set(font_name.clone(), font_obj.clone());
                                            continue;
                                        }
                                    }
                                }
                                Err(_) => {
                                    // Resolution failed, keep original reference
                                    resolved_fonts.set(font_name.clone(), font_obj.clone());
                                    continue;
                                }
                            }
                        }
                        crate::pdf_objects::Object::Dictionary(dict) => dict.clone(),
                        _ => {
                            // Neither reference nor dictionary, keep as-is
                            resolved_fonts.set(font_name.clone(), font_obj.clone());
                            continue;
                        }
                    };

                    // Step 2: Now font_dict is guaranteed to be a Dictionary, resolve embedded streams
                    match Self::resolve_font_streams(&font_dict, document) {
                        Ok(resolved_dict) => {
                            resolved_fonts.set(
                                font_name.clone(),
                                crate::pdf_objects::Object::Dictionary(resolved_dict),
                            );
                        }
                        Err(_) => {
                            // If stream resolution fails, keep the resolved dictionary without streams
                            resolved_fonts.set(
                                font_name.clone(),
                                crate::pdf_objects::Object::Dictionary(font_dict),
                            );
                        }
                    }
                }

                // Replace Font dictionary with resolved version
                unified_resources.set(
                    "Font",
                    crate::pdf_objects::Object::Dictionary(resolved_fonts),
                );
            }

            // Phase 3.5: Resolve XObject streams (images, forms)
            // XObjects are critical for PDF content - unresolved references cause blank PDFs
            if let Some(crate::pdf_objects::Object::Dictionary(xobjects)) =
                unified_resources.get("XObject")
            {
                let xobjects_clone = xobjects.clone();
                let mut resolved_xobjects = crate::pdf_objects::Dictionary::new();

                for (xobj_name, xobj_obj) in xobjects_clone.iter() {
                    let resolved = match xobj_obj {
                        crate::pdf_objects::Object::Reference(id) => {
                            // Resolve reference to get actual XObject stream
                            match document.get_object(id.number(), id.generation()) {
                                Ok(resolved_obj) => {
                                    Self::convert_parser_object_to_unified(&resolved_obj)
                                }
                                Err(_) => {
                                    // Resolution failed, keep reference
                                    xobj_obj.clone()
                                }
                            }
                        }
                        _ => xobj_obj.clone(),
                    };
                    resolved_xobjects.set(xobj_name.clone(), resolved);
                }

                unified_resources.set(
                    "XObject",
                    crate::pdf_objects::Object::Dictionary(resolved_xobjects),
                );
            }

            // Phase 3.5: Resolve ExtGState (graphics state parameters)
            if let Some(crate::pdf_objects::Object::Dictionary(extgstates)) =
                unified_resources.get("ExtGState")
            {
                let extgstates_clone = extgstates.clone();
                let mut resolved_extgstates = crate::pdf_objects::Dictionary::new();

                for (gs_name, gs_obj) in extgstates_clone.iter() {
                    let resolved = match gs_obj {
                        crate::pdf_objects::Object::Reference(id) => {
                            match document.get_object(id.number(), id.generation()) {
                                Ok(resolved_obj) => {
                                    Self::convert_parser_object_to_unified(&resolved_obj)
                                }
                                Err(_) => gs_obj.clone(),
                            }
                        }
                        _ => gs_obj.clone(),
                    };
                    resolved_extgstates.set(gs_name.clone(), resolved);
                }

                unified_resources.set(
                    "ExtGState",
                    crate::pdf_objects::Object::Dictionary(resolved_extgstates),
                );
            }

            // Phase 3.5: Resolve ColorSpace references
            if let Some(crate::pdf_objects::Object::Dictionary(colorspaces)) =
                unified_resources.get("ColorSpace")
            {
                let colorspaces_clone = colorspaces.clone();
                let mut resolved_colorspaces = crate::pdf_objects::Dictionary::new();

                for (cs_name, cs_obj) in colorspaces_clone.iter() {
                    let resolved = match cs_obj {
                        crate::pdf_objects::Object::Reference(id) => {
                            match document.get_object(id.number(), id.generation()) {
                                Ok(resolved_obj) => {
                                    Self::convert_parser_object_to_unified(&resolved_obj)
                                }
                                Err(_) => cs_obj.clone(),
                            }
                        }
                        _ => cs_obj.clone(),
                    };
                    resolved_colorspaces.set(cs_name.clone(), resolved);
                }

                unified_resources.set(
                    "ColorSpace",
                    crate::pdf_objects::Object::Dictionary(resolved_colorspaces),
                );
            }

            // Phase 3.5: Resolve Pattern references
            if let Some(crate::pdf_objects::Object::Dictionary(patterns)) =
                unified_resources.get("Pattern")
            {
                let patterns_clone = patterns.clone();
                let mut resolved_patterns = crate::pdf_objects::Dictionary::new();

                for (pat_name, pat_obj) in patterns_clone.iter() {
                    let resolved = match pat_obj {
                        crate::pdf_objects::Object::Reference(id) => {
                            match document.get_object(id.number(), id.generation()) {
                                Ok(resolved_obj) => {
                                    Self::convert_parser_object_to_unified(&resolved_obj)
                                }
                                Err(_) => pat_obj.clone(),
                            }
                        }
                        _ => pat_obj.clone(),
                    };
                    resolved_patterns.set(pat_name.clone(), resolved);
                }

                unified_resources.set(
                    "Pattern",
                    crate::pdf_objects::Object::Dictionary(resolved_patterns),
                );
            }

            // Phase 3.5: Resolve Shading references
            if let Some(crate::pdf_objects::Object::Dictionary(shadings)) =
                unified_resources.get("Shading")
            {
                let shadings_clone = shadings.clone();
                let mut resolved_shadings = crate::pdf_objects::Dictionary::new();

                for (sh_name, sh_obj) in shadings_clone.iter() {
                    let resolved = match sh_obj {
                        crate::pdf_objects::Object::Reference(id) => {
                            match document.get_object(id.number(), id.generation()) {
                                Ok(resolved_obj) => {
                                    Self::convert_parser_object_to_unified(&resolved_obj)
                                }
                                Err(_) => sh_obj.clone(),
                            }
                        }
                        _ => sh_obj.clone(),
                    };
                    resolved_shadings.set(sh_name.clone(), resolved);
                }

                unified_resources.set(
                    "Shading",
                    crate::pdf_objects::Object::Dictionary(resolved_shadings),
                );
            }

            page.preserved_resources = Some(unified_resources);
        }

        Ok(page)
    }

    /// Creates a new A4 page (595 x 842 points).
    pub fn a4() -> Self {
        Self::new(595.0, 842.0)
    }

    /// Creates a new A4 landscape page (842 x 595 points).
    pub fn a4_landscape() -> Self {
        Self::new(842.0, 595.0)
    }

    /// Creates a new US Letter page (612 x 792 points).
    pub fn letter() -> Self {
        Self::new(612.0, 792.0)
    }

    /// Creates a new US Letter landscape page (792 x 612 points).
    pub fn letter_landscape() -> Self {
        Self::new(792.0, 612.0)
    }

    /// Creates a new US Legal page (612 x 1008 points).
    pub fn legal() -> Self {
        Self::new(612.0, 1008.0)
    }

    /// Creates a new US Legal landscape page (1008 x 612 points).
    pub fn legal_landscape() -> Self {
        Self::new(1008.0, 612.0)
    }

    /// Returns a mutable reference to the graphics context for drawing shapes.
    pub fn graphics(&mut self) -> &mut GraphicsContext {
        &mut self.graphics_context
    }

    /// Returns a mutable reference to the text context for adding text.
    pub fn text(&mut self) -> &mut TextContext {
        &mut self.text_context
    }

    pub fn set_margins(&mut self, left: f64, right: f64, top: f64, bottom: f64) {
        self.margins = Margins {
            left,
            right,
            top,
            bottom,
        };
    }

    pub fn margins(&self) -> &Margins {
        &self.margins
    }

    pub fn content_width(&self) -> f64 {
        self.width - self.margins.left - self.margins.right
    }

    pub fn content_height(&self) -> f64 {
        self.height - self.margins.top - self.margins.bottom
    }

    pub fn content_area(&self) -> (f64, f64, f64, f64) {
        (
            self.margins.left,
            self.margins.bottom,
            self.width - self.margins.right,
            self.height - self.margins.top,
        )
    }

    pub fn width(&self) -> f64 {
        self.width
    }

    pub fn height(&self) -> f64 {
        self.height
    }

    /// Get the current coordinate system for this page
    pub fn coordinate_system(&self) -> crate::coordinate_system::CoordinateSystem {
        self.coordinate_system
    }

    /// Set the coordinate system for this page
    pub fn set_coordinate_system(
        &mut self,
        coordinate_system: crate::coordinate_system::CoordinateSystem,
    ) -> &mut Self {
        self.coordinate_system = coordinate_system;
        self
    }

    /// Sets the page rotation in degrees.
    /// Valid values are 0, 90, 180, and 270.
    /// Other values will be normalized to the nearest valid rotation.
    pub fn set_rotation(&mut self, rotation: i32) {
        // Normalize rotation to valid values (0, 90, 180, 270)
        let normalized = rotation.rem_euclid(360); // Ensure positive
        self.rotation = match normalized {
            0..=44 | 316..=360 => 0,
            45..=134 => 90,
            135..=224 => 180,
            225..=315 => 270,
            _ => 0, // Should not happen, but default to 0
        };
    }

    /// Converts a parser Dictionary to unified pdf_objects Dictionary
    fn convert_parser_dict_to_unified(
        parser_dict: &crate::parser::objects::PdfDictionary,
    ) -> crate::pdf_objects::Dictionary {
        use crate::pdf_objects::{Dictionary, Name};

        let mut unified_dict = Dictionary::new();

        for (key, value) in &parser_dict.0 {
            let unified_key = Name::new(key.as_str());
            let unified_value = Self::convert_parser_object_to_unified(value);
            unified_dict.set(unified_key, unified_value);
        }

        unified_dict
    }

    /// Converts a parser PdfObject to unified Object
    fn convert_parser_object_to_unified(
        parser_obj: &crate::parser::objects::PdfObject,
    ) -> crate::pdf_objects::Object {
        use crate::parser::objects::PdfObject;
        use crate::pdf_objects::{Array, BinaryString, Name, Object, ObjectId, Stream};

        match parser_obj {
            PdfObject::Null => Object::Null,
            PdfObject::Boolean(b) => Object::Boolean(*b),
            PdfObject::Integer(i) => Object::Integer(*i),
            PdfObject::Real(f) => Object::Real(*f),
            PdfObject::String(s) => Object::String(BinaryString::new(s.as_bytes().to_vec())),
            PdfObject::Name(n) => Object::Name(Name::new(n.as_str())),
            PdfObject::Array(arr) => {
                let mut unified_arr = Array::new();
                for item in &arr.0 {
                    unified_arr.push(Self::convert_parser_object_to_unified(item));
                }
                Object::Array(unified_arr)
            }
            PdfObject::Dictionary(dict) => {
                Object::Dictionary(Self::convert_parser_dict_to_unified(dict))
            }
            PdfObject::Stream(stream) => {
                let dict = Self::convert_parser_dict_to_unified(&stream.dict);
                let data = stream.data.clone();
                Object::Stream(Stream::new(dict, data))
            }
            PdfObject::Reference(num, gen) => Object::Reference(ObjectId::new(*num, *gen)),
        }
    }

    /// Resolves embedded font streams from a font dictionary (Phase 3.2 + Phase 3.4)
    ///
    /// Takes a font dictionary and resolves any FontDescriptor + FontFile references,
    /// embedding the stream data directly so the writer doesn't need to resolve references.
    ///
    /// For Type0 (composite) fonts, this also resolves the complete hierarchy:
    /// Type0 → DescendantFonts → CIDFont → FontDescriptor → FontFile2/FontFile3
    ///
    /// # Returns
    /// Font dictionary with embedded streams (if font has embedded data),
    /// or original dictionary (if standard font or resolution fails)
    fn resolve_font_streams<R: std::io::Read + std::io::Seek>(
        font_dict: &crate::pdf_objects::Dictionary,
        document: &crate::parser::document::PdfDocument<R>,
    ) -> Result<crate::pdf_objects::Dictionary> {
        use crate::pdf_objects::Object;

        let mut resolved_dict = font_dict.clone();

        // Phase 3.4: Check if this is a Type0 (composite) font
        if detect_type0_font(font_dict) {
            // Create a resolver closure that converts parser objects to unified format
            let resolver =
                |id: crate::pdf_objects::ObjectId| -> Option<crate::pdf_objects::Object> {
                    match document.get_object(id.number(), id.generation()) {
                        Ok(parser_obj) => Some(Self::convert_parser_object_to_unified(&parser_obj)),
                        Err(_) => None,
                    }
                };

            // Resolve the complete Type0 hierarchy
            if let Some(info) = resolve_type0_hierarchy(font_dict, resolver) {
                // Embed the resolved CIDFont as DescendantFonts
                if let Some(cidfont) = info.cidfont_dict {
                    let mut resolved_cidfont = cidfont;

                    // Embed FontDescriptor with resolved font stream
                    if let Some(descriptor) = info.font_descriptor {
                        let mut resolved_descriptor = descriptor;

                        // Embed the font stream directly in FontDescriptor
                        if let Some(stream) = info.font_stream {
                            // Determine which key to use based on font_file_type
                            let key = match info.font_file_type {
                                Some(crate::fonts::type0_parsing::FontFileType::TrueType) => {
                                    "FontFile2"
                                }
                                Some(crate::fonts::type0_parsing::FontFileType::CFF) => "FontFile3",
                                Some(crate::fonts::type0_parsing::FontFileType::Type1) => {
                                    "FontFile"
                                }
                                None => "FontFile2", // Default for CIDFontType2
                            };
                            resolved_descriptor.set(key, Object::Stream(stream));
                        }

                        resolved_cidfont
                            .set("FontDescriptor", Object::Dictionary(resolved_descriptor));
                    }

                    // Replace DescendantFonts array with resolved CIDFont
                    let mut descendants = crate::pdf_objects::Array::new();
                    descendants.push(Object::Dictionary(resolved_cidfont));
                    resolved_dict.set("DescendantFonts", Object::Array(descendants));
                }

                // Embed ToUnicode stream if present
                if let Some(tounicode) = info.tounicode_stream {
                    resolved_dict.set("ToUnicode", Object::Stream(tounicode));
                }
            }

            return Ok(resolved_dict);
        }

        // Original Phase 3.2 logic for simple fonts (Type1, TrueType, etc.)
        // Check if font has a FontDescriptor
        if let Some(Object::Reference(descriptor_id)) = font_dict.get("FontDescriptor") {
            // Resolve FontDescriptor from document
            let descriptor_obj =
                document.get_object(descriptor_id.number(), descriptor_id.generation())?;

            // Convert to unified format
            let descriptor_unified = Self::convert_parser_object_to_unified(&descriptor_obj);

            if let Object::Dictionary(mut descriptor_dict) = descriptor_unified {
                // Check for embedded font streams (FontFile, FontFile2, FontFile3)
                let font_file_keys = ["FontFile", "FontFile2", "FontFile3"];
                let mut stream_resolved = false;

                for key in &font_file_keys {
                    if let Some(Object::Reference(stream_id)) = descriptor_dict.get(*key) {
                        // Resolve font stream from document
                        match document.get_object(stream_id.number(), stream_id.generation()) {
                            Ok(stream_obj) => {
                                // Convert to unified format (includes stream data)
                                let stream_unified =
                                    Self::convert_parser_object_to_unified(&stream_obj);

                                // Replace reference with actual stream object
                                descriptor_dict.set(*key, stream_unified);
                                stream_resolved = true;
                            }
                            Err(_) => {
                                // Resolution failed, keep reference as-is
                                continue;
                            }
                        }
                    }
                }

                // If we resolved any streams, update FontDescriptor in font dictionary
                if stream_resolved {
                    resolved_dict.set("FontDescriptor", Object::Dictionary(descriptor_dict));
                }
            }
        }

        Ok(resolved_dict)
    }

    /// Gets the preserved resources from the original PDF (if any)
    pub fn get_preserved_resources(&self) -> Option<&crate::pdf_objects::Dictionary> {
        self.preserved_resources.as_ref()
    }

    /// Gets the current page rotation in degrees.
    pub fn get_rotation(&self) -> i32 {
        self.rotation
    }

    /// Gets the effective width considering rotation.
    /// For 90° and 270° rotations, returns the height.
    pub fn effective_width(&self) -> f64 {
        match self.rotation {
            90 | 270 => self.height,
            _ => self.width,
        }
    }

    /// Gets the effective height considering rotation.
    /// For 90° and 270° rotations, returns the width.
    pub fn effective_height(&self) -> f64 {
        match self.rotation {
            90 | 270 => self.width,
            _ => self.height,
        }
    }

    pub fn text_flow(&self) -> TextFlowContext {
        TextFlowContext::new(self.width, self.height, self.margins.clone())
    }

    pub fn add_text_flow(&mut self, text_flow: &TextFlowContext) {
        let operations = text_flow.generate_operations();
        self.content.extend_from_slice(&operations);
    }

    pub fn add_image(&mut self, name: impl Into<String>, image: Image) {
        self.images.insert(name.into(), image);
    }

    pub fn draw_image(
        &mut self,
        name: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<()> {
        if self.images.contains_key(name) {
            // Draw the image using the graphics context
            self.graphics_context.draw_image(name, x, y, width, height);
            Ok(())
        } else {
            Err(crate::PdfError::InvalidReference(format!(
                "Image '{name}' not found"
            )))
        }
    }

    pub(crate) fn images(&self) -> &HashMap<String, Image> {
        &self.images
    }

    /// Adds a Form XObject resource to this page.
    /// Used by overlay operations to embed external page content.
    pub(crate) fn add_form_xobject(
        &mut self,
        name: impl Into<String>,
        form: crate::graphics::FormXObject,
    ) {
        self.form_xobjects.insert(name.into(), form);
    }

    /// Returns all Form XObjects registered on this page.
    pub(crate) fn form_xobjects(&self) -> &HashMap<String, crate::graphics::FormXObject> {
        &self.form_xobjects
    }

    /// Appends raw PDF operators to the content stream.
    /// Content appended here renders AFTER the existing page content (on top).
    pub(crate) fn append_raw_content(&mut self, data: &[u8]) {
        self.content.extend_from_slice(data);
    }

    /// Add a table to the page.
    ///
    /// This method renders a table at the specified position using the current
    /// graphics context. The table will be drawn with borders, text, and any
    /// configured styling options.
    ///
    /// # Arguments
    ///
    /// * `table` - The table to render on the page
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxidize_pdf::{Page, text::{Table, TableOptions}};
    ///
    /// let mut page = Page::a4();
    ///
    /// // Create a table with 3 columns
    /// let mut table = Table::new(vec![100.0, 150.0, 100.0]);
    /// table.set_position(50.0, 700.0);
    ///
    /// // Add header row
    /// table.add_header_row(vec![
    ///     "Name".to_string(),
    ///     "Description".to_string(),
    ///     "Price".to_string()
    /// ])?;
    ///
    /// // Add data rows
    /// table.add_row(vec![
    ///     "Item 1".to_string(),
    ///     "First item description".to_string(),
    ///     "$10.00".to_string()
    /// ])?;
    ///
    /// // Render the table on the page
    /// page.add_table(&table)?;
    /// # Ok::<(), oxidize_pdf::PdfError>(())
    /// ```
    pub fn add_table(&mut self, table: &Table) -> Result<()> {
        self.graphics_context.render_table(table)
    }

    /// Get ExtGState resources from the graphics context
    pub fn get_extgstate_resources(
        &self,
    ) -> Option<&std::collections::HashMap<String, crate::graphics::ExtGState>> {
        if self.graphics_context.has_extgstates() {
            Some(self.graphics_context.extgstate_manager().states())
        } else {
            None
        }
    }

    /// Adds an annotation to this page
    pub fn add_annotation(&mut self, annotation: Annotation) {
        self.annotations.push(annotation);
    }

    /// Returns a reference to the annotations
    pub fn annotations(&self) -> &[Annotation] {
        &self.annotations
    }

    /// Returns a mutable reference to the annotations  
    pub fn annotations_mut(&mut self) -> &mut Vec<Annotation> {
        &mut self.annotations
    }

    /// Add a form field widget to the page.
    ///
    /// This method adds a widget annotation and returns the reference ID that
    /// should be used to link the widget to its corresponding form field.
    ///
    /// # Arguments
    ///
    /// * `widget` - The widget to add to the page
    ///
    /// # Returns
    ///
    /// An ObjectReference that should be used to link this widget to a form field
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::{Page, forms::Widget, geometry::{Rectangle, Point}};
    ///
    /// let mut page = Page::a4();
    /// let widget = Widget::new(
    ///     Rectangle::new(Point::new(100.0, 700.0), Point::new(300.0, 720.0))
    /// );
    /// let widget_ref = page.add_form_widget(widget);
    /// ```
    pub fn add_form_widget(&mut self, widget: Widget) -> ObjectReference {
        // Create a placeholder object reference for this widget
        // The actual ObjectId will be assigned by the document writer
        // We use a placeholder ID that doesn't conflict with real ObjectIds
        let widget_ref = ObjectReference::new(
            0, // Placeholder ID - writer will assign the real ID
            0,
        );

        // Convert widget to annotation
        let mut annot = Annotation::new(crate::annotations::AnnotationType::Widget, widget.rect);

        // Add widget-specific properties
        for (key, value) in widget.to_annotation_dict().iter() {
            annot.properties.set(key, value.clone());
        }

        // Add to page's annotations
        self.annotations.push(annot);

        widget_ref
    }

    /// Sets the header for this page.
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxidize_pdf::{Page, text::HeaderFooter};
    ///
    /// let mut page = Page::a4();
    /// page.set_header(HeaderFooter::new_header("Company Report 2024"));
    /// ```
    pub fn set_header(&mut self, header: HeaderFooter) {
        self.header = Some(header);
    }

    /// Sets the footer for this page.
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxidize_pdf::{Page, text::HeaderFooter};
    ///
    /// let mut page = Page::a4();
    /// page.set_footer(HeaderFooter::new_footer("Page {{page_number}} of {{total_pages}}"));
    /// ```
    pub fn set_footer(&mut self, footer: HeaderFooter) {
        self.footer = Some(footer);
    }

    /// Gets a reference to the header if set.
    pub fn header(&self) -> Option<&HeaderFooter> {
        self.header.as_ref()
    }

    /// Gets a reference to the footer if set.
    pub fn footer(&self) -> Option<&HeaderFooter> {
        self.footer.as_ref()
    }

    /// Sets the page content directly.
    ///
    /// This is used internally when processing headers and footers.
    pub(crate) fn set_content(&mut self, content: Vec<u8>) {
        self.content = content;
    }

    pub(crate) fn generate_content(&mut self) -> Result<Vec<u8>> {
        // Generate content with no page info (used for simple pages without headers/footers)
        self.generate_content_with_page_info(None, None, None)
    }

    /// Generates page content with header/footer support.
    ///
    /// This method is used internally by the writer to render pages with
    /// proper page numbering in headers and footers.
    pub(crate) fn generate_content_with_page_info(
        &mut self,
        page_number: Option<usize>,
        total_pages: Option<usize>,
        custom_values: Option<&HashMap<String, String>>,
    ) -> Result<Vec<u8>> {
        let mut final_content = Vec::new();

        // Render header if present
        if let Some(header) = &self.header {
            if let (Some(page_num), Some(total)) = (page_number, total_pages) {
                let header_content =
                    self.render_header_footer(header, page_num, total, custom_values)?;
                final_content.extend_from_slice(&header_content);
            }
        }

        // Add graphics operations
        final_content.extend_from_slice(&self.graphics_context.generate_operations()?);

        // Add text operations
        final_content.extend_from_slice(&self.text_context.generate_operations()?);

        // Add any content that was added via add_text_flow
        // Phase 2.3: Rewrite font references in preserved content if fonts were renamed
        let content_to_add = if let Some(ref preserved_res) = self.preserved_resources {
            // Check if we have preserved fonts that need renaming
            if let Some(fonts_dict) = preserved_res.get("Font") {
                if let crate::pdf_objects::Object::Dictionary(ref fonts) = fonts_dict {
                    // Build font mapping (F1 → OrigF1, Arial → OrigArial, etc.)
                    let mut font_mapping = std::collections::HashMap::new();
                    for (original_name, _) in fonts.iter() {
                        let new_name = format!("Orig{}", original_name.as_str());
                        font_mapping.insert(original_name.as_str().to_string(), new_name);
                    }

                    // Rewrite font references in preserved content
                    if !font_mapping.is_empty() && !self.content.is_empty() {
                        use crate::writer::rewrite_font_references;
                        rewrite_font_references(&self.content, &font_mapping)
                    } else {
                        self.content.clone()
                    }
                } else {
                    self.content.clone()
                }
            } else {
                self.content.clone()
            }
        } else {
            self.content.clone()
        };

        final_content.extend_from_slice(&content_to_add);

        // Render footer if present
        if let Some(footer) = &self.footer {
            if let (Some(page_num), Some(total)) = (page_number, total_pages) {
                let footer_content =
                    self.render_header_footer(footer, page_num, total, custom_values)?;
                final_content.extend_from_slice(&footer_content);
            }
        }

        Ok(final_content)
    }

    /// Renders a header or footer with the given page information.
    fn render_header_footer(
        &self,
        header_footer: &HeaderFooter,
        page_number: usize,
        total_pages: usize,
        custom_values: Option<&HashMap<String, String>>,
    ) -> Result<Vec<u8>> {
        use crate::text::measure_text;

        // Render the content with placeholders replaced
        let content = header_footer.render(page_number, total_pages, custom_values);

        // Calculate text width for alignment
        let text_width = measure_text(
            &content,
            &header_footer.options().font,
            header_footer.options().font_size,
        );

        // Calculate positions
        let x = header_footer.calculate_x_position(self.width, text_width);
        let y = header_footer.calculate_y_position(self.height);

        // Create a temporary text context for the header/footer
        let mut text_ctx = TextContext::new();
        text_ctx
            .set_font(
                header_footer.options().font.clone(),
                header_footer.options().font_size,
            )
            .at(x, y)
            .write(&content)?;

        text_ctx.generate_operations()
    }

    /// Convert page to dictionary for PDF structure
    pub(crate) fn to_dict(&self) -> Dictionary {
        let mut dict = Dictionary::new();

        // MediaBox
        let media_box = Array::from(vec![
            Object::Real(0.0),
            Object::Real(0.0),
            Object::Real(self.width),
            Object::Real(self.height),
        ]);
        dict.set("MediaBox", Object::Array(media_box.into()));

        // Add rotation if not zero
        if self.rotation != 0 {
            dict.set("Rotate", Object::Integer(self.rotation as i64));
        }

        // Resources (empty for now, would include fonts, images, etc.)
        let resources = Dictionary::new();
        dict.set("Resources", Object::Dictionary(resources));

        // Annotations - will be added by the writer with proper object references
        // The Page struct holds the annotation data, but the writer is responsible
        // for creating object references and writing the annotation objects
        //
        // NOTE: We don't add Annots array here anymore because the writer
        // will handle this properly with sequential ObjectIds. The temporary
        // ObjectIds (1000+) were causing invalid references in the final PDF.
        // The writer now handles all ObjectId allocation and writing.

        // Contents would be added by the writer

        dict
    }

    /// Gets all characters used in this page.
    ///
    /// Combines characters from both graphics_context and text_context
    /// to ensure proper font subsetting for custom fonts (fixes issue #97).
    pub(crate) fn get_used_characters(&self) -> Option<HashSet<char>> {
        let graphics_chars = self.graphics_context.get_used_characters();
        let text_chars = self.text_context.get_used_characters();

        match (graphics_chars, text_chars) {
            (None, None) => None,
            (Some(chars), None) | (None, Some(chars)) => Some(chars),
            (Some(mut g_chars), Some(t_chars)) => {
                g_chars.extend(t_chars);
                Some(g_chars)
            }
        }
    }

    // ==================== Tagged PDF / Marked Content Support ====================

    /// Begins a marked content sequence for Tagged PDF
    ///
    /// This adds a BDC (Begin Marked Content with Properties) operator to the content stream
    /// with an MCID (Marked Content ID) property. The MCID connects the content to a
    /// structure element in the structure tree.
    ///
    /// # Returns
    ///
    /// Returns the assigned MCID, which should be added to the corresponding StructureElement
    /// via `StructureElement::add_mcid(page_index, mcid)`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::{Page, structure::{StructTree, StructureElement, StandardStructureType}};
    ///
    /// let mut page = Page::a4();
    /// let mut tree = StructTree::new();
    ///
    /// // Create structure
    /// let doc = StructureElement::new(StandardStructureType::Document);
    /// let doc_idx = tree.set_root(doc);
    /// let mut para = StructureElement::new(StandardStructureType::P);
    ///
    /// // Begin marked content for paragraph
    /// let mcid = page.begin_marked_content("P")?;
    ///
    /// // Add content
    /// page.text().write("Hello, Tagged PDF!")?;
    ///
    /// // End marked content
    /// page.end_marked_content()?;
    ///
    /// // Connect MCID to structure element
    /// para.add_mcid(0, mcid);  // page_index=0, mcid from above
    /// tree.add_child(doc_idx, para).map_err(|e| oxidize_pdf::PdfError::InvalidOperation(e))?;
    /// # Ok::<(), oxidize_pdf::PdfError>(())
    /// ```
    pub fn begin_marked_content(&mut self, tag: &str) -> Result<u32> {
        let mcid = self.next_mcid;
        self.next_mcid += 1;

        // Add BDC operator with MCID property to text context
        // Format: /Tag <</MCID mcid>> BDC
        let bdc_op = format!("/{} <</MCID {}>> BDC\n", tag, mcid);
        self.text_context.append_raw_operation(&bdc_op);

        self.marked_content_stack.push(tag.to_string());

        Ok(mcid)
    }

    /// Ends the current marked content sequence
    ///
    /// This adds an EMC (End Marked Content) operator to close the most recently
    /// opened marked content sequence.
    ///
    /// # Errors
    ///
    /// Returns an error if there is no open marked content sequence.
    pub fn end_marked_content(&mut self) -> Result<()> {
        if self.marked_content_stack.is_empty() {
            return Err(crate::PdfError::InvalidOperation(
                "No marked content sequence to end (EMC without BDC)".to_string(),
            ));
        }

        self.marked_content_stack.pop();

        // Add EMC operator to text context
        self.text_context.append_raw_operation("EMC\n");

        Ok(())
    }

    /// Returns the next MCID that will be assigned
    ///
    /// This is useful for pre-allocating structure elements before adding content.
    pub fn next_mcid(&self) -> u32 {
        self.next_mcid
    }

    /// Returns the current depth of nested marked content
    pub fn marked_content_depth(&self) -> usize {
        self.marked_content_stack.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graphics::Color;
    use crate::text::Font;

    #[test]
    fn test_page_new() {
        let page = Page::new(100.0, 200.0);
        assert_eq!(page.width(), 100.0);
        assert_eq!(page.height(), 200.0);
        assert_eq!(page.margins().left, 72.0);
        assert_eq!(page.margins().right, 72.0);
        assert_eq!(page.margins().top, 72.0);
        assert_eq!(page.margins().bottom, 72.0);
    }

    #[test]
    fn test_page_a4() {
        let page = Page::a4();
        assert_eq!(page.width(), 595.0);
        assert_eq!(page.height(), 842.0);
    }

    #[test]
    fn test_page_letter() {
        let page = Page::letter();
        assert_eq!(page.width(), 612.0);
        assert_eq!(page.height(), 792.0);
    }

    #[test]
    fn test_set_margins() {
        let mut page = Page::a4();
        page.set_margins(10.0, 20.0, 30.0, 40.0);

        assert_eq!(page.margins().left, 10.0);
        assert_eq!(page.margins().right, 20.0);
        assert_eq!(page.margins().top, 30.0);
        assert_eq!(page.margins().bottom, 40.0);
    }

    #[test]
    fn test_content_dimensions() {
        let mut page = Page::new(300.0, 400.0);
        page.set_margins(50.0, 50.0, 50.0, 50.0);

        assert_eq!(page.content_width(), 200.0);
        assert_eq!(page.content_height(), 300.0);
    }

    #[test]
    fn test_content_area() {
        let mut page = Page::new(300.0, 400.0);
        page.set_margins(10.0, 20.0, 30.0, 40.0);

        let (left, bottom, right, top) = page.content_area();
        assert_eq!(left, 10.0);
        assert_eq!(bottom, 40.0);
        assert_eq!(right, 280.0);
        assert_eq!(top, 370.0);
    }

    #[test]
    fn test_graphics_context() {
        let mut page = Page::a4();
        let graphics = page.graphics();
        graphics.set_fill_color(Color::red());
        graphics.rect(100.0, 100.0, 200.0, 150.0);
        graphics.fill();

        // Graphics context should be accessible and modifiable
        assert!(page.generate_content().is_ok());
    }

    #[test]
    fn test_text_context() {
        let mut page = Page::a4();
        let text = page.text();
        text.set_font(Font::Helvetica, 12.0);
        text.at(100.0, 700.0);
        text.write("Hello World").unwrap();

        // Text context should be accessible and modifiable
        assert!(page.generate_content().is_ok());
    }

    #[test]
    fn test_text_flow() {
        let page = Page::a4();
        let text_flow = page.text_flow();

        // Text flow should be created with page dimensions and margins
        // Just verify it can be created
        drop(text_flow);
    }

    #[test]
    fn test_add_text_flow() {
        let mut page = Page::a4();
        let mut text_flow = page.text_flow();
        text_flow.at(100.0, 700.0);
        text_flow.set_font(Font::TimesRoman, 14.0);
        text_flow.write_wrapped("Test text flow").unwrap();

        page.add_text_flow(&text_flow);

        let content = page.generate_content().unwrap();
        assert!(!content.is_empty());
    }

    #[test]
    fn test_add_image() {
        let mut page = Page::a4();
        // Create a minimal valid JPEG with SOF0 header
        let jpeg_data = vec![
            0xFF, 0xD8, // SOI marker
            0xFF, 0xC0, // SOF0 marker
            0x00, 0x11, // Length (17 bytes)
            0x08, // Precision (8 bits)
            0x00, 0x64, // Height (100)
            0x00, 0xC8, // Width (200)
            0x03, // Components (3 = RGB)
            0xFF, 0xD9, // EOI marker
        ];
        let image = Image::from_jpeg_data(jpeg_data).unwrap();

        page.add_image("test_image", image);
        assert!(page.images().contains_key("test_image"));
        assert_eq!(page.images().len(), 1);
    }

    #[test]
    fn test_draw_image() {
        let mut page = Page::a4();
        // Create a minimal valid JPEG with SOF0 header
        let jpeg_data = vec![
            0xFF, 0xD8, // SOI marker
            0xFF, 0xC0, // SOF0 marker
            0x00, 0x11, // Length (17 bytes)
            0x08, // Precision (8 bits)
            0x00, 0x64, // Height (100)
            0x00, 0xC8, // Width (200)
            0x03, // Components (3 = RGB)
            0xFF, 0xD9, // EOI marker
        ];
        let image = Image::from_jpeg_data(jpeg_data).unwrap();

        page.add_image("test_image", image);
        let result = page.draw_image("test_image", 50.0, 50.0, 200.0, 200.0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_draw_nonexistent_image() {
        let mut page = Page::a4();
        let result = page.draw_image("nonexistent", 50.0, 50.0, 200.0, 200.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_generate_content() {
        let mut page = Page::a4();

        // Add some graphics
        page.graphics()
            .set_fill_color(Color::blue())
            .circle(200.0, 400.0, 50.0)
            .fill();

        // Add some text
        page.text()
            .set_font(Font::Courier, 10.0)
            .at(50.0, 650.0)
            .write("Test content")
            .unwrap();

        let content = page.generate_content().unwrap();
        assert!(!content.is_empty());
    }

    #[test]
    fn test_margins_default() {
        let margins = Margins::default();
        assert_eq!(margins.left, 72.0);
        assert_eq!(margins.right, 72.0);
        assert_eq!(margins.top, 72.0);
        assert_eq!(margins.bottom, 72.0);
    }

    #[test]
    fn test_page_clone() {
        let mut page1 = Page::a4();
        page1.set_margins(10.0, 20.0, 30.0, 40.0);
        // Create a minimal valid JPEG with SOF0 header
        let jpeg_data = vec![
            0xFF, 0xD8, // SOI marker
            0xFF, 0xC0, // SOF0 marker
            0x00, 0x11, // Length (17 bytes)
            0x08, // Precision (8 bits)
            0x00, 0x32, // Height (50)
            0x00, 0x32, // Width (50)
            0x03, // Components (3 = RGB)
            0xFF, 0xD9, // EOI marker
        ];
        let image = Image::from_jpeg_data(jpeg_data).unwrap();
        page1.add_image("img1", image);

        let page2 = page1.clone();
        assert_eq!(page2.width(), page1.width());
        assert_eq!(page2.height(), page1.height());
        assert_eq!(page2.margins().left, page1.margins().left);
        assert_eq!(page2.images().len(), page1.images().len());
    }

    #[test]
    fn test_header_footer_basic() {
        use crate::text::HeaderFooter;

        let mut page = Page::a4();

        let header = HeaderFooter::new_header("Test Header");
        let footer = HeaderFooter::new_footer("Test Footer");

        page.set_header(header);
        page.set_footer(footer);

        assert!(page.header().is_some());
        assert!(page.footer().is_some());
        assert_eq!(page.header().unwrap().content(), "Test Header");
        assert_eq!(page.footer().unwrap().content(), "Test Footer");
    }

    #[test]
    fn test_header_footer_with_page_numbers() {
        use crate::text::HeaderFooter;

        let mut page = Page::a4();

        let footer = HeaderFooter::new_footer("Page {{page_number}} of {{total_pages}}");
        page.set_footer(footer);

        // Generate content with page info
        let content = page
            .generate_content_with_page_info(Some(3), Some(10), None)
            .unwrap();
        assert!(!content.is_empty());

        // The content should contain the rendered footer
        let content_str = String::from_utf8_lossy(&content);
        assert!(content_str.contains("Page 3 of 10"));
    }

    #[test]
    fn test_page_content_with_headers_footers() {
        use crate::text::{HeaderFooter, TextAlign};

        let mut page = Page::a4();

        // Add header
        let header = HeaderFooter::new_header("Document Title")
            .with_font(Font::HelveticaBold, 14.0)
            .with_alignment(TextAlign::Center);
        page.set_header(header);

        // Add footer
        let footer = HeaderFooter::new_footer("Page {{page_number}}")
            .with_font(Font::Helvetica, 10.0)
            .with_alignment(TextAlign::Right);
        page.set_footer(footer);

        // Add main content
        page.text()
            .set_font(Font::TimesRoman, 12.0)
            .at(100.0, 700.0)
            .write("Main content here")
            .unwrap();

        // Generate with page info
        let content = page
            .generate_content_with_page_info(Some(1), Some(5), None)
            .unwrap();
        assert!(!content.is_empty());

        // Verify that content was generated (it includes header, main content, and footer)
        // Note: We generate raw PDF content streams here, not the full PDF
        // The content may be in PDF format with operators like BT/ET, Tj, etc.
        assert!(content.len() > 100); // Should have substantial content
    }

    #[test]
    fn test_no_headers_footers() {
        let mut page = Page::a4();

        // No headers/footers set
        assert!(page.header().is_none());
        assert!(page.footer().is_none());

        // Content generation should work without headers/footers
        let content = page
            .generate_content_with_page_info(Some(1), Some(1), None)
            .unwrap();
        assert!(content.is_empty() || !content.is_empty()); // May be empty or contain default content
    }

    #[test]
    fn test_header_footer_custom_values() {
        use crate::text::HeaderFooter;
        use std::collections::HashMap;

        let mut page = Page::a4();

        let header = HeaderFooter::new_header("{{company}} - {{title}}");
        page.set_header(header);

        let mut custom_values = HashMap::new();
        custom_values.insert("company".to_string(), "ACME Corp".to_string());
        custom_values.insert("title".to_string(), "Annual Report".to_string());

        let content = page
            .generate_content_with_page_info(Some(1), Some(1), Some(&custom_values))
            .unwrap();
        let content_str = String::from_utf8_lossy(&content);
        assert!(content_str.contains("ACME Corp - Annual Report"));
    }

    // Integration tests for Page ↔ Document ↔ Writer interactions
    mod integration_tests {
        use super::*;
        use crate::document::Document;
        use crate::writer::PdfWriter;
        use std::fs;
        use tempfile::TempDir;

        #[test]
        fn test_page_document_integration() {
            let mut doc = Document::new();
            doc.set_title("Page Integration Test");

            // Create pages with different sizes
            let page1 = Page::a4();
            let page2 = Page::letter();
            let mut page3 = Page::new(400.0, 600.0);

            // Add content to custom page
            page3.set_margins(20.0, 20.0, 20.0, 20.0);
            page3
                .text()
                .set_font(Font::Helvetica, 14.0)
                .at(50.0, 550.0)
                .write("Custom page content")
                .unwrap();

            doc.add_page(page1);
            doc.add_page(page2);
            doc.add_page(page3);

            assert_eq!(doc.pages.len(), 3);

            // Verify page properties are preserved
            assert_eq!(doc.pages[0].width(), 595.0); // A4
            assert_eq!(doc.pages[1].width(), 612.0); // Letter
            assert_eq!(doc.pages[2].width(), 400.0); // Custom

            // Verify content generation works
            let mut page_copy = doc.pages[2].clone();
            let content = page_copy.generate_content().unwrap();
            assert!(!content.is_empty());
        }

        #[test]
        fn test_page_writer_integration() {
            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("page_writer_test.pdf");

            let mut doc = Document::new();
            doc.set_title("Page Writer Integration");

            // Create a page with complex content
            let mut page = Page::a4();
            page.set_margins(50.0, 50.0, 50.0, 50.0);

            // Add text content
            page.text()
                .set_font(Font::Helvetica, 16.0)
                .at(100.0, 750.0)
                .write("Integration Test Header")
                .unwrap();

            page.text()
                .set_font(Font::TimesRoman, 12.0)
                .at(100.0, 700.0)
                .write("This is body text for the integration test.")
                .unwrap();

            // Add graphics content
            page.graphics()
                .set_fill_color(Color::rgb(0.2, 0.6, 0.9))
                .rect(100.0, 600.0, 200.0, 50.0)
                .fill();

            page.graphics()
                .set_stroke_color(Color::rgb(0.8, 0.2, 0.2))
                .set_line_width(3.0)
                .circle(300.0, 500.0, 40.0)
                .stroke();

            doc.add_page(page);

            // Write to file
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            // Verify file was created and has content
            assert!(file_path.exists());
            let metadata = fs::metadata(&file_path).unwrap();
            assert!(metadata.len() > 1000); // Should be substantial

            // Verify PDF structure (text may be compressed, so check for basic structure)
            let content = fs::read(&file_path).unwrap();
            let content_str = String::from_utf8_lossy(&content);
            assert!(content_str.contains("obj")); // Should contain PDF objects
            assert!(content_str.contains("stream")); // Should contain content streams
        }

        #[test]
        fn test_page_margins_integration() {
            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("margins_test.pdf");

            let mut doc = Document::new();
            doc.set_title("Margins Integration Test");

            // Test different margin configurations
            let mut page1 = Page::a4();
            page1.set_margins(10.0, 20.0, 30.0, 40.0);

            let mut page2 = Page::letter();
            page2.set_margins(72.0, 72.0, 72.0, 72.0); // 1 inch margins

            let mut page3 = Page::new(500.0, 700.0);
            page3.set_margins(0.0, 0.0, 0.0, 0.0); // No margins

            // Add content that uses margin information
            for (i, page) in [&mut page1, &mut page2, &mut page3].iter_mut().enumerate() {
                let (left, bottom, right, top) = page.content_area();

                // Place text at content area boundaries
                page.text()
                    .set_font(Font::Helvetica, 10.0)
                    .at(left, top - 20.0)
                    .write(&format!(
                        "Page {} - Content area: ({:.1}, {:.1}, {:.1}, {:.1})",
                        i + 1,
                        left,
                        bottom,
                        right,
                        top
                    ))
                    .unwrap();

                // Draw border around content area
                page.graphics()
                    .set_stroke_color(Color::rgb(0.5, 0.5, 0.5))
                    .set_line_width(1.0)
                    .rect(left, bottom, right - left, top - bottom)
                    .stroke();
            }

            doc.add_page(page1);
            doc.add_page(page2);
            doc.add_page(page3);

            // Write and verify
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            assert!(file_path.exists());
            let metadata = fs::metadata(&file_path).unwrap();
            assert!(metadata.len() > 500); // Should contain substantial content
        }

        #[test]
        fn test_page_image_integration() {
            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("image_test.pdf");

            let mut doc = Document::new();
            doc.set_title("Image Integration Test");

            let mut page = Page::a4();

            // Create test images
            let jpeg_data1 = vec![
                0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0xC8, 0x03, 0xFF, 0xD9,
            ];
            let image1 = Image::from_jpeg_data(jpeg_data1).unwrap();

            let jpeg_data2 = vec![
                0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x32, 0x00, 0x32, 0x01, 0xFF, 0xD9,
            ];
            let image2 = Image::from_jpeg_data(jpeg_data2).unwrap();

            // Add images to page
            page.add_image("image1", image1);
            page.add_image("image2", image2);

            // Draw images at different positions
            page.draw_image("image1", 100.0, 600.0, 200.0, 100.0)
                .unwrap();
            page.draw_image("image2", 350.0, 600.0, 50.0, 50.0).unwrap();

            // Add text labels
            page.text()
                .set_font(Font::Helvetica, 12.0)
                .at(100.0, 580.0)
                .write("Image 1 (200x100)")
                .unwrap();

            page.text()
                .set_font(Font::Helvetica, 12.0)
                .at(350.0, 580.0)
                .write("Image 2 (50x50)")
                .unwrap();

            // Verify images were added before moving page
            assert_eq!(page.images().len(), 2, "Two images should be added to page");

            doc.add_page(page);

            // Write and verify
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            assert!(file_path.exists());
            let metadata = fs::metadata(&file_path).unwrap();
            assert!(metadata.len() > 500); // Should contain images and text

            // Verify XObject references in PDF
            let content = fs::read(&file_path).unwrap();
            let content_str = String::from_utf8_lossy(&content);

            // Debug: print what we're looking for
            tracing::debug!("PDF size: {} bytes", content.len());
            tracing::debug!("Contains 'XObject': {}", content_str.contains("XObject"));
            tracing::debug!("Contains '/XObject': {}", content_str.contains("/XObject"));

            // Check for image-related content
            if content_str.contains("/Type /Image") || content_str.contains("DCTDecode") {
                tracing::debug!("Found image-related content but no XObject dictionary");
            }

            // Verify XObject is properly written
            assert!(content_str.contains("XObject"));
        }

        #[test]
        fn test_page_text_flow_integration() {
            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("text_flow_test.pdf");

            let mut doc = Document::new();
            doc.set_title("Text Flow Integration Test");

            let mut page = Page::a4();
            page.set_margins(50.0, 50.0, 50.0, 50.0);

            // Create text flow with long content
            let mut text_flow = page.text_flow();
            text_flow.set_font(Font::TimesRoman, 12.0);
            text_flow.at(100.0, 700.0);

            let long_text =
                "This is a long paragraph that should demonstrate text flow capabilities. "
                    .repeat(10);
            text_flow.write_wrapped(&long_text).unwrap();

            // Add the text flow to the page
            page.add_text_flow(&text_flow);

            // Also add regular text
            page.text()
                .set_font(Font::Helvetica, 14.0)
                .at(100.0, 750.0)
                .write("Regular Text Above Text Flow")
                .unwrap();

            doc.add_page(page);

            // Write and verify
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            assert!(file_path.exists());
            let metadata = fs::metadata(&file_path).unwrap();
            assert!(metadata.len() > 1000); // Should contain text content

            // Verify text structure appears in PDF
            let content = fs::read(&file_path).unwrap();
            let content_str = String::from_utf8_lossy(&content);
            assert!(content_str.contains("obj")); // Should contain PDF objects
            assert!(content_str.contains("stream")); // Should contain content streams
        }

        #[test]
        fn test_page_complex_content_integration() {
            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("complex_content_test.pdf");

            let mut doc = Document::new();
            doc.set_title("Complex Content Integration Test");

            let mut page = Page::a4();
            page.set_margins(40.0, 40.0, 40.0, 40.0);

            // Create complex layered content

            // Background graphics
            page.graphics()
                .set_fill_color(Color::rgb(0.95, 0.95, 0.95))
                .rect(50.0, 50.0, 495.0, 742.0)
                .fill();

            // Header section
            page.graphics()
                .set_fill_color(Color::rgb(0.2, 0.4, 0.8))
                .rect(50.0, 750.0, 495.0, 42.0)
                .fill();

            page.text()
                .set_font(Font::HelveticaBold, 18.0)
                .at(60.0, 765.0)
                .write("Complex Content Integration Test")
                .unwrap();

            // Content sections with mixed elements
            let mut y_pos = 700.0;
            for i in 1..=3 {
                // Section header
                page.graphics()
                    .set_fill_color(Color::rgb(0.8, 0.8, 0.9))
                    .rect(60.0, y_pos, 475.0, 20.0)
                    .fill();

                page.text()
                    .set_font(Font::HelveticaBold, 12.0)
                    .at(70.0, y_pos + 5.0)
                    .write(&format!("Section {i}"))
                    .unwrap();

                y_pos -= 30.0;

                // Section content
                page.text()
                    .set_font(Font::TimesRoman, 10.0)
                    .at(70.0, y_pos)
                    .write(&format!(
                        "This is the content for section {i}. It demonstrates mixed content."
                    ))
                    .unwrap();

                // Section graphics
                page.graphics()
                    .set_stroke_color(Color::rgb(0.6, 0.2, 0.2))
                    .set_line_width(2.0)
                    .move_to(70.0, y_pos - 10.0)
                    .line_to(530.0, y_pos - 10.0)
                    .stroke();

                y_pos -= 50.0;
            }

            // Footer
            page.graphics()
                .set_fill_color(Color::rgb(0.3, 0.3, 0.3))
                .rect(50.0, 50.0, 495.0, 30.0)
                .fill();

            page.text()
                .set_font(Font::Helvetica, 10.0)
                .at(60.0, 60.0)
                .write("Generated by oxidize-pdf integration test")
                .unwrap();

            doc.add_page(page);

            // Write and verify
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            assert!(file_path.exists());
            let metadata = fs::metadata(&file_path).unwrap();
            assert!(metadata.len() > 500); // Should contain substantial content

            // Verify content structure (text may be compressed, so check for basic structure)
            let content = fs::read(&file_path).unwrap();
            let content_str = String::from_utf8_lossy(&content);
            assert!(content_str.contains("obj")); // Should contain PDF objects
            assert!(content_str.contains("stream")); // Should contain content streams
            assert!(content_str.contains("endobj")); // Should contain object endings
        }

        #[test]
        fn test_page_content_generation_performance() {
            let mut page = Page::a4();

            // Add many elements to test performance
            for i in 0..100 {
                let y = 800.0 - (i as f64 * 7.0);
                if y > 50.0 {
                    page.text()
                        .set_font(Font::Helvetica, 8.0)
                        .at(50.0, y)
                        .write(&format!("Performance test line {i}"))
                        .unwrap();
                }
            }

            // Add graphics elements
            for i in 0..50 {
                let x = 50.0 + (i as f64 * 10.0);
                if x < 550.0 {
                    page.graphics()
                        .set_fill_color(Color::rgb(0.5, 0.5, 0.8))
                        .rect(x, 400.0, 8.0, 8.0)
                        .fill();
                }
            }

            // Content generation should complete in reasonable time
            let start = std::time::Instant::now();
            let content = page.generate_content().unwrap();
            let duration = start.elapsed();

            assert!(!content.is_empty());
            assert!(duration.as_millis() < 1000); // Should complete within 1 second
        }

        #[test]
        fn test_page_error_handling() {
            let mut page = Page::a4();

            // Test drawing non-existent image
            let result = page.draw_image("nonexistent", 100.0, 100.0, 50.0, 50.0);
            assert!(result.is_err());

            // Test with invalid parameters - should still work
            let result = page.draw_image("still_nonexistent", -100.0, -100.0, 0.0, 0.0);
            assert!(result.is_err());

            // Add an image and test valid drawing
            let jpeg_data = vec![
                0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x32, 0x00, 0x32, 0x01, 0xFF, 0xD9,
            ];
            let image = Image::from_jpeg_data(jpeg_data).unwrap();
            page.add_image("valid_image", image);

            let result = page.draw_image("valid_image", 100.0, 100.0, 50.0, 50.0);
            assert!(result.is_ok());
        }

        #[test]
        fn test_page_memory_management() {
            let mut pages = Vec::new();

            // Create many pages to test memory usage
            for i in 0..100 {
                let mut page = Page::a4();
                page.set_margins(i as f64, i as f64, i as f64, i as f64);

                page.text()
                    .set_font(Font::Helvetica, 12.0)
                    .at(100.0, 700.0)
                    .write(&format!("Page {i}"))
                    .unwrap();

                pages.push(page);
            }

            // All pages should be valid
            assert_eq!(pages.len(), 100);

            // Content generation should work for all pages
            for page in pages.iter_mut() {
                let content = page.generate_content().unwrap();
                assert!(!content.is_empty());
            }
        }

        #[test]
        fn test_page_standard_sizes() {
            let a4 = Page::a4();
            let letter = Page::letter();
            let custom = Page::new(200.0, 300.0);

            // Test standard dimensions
            assert_eq!(a4.width(), 595.0);
            assert_eq!(a4.height(), 842.0);
            assert_eq!(letter.width(), 612.0);
            assert_eq!(letter.height(), 792.0);
            assert_eq!(custom.width(), 200.0);
            assert_eq!(custom.height(), 300.0);

            // Test content areas with default margins
            let a4_content_width = a4.content_width();
            let letter_content_width = letter.content_width();
            let custom_content_width = custom.content_width();

            assert_eq!(a4_content_width, 595.0 - 144.0); // 595 - 2*72
            assert_eq!(letter_content_width, 612.0 - 144.0); // 612 - 2*72
            assert_eq!(custom_content_width, 200.0 - 144.0); // 200 - 2*72
        }

        #[test]
        fn test_header_footer_document_integration() {
            use crate::text::{HeaderFooter, TextAlign};

            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("header_footer_test.pdf");

            let mut doc = Document::new();
            doc.set_title("Header Footer Integration Test");

            // Create multiple pages with headers and footers
            for i in 1..=3 {
                let mut page = Page::a4();

                // Set header
                let header = HeaderFooter::new_header(format!("Chapter {i}"))
                    .with_font(Font::HelveticaBold, 16.0)
                    .with_alignment(TextAlign::Center);
                page.set_header(header);

                // Set footer with page numbers
                let footer = HeaderFooter::new_footer("Page {{page_number}} of {{total_pages}}")
                    .with_font(Font::Helvetica, 10.0)
                    .with_alignment(TextAlign::Center);
                page.set_footer(footer);

                // Add content
                page.text()
                    .set_font(Font::TimesRoman, 12.0)
                    .at(100.0, 700.0)
                    .write(&format!("This is the content of chapter {i}"))
                    .unwrap();

                doc.add_page(page);
            }

            // Write to file
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            // Verify file was created
            assert!(file_path.exists());
            let metadata = fs::metadata(&file_path).unwrap();
            assert!(metadata.len() > 1000);

            // Read and verify content
            let content = fs::read(&file_path).unwrap();
            let content_str = String::from_utf8_lossy(&content);

            // PDF was created successfully and has substantial content
            assert!(content.len() > 2000);
            // Verify basic PDF structure
            assert!(content_str.contains("%PDF"));
            assert!(content_str.contains("endobj"));

            // Note: Content may be compressed, so we can't directly check for text strings
            // The important thing is that the PDF was generated without errors
        }

        #[test]
        fn test_header_footer_alignment_integration() {
            use crate::text::{HeaderFooter, TextAlign};

            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("alignment_test.pdf");

            let mut doc = Document::new();

            let mut page = Page::a4();

            // Left-aligned header
            let header = HeaderFooter::new_header("Left Header")
                .with_font(Font::Helvetica, 12.0)
                .with_alignment(TextAlign::Left)
                .with_margin(50.0);
            page.set_header(header);

            // Right-aligned footer
            let footer = HeaderFooter::new_footer("Right Footer - Page {{page_number}}")
                .with_font(Font::Helvetica, 10.0)
                .with_alignment(TextAlign::Right)
                .with_margin(50.0);
            page.set_footer(footer);

            doc.add_page(page);

            // Write to file
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            assert!(file_path.exists());
        }

        #[test]
        fn test_header_footer_date_time_integration() {
            use crate::text::HeaderFooter;

            let temp_dir = TempDir::new().unwrap();
            let file_path = temp_dir.path().join("date_time_test.pdf");

            let mut doc = Document::new();

            let mut page = Page::a4();

            // Header with date/time
            let header = HeaderFooter::new_header("Report generated on {{date}} at {{time}}")
                .with_font(Font::Helvetica, 11.0);
            page.set_header(header);

            // Footer with year
            let footer =
                HeaderFooter::new_footer("© {{year}} Company Name").with_font(Font::Helvetica, 9.0);
            page.set_footer(footer);

            doc.add_page(page);

            // Write to file
            let mut writer = PdfWriter::new(&file_path).unwrap();
            writer.write_document(&mut doc).unwrap();

            assert!(file_path.exists());

            // Verify the file was created successfully
            let content = fs::read(&file_path).unwrap();
            assert!(content.len() > 500);

            // Verify basic PDF structure
            let content_str = String::from_utf8_lossy(&content);
            assert!(content_str.contains("%PDF"));
            assert!(content_str.contains("endobj"));

            // Note: We can't check for specific text content as it may be compressed
            // The test validates that headers/footers with date placeholders don't cause errors
        }
    }
}

#[cfg(test)]
mod unit_tests {
    use super::*;
    use crate::graphics::Color;
    use crate::text::Font;

    // ============= Constructor Tests =============

    #[test]
    fn test_new_page_dimensions() {
        let page = Page::new(100.0, 200.0);
        assert_eq!(page.width(), 100.0);
        assert_eq!(page.height(), 200.0);
    }

    #[test]
    fn test_a4_page_dimensions() {
        let page = Page::a4();
        assert_eq!(page.width(), 595.0);
        assert_eq!(page.height(), 842.0);
    }

    #[test]
    fn test_letter_page_dimensions() {
        let page = Page::letter();
        assert_eq!(page.width(), 612.0);
        assert_eq!(page.height(), 792.0);
    }

    #[test]
    fn test_legal_page_dimensions() {
        let page = Page::legal();
        assert_eq!(page.width(), 612.0);
        assert_eq!(page.height(), 1008.0);
    }

    // ============= Margins Tests =============

    #[test]
    fn test_default_margins() {
        let page = Page::a4();
        let margins = page.margins();
        assert_eq!(margins.left, 72.0);
        assert_eq!(margins.right, 72.0);
        assert_eq!(margins.top, 72.0);
        assert_eq!(margins.bottom, 72.0);
    }

    #[test]
    fn test_set_margins() {
        let mut page = Page::a4();
        page.set_margins(10.0, 20.0, 30.0, 40.0);

        let margins = page.margins();
        assert_eq!(margins.left, 10.0);
        assert_eq!(margins.right, 20.0);
        assert_eq!(margins.top, 30.0);
        assert_eq!(margins.bottom, 40.0);
    }

    #[test]
    fn test_content_width() {
        let mut page = Page::new(600.0, 800.0);
        page.set_margins(50.0, 50.0, 0.0, 0.0);
        assert_eq!(page.content_width(), 500.0);
    }

    #[test]
    fn test_content_height() {
        let mut page = Page::new(600.0, 800.0);
        page.set_margins(0.0, 0.0, 100.0, 100.0);
        assert_eq!(page.content_height(), 600.0);
    }

    #[test]
    fn test_content_area() {
        let mut page = Page::new(600.0, 800.0);
        page.set_margins(50.0, 60.0, 70.0, 80.0);

        let (x, y, right, top) = page.content_area();
        assert_eq!(x, 50.0); // left margin
        assert_eq!(y, 80.0); // bottom margin
        assert_eq!(right, 540.0); // page width (600) - right margin (60)
        assert_eq!(top, 730.0); // page height (800) - top margin (70)
    }

    // ============= Graphics Context Tests =============

    #[test]
    fn test_graphics_context_access() {
        let mut page = Page::a4();
        let gc = page.graphics();

        // Test that we can perform basic operations
        gc.move_to(0.0, 0.0);
        gc.line_to(100.0, 100.0);

        // Operations should be recorded
        let ops = gc.get_operations();
        assert!(!ops.is_empty());
    }

    #[test]
    fn test_graphics_operations_chain() {
        let mut page = Page::a4();

        page.graphics()
            .set_fill_color(Color::red())
            .rectangle(10.0, 10.0, 100.0, 50.0)
            .fill();

        let ops = page.graphics().get_operations();
        assert!(ops.contains("re")); // rectangle operator
        assert!(ops.contains("f")); // fill operator
    }

    // ============= Text Context Tests =============

    #[test]
    fn test_text_context_access() {
        let mut page = Page::a4();
        let tc = page.text();

        tc.set_font(Font::Helvetica, 12.0);
        tc.at(100.0, 100.0);

        // Should be able to write text without error
        let result = tc.write("Test text");
        assert!(result.is_ok());
    }

    // Issue #97: Test that get_used_characters combines both contexts
    #[test]
    fn test_get_used_characters_from_text_context() {
        let mut page = Page::a4();

        // Write text via text_context
        page.text().write("ABC").unwrap();

        // Should capture characters from text_context
        let chars = page.get_used_characters();
        assert!(chars.is_some());
        let chars = chars.unwrap();
        assert!(chars.contains(&'A'));
        assert!(chars.contains(&'B'));
        assert!(chars.contains(&'C'));
    }

    #[test]
    fn test_get_used_characters_combines_both_contexts() {
        let mut page = Page::a4();

        // Write text via text_context
        page.text().write("AB").unwrap();

        // Write text via graphics_context
        let _ = page.graphics().draw_text("CD", 100.0, 100.0);

        // Should capture characters from both contexts
        let chars = page.get_used_characters();
        assert!(chars.is_some());
        let chars = chars.unwrap();
        assert!(chars.contains(&'A'));
        assert!(chars.contains(&'B'));
        assert!(chars.contains(&'C'));
        assert!(chars.contains(&'D'));
    }

    #[test]
    fn test_get_used_characters_cjk_via_text_context() {
        let mut page = Page::a4();

        // Write CJK text via text_context (the bug scenario from issue #97)
        page.text()
            .set_font(Font::Custom("NotoSansCJK".to_string()), 12.0);
        page.text().write("中文").unwrap();

        let chars = page.get_used_characters();
        assert!(chars.is_some());
        let chars = chars.unwrap();
        assert!(chars.contains(&'中'));
        assert!(chars.contains(&'æ–‡'));
    }

    #[test]
    fn test_text_flow_creation() {
        let page = Page::a4();
        let text_flow = page.text_flow();

        // Test that text flow is created without panic
        // TextFlowContext doesn't expose its internal state
        // but we can verify it's created correctly
        let _ = text_flow; // Just ensure it can be created
    }

    // ============= Image Tests =============

    #[test]
    fn test_add_image() {
        let mut page = Page::a4();

        // Create a minimal JPEG image
        let image_data = vec![
            0xFF, 0xD8, // SOI marker
            0xFF, 0xC0, // SOF0 marker
            0x00, 0x11, // Length
            0x08, // Precision
            0x00, 0x10, // Height
            0x00, 0x10, // Width
            0x03, // Components
            0x01, 0x11, 0x00, // Component 1
            0x02, 0x11, 0x00, // Component 2
            0x03, 0x11, 0x00, // Component 3
            0xFF, 0xD9, // EOI marker
        ];

        let image = Image::from_jpeg_data(image_data).unwrap();
        page.add_image("test_image", image);

        // Image should be stored
        assert!(page.images.contains_key("test_image"));
    }

    #[test]
    fn test_draw_image_simple() {
        let mut page = Page::a4();

        // Create and add image
        let image_data = vec![
            0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x10, 0x00, 0x10, 0x03, 0x01, 0x11,
            0x00, 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, 0xFF, 0xD9,
        ];

        let image = Image::from_jpeg_data(image_data).unwrap();
        page.add_image("img1", image);

        // Draw the image
        let result = page.draw_image("img1", 100.0, 100.0, 200.0, 200.0);
        assert!(result.is_ok());
    }

    // ============= Annotations Tests =============

    #[test]
    fn test_add_annotation() {
        use crate::annotations::{Annotation, AnnotationType};
        use crate::geometry::{Point, Rectangle};

        let mut page = Page::a4();
        let rect = Rectangle::new(Point::new(100.0, 100.0), Point::new(200.0, 150.0));
        let annotation = Annotation::new(AnnotationType::Text, rect);

        page.add_annotation(annotation);
        assert_eq!(page.annotations().len(), 1);
    }

    #[test]
    fn test_annotations_mut() {
        use crate::annotations::{Annotation, AnnotationType};
        use crate::geometry::{Point, Rectangle};

        let mut page = Page::a4();
        let _rect = Rectangle::new(Point::new(100.0, 100.0), Point::new(200.0, 150.0));

        // Add multiple annotations
        for i in 0..3 {
            let annotation = Annotation::new(
                AnnotationType::Text,
                Rectangle::new(
                    Point::new(100.0 + i as f64 * 10.0, 100.0),
                    Point::new(200.0 + i as f64 * 10.0, 150.0),
                ),
            );
            page.add_annotation(annotation);
        }

        // Modify annotations
        let annotations = page.annotations_mut();
        annotations.clear();
        assert_eq!(page.annotations().len(), 0);
    }

    // ============= Form Widget Tests =============

    #[test]
    fn test_add_form_widget() {
        use crate::forms::Widget;
        use crate::geometry::{Point, Rectangle};

        let mut page = Page::a4();
        let rect = Rectangle::new(Point::new(100.0, 100.0), Point::new(200.0, 120.0));
        let widget = Widget::new(rect);

        let obj_ref = page.add_form_widget(widget);
        assert_eq!(obj_ref.number(), 0);
        assert_eq!(obj_ref.generation(), 0);

        // Annotations should include the widget
        assert_eq!(page.annotations().len(), 1);
    }

    // ============= Header/Footer Tests =============

    #[test]
    fn test_set_header() {
        use crate::text::HeaderFooter;

        let mut page = Page::a4();
        let header = HeaderFooter::new_header("Test Header");

        page.set_header(header);
        assert!(page.header().is_some());

        if let Some(h) = page.header() {
            assert_eq!(h.content(), "Test Header");
        }
    }

    #[test]
    fn test_set_footer() {
        use crate::text::HeaderFooter;

        let mut page = Page::a4();
        let footer = HeaderFooter::new_footer("Page {{page}} of {{total}}");

        page.set_footer(footer);
        assert!(page.footer().is_some());

        if let Some(f) = page.footer() {
            assert_eq!(f.content(), "Page {{page}} of {{total}}");
        }
    }

    #[test]
    fn test_header_footer_rendering() {
        use crate::text::HeaderFooter;

        let mut page = Page::a4();

        // Set both header and footer
        page.set_header(HeaderFooter::new_header("Header"));
        page.set_footer(HeaderFooter::new_footer("Footer"));

        // Generate content with header/footer
        let result = page.generate_content_with_page_info(Some(1), Some(1), None);
        assert!(result.is_ok());

        let content = result.unwrap();
        assert!(!content.is_empty());
    }

    // ============= Table Tests =============

    #[test]
    fn test_add_table() {
        use crate::text::Table;

        let mut page = Page::a4();
        let mut table = Table::with_equal_columns(2, 200.0);

        // Add some rows
        table
            .add_row(vec!["Cell 1".to_string(), "Cell 2".to_string()])
            .unwrap();
        table
            .add_row(vec!["Cell 3".to_string(), "Cell 4".to_string()])
            .unwrap();

        let result = page.add_table(&table);
        assert!(result.is_ok());
    }

    // ============= Content Generation Tests =============

    #[test]
    fn test_generate_operations_empty() {
        let page = Page::a4();
        // Page doesn't have generate_operations, use graphics_context
        let ops = page.graphics_context.generate_operations();

        // Even empty page should have valid PDF operations
        assert!(ops.is_ok());
    }

    #[test]
    fn test_generate_operations_with_graphics() {
        let mut page = Page::a4();

        page.graphics().rectangle(50.0, 50.0, 100.0, 100.0).fill();

        // Page doesn't have generate_operations, use graphics_context
        let ops = page.graphics_context.generate_operations();
        assert!(ops.is_ok());

        let content = ops.unwrap();
        let content_str = String::from_utf8_lossy(&content);
        assert!(content_str.contains("re")); // rectangle
        assert!(content_str.contains("f")); // fill
    }

    #[test]
    fn test_generate_operations_with_text() {
        let mut page = Page::a4();

        page.text()
            .set_font(Font::Helvetica, 12.0)
            .at(100.0, 700.0)
            .write("Hello")
            .unwrap();

        // Text operations are in text_context, not graphics_context
        let ops = page.text_context.generate_operations();
        assert!(ops.is_ok());

        let content = ops.unwrap();
        let content_str = String::from_utf8_lossy(&content);
        assert!(content_str.contains("BT")); // Begin text
        assert!(content_str.contains("ET")); // End text
    }

    // ============= Edge Cases and Error Handling =============

    #[test]
    fn test_negative_margins() {
        let mut page = Page::a4();
        page.set_margins(-10.0, -20.0, -30.0, -40.0);

        // Negative margins should still work (might be intentional)
        let margins = page.margins();
        assert_eq!(margins.left, -10.0);
        assert_eq!(margins.right, -20.0);
    }

    #[test]
    fn test_zero_dimensions() {
        let page = Page::new(0.0, 0.0);
        assert_eq!(page.width(), 0.0);
        assert_eq!(page.height(), 0.0);

        // Content area with default margins would be negative
        let (_, _, width, height) = page.content_area();
        assert!(width < 0.0);
        assert!(height < 0.0);
    }

    #[test]
    fn test_huge_dimensions() {
        let page = Page::new(1_000_000.0, 1_000_000.0);
        assert_eq!(page.width(), 1_000_000.0);
        assert_eq!(page.height(), 1_000_000.0);
    }

    #[test]
    fn test_draw_nonexistent_image() {
        let mut page = Page::a4();

        // Try to draw an image that wasn't added
        let result = page.draw_image("nonexistent", 100.0, 100.0, 200.0, 200.0);

        // Should fail gracefully
        assert!(result.is_err());
    }

    #[test]
    fn test_clone_page() {
        let mut page = Page::a4();
        page.set_margins(10.0, 20.0, 30.0, 40.0);

        page.graphics().rectangle(50.0, 50.0, 100.0, 100.0).fill();

        let cloned = page.clone();
        assert_eq!(cloned.width(), page.width());
        assert_eq!(cloned.height(), page.height());
        assert_eq!(cloned.margins().left, page.margins().left);
    }

    #[test]
    fn test_page_from_parsed_basic() {
        use crate::parser::objects::PdfDictionary;
        use crate::parser::page_tree::ParsedPage;

        // Create a test parsed page
        let parsed_page = ParsedPage {
            obj_ref: (1, 0),
            dict: PdfDictionary::new(),
            inherited_resources: None,
            media_box: [0.0, 0.0, 612.0, 792.0], // US Letter
            crop_box: None,
            rotation: 0,
            annotations: None,
        };

        // Convert to writable page
        let page = Page::from_parsed(&parsed_page).unwrap();

        // Verify dimensions
        assert_eq!(page.width(), 612.0);
        assert_eq!(page.height(), 792.0);
        assert_eq!(page.get_rotation(), 0);
    }

    #[test]
    fn test_page_from_parsed_with_rotation() {
        use crate::parser::objects::PdfDictionary;
        use crate::parser::page_tree::ParsedPage;

        // Create a test parsed page with 90-degree rotation
        let parsed_page = ParsedPage {
            obj_ref: (1, 0),
            dict: PdfDictionary::new(),
            inherited_resources: None,
            media_box: [0.0, 0.0, 595.0, 842.0], // A4
            crop_box: None,
            rotation: 90,
            annotations: None,
        };

        // Convert to writable page
        let page = Page::from_parsed(&parsed_page).unwrap();

        // Verify rotation was preserved
        assert_eq!(page.get_rotation(), 90);
        assert_eq!(page.width(), 595.0);
        assert_eq!(page.height(), 842.0);

        // Verify effective dimensions (rotated)
        assert_eq!(page.effective_width(), 842.0);
        assert_eq!(page.effective_height(), 595.0);
    }

    #[test]
    fn test_page_from_parsed_with_cropbox() {
        use crate::parser::objects::PdfDictionary;
        use crate::parser::page_tree::ParsedPage;

        // Create a test parsed page with CropBox
        let parsed_page = ParsedPage {
            obj_ref: (1, 0),
            dict: PdfDictionary::new(),
            inherited_resources: None,
            media_box: [0.0, 0.0, 612.0, 792.0],
            crop_box: Some([10.0, 10.0, 602.0, 782.0]),
            rotation: 0,
            annotations: None,
        };

        // Convert to writable page
        let page = Page::from_parsed(&parsed_page).unwrap();

        // CropBox doesn't affect page dimensions (only visible area)
        assert_eq!(page.width(), 612.0);
        assert_eq!(page.height(), 792.0);
    }

    #[test]
    fn test_page_from_parsed_small_mediabox() {
        use crate::parser::objects::PdfDictionary;
        use crate::parser::page_tree::ParsedPage;

        // Create a test parsed page with custom small dimensions
        let parsed_page = ParsedPage {
            obj_ref: (1, 0),
            dict: PdfDictionary::new(),
            inherited_resources: None,
            media_box: [0.0, 0.0, 200.0, 300.0],
            crop_box: None,
            rotation: 0,
            annotations: None,
        };

        // Convert to writable page
        let page = Page::from_parsed(&parsed_page).unwrap();

        assert_eq!(page.width(), 200.0);
        assert_eq!(page.height(), 300.0);
    }

    #[test]
    fn test_page_from_parsed_non_zero_origin() {
        use crate::parser::objects::PdfDictionary;
        use crate::parser::page_tree::ParsedPage;

        // Create a test parsed page with non-zero origin
        let parsed_page = ParsedPage {
            obj_ref: (1, 0),
            dict: PdfDictionary::new(),
            inherited_resources: None,
            media_box: [10.0, 20.0, 610.0, 820.0], // Offset origin
            crop_box: None,
            rotation: 0,
            annotations: None,
        };

        // Convert to writable page
        let page = Page::from_parsed(&parsed_page).unwrap();

        // Width and height should be calculated correctly
        assert_eq!(page.width(), 600.0); // 610 - 10
        assert_eq!(page.height(), 800.0); // 820 - 20
    }

    #[test]
    fn test_page_rotation() {
        let mut page = Page::a4();

        // Test default rotation
        assert_eq!(page.get_rotation(), 0);

        // Test setting valid rotations
        page.set_rotation(90);
        assert_eq!(page.get_rotation(), 90);

        page.set_rotation(180);
        assert_eq!(page.get_rotation(), 180);

        page.set_rotation(270);
        assert_eq!(page.get_rotation(), 270);

        page.set_rotation(360);
        assert_eq!(page.get_rotation(), 0);

        // Test rotation normalization
        page.set_rotation(45);
        assert_eq!(page.get_rotation(), 90);

        page.set_rotation(135);
        assert_eq!(page.get_rotation(), 180);

        page.set_rotation(-90);
        assert_eq!(page.get_rotation(), 270);
    }

    #[test]
    fn test_effective_dimensions() {
        let mut page = Page::new(600.0, 800.0);

        // No rotation - same dimensions
        assert_eq!(page.effective_width(), 600.0);
        assert_eq!(page.effective_height(), 800.0);

        // 90 degree rotation - swapped dimensions
        page.set_rotation(90);
        assert_eq!(page.effective_width(), 800.0);
        assert_eq!(page.effective_height(), 600.0);

        // 180 degree rotation - same dimensions
        page.set_rotation(180);
        assert_eq!(page.effective_width(), 600.0);
        assert_eq!(page.effective_height(), 800.0);

        // 270 degree rotation - swapped dimensions
        page.set_rotation(270);
        assert_eq!(page.effective_width(), 800.0);
        assert_eq!(page.effective_height(), 600.0);
    }

    #[test]
    fn test_rotation_in_pdf_dict() {
        let mut page = Page::a4();

        // No rotation should not include Rotate field
        let dict = page.to_dict();
        assert!(dict.get("Rotate").is_none());

        // With rotation should include Rotate field
        page.set_rotation(90);
        let dict = page.to_dict();
        assert_eq!(dict.get("Rotate"), Some(&Object::Integer(90)));

        page.set_rotation(270);
        let dict = page.to_dict();
        assert_eq!(dict.get("Rotate"), Some(&Object::Integer(270)));
    }
}

/// Layout manager for intelligent positioning of elements on a page
///
/// This manager handles automatic positioning of tables, images, and other elements
/// using different coordinate systems while preventing overlaps and managing page flow.
#[derive(Debug)]
pub struct LayoutManager {
    /// Coordinate system being used
    pub coordinate_system: crate::coordinate_system::CoordinateSystem,
    /// Current Y position for next element
    pub current_y: f64,
    /// Page dimensions
    pub page_width: f64,
    pub page_height: f64,
    /// Page margins
    pub margins: Margins,
    /// Spacing between elements
    pub element_spacing: f64,
}

impl LayoutManager {
    /// Create a new layout manager for the given page
    pub fn new(page: &Page, coordinate_system: crate::coordinate_system::CoordinateSystem) -> Self {
        let current_y = match coordinate_system {
            crate::coordinate_system::CoordinateSystem::PdfStandard => {
                // PDF coordinates: start from top (high Y value)
                page.height() - page.margins().top
            }
            crate::coordinate_system::CoordinateSystem::ScreenSpace => {
                // Screen coordinates: start from top (low Y value)
                page.margins().top
            }
            crate::coordinate_system::CoordinateSystem::Custom(_) => {
                // For custom systems, start conservatively in the middle
                page.height() / 2.0
            }
        };

        Self {
            coordinate_system,
            current_y,
            page_width: page.width(),
            page_height: page.height(),
            margins: page.margins().clone(),
            element_spacing: 10.0,
        }
    }

    /// Set custom spacing between elements
    pub fn with_element_spacing(mut self, spacing: f64) -> Self {
        self.element_spacing = spacing;
        self
    }

    /// Check if an element of given height will fit on the current page
    pub fn will_fit(&self, element_height: f64) -> bool {
        let required_space = element_height + self.element_spacing;

        match self.coordinate_system {
            crate::coordinate_system::CoordinateSystem::PdfStandard => {
                // In PDF coords, we subtract height and check against bottom margin
                self.current_y - required_space >= self.margins.bottom
            }
            crate::coordinate_system::CoordinateSystem::ScreenSpace => {
                // In screen coords, we add height and check against page height
                self.current_y + required_space <= self.page_height - self.margins.bottom
            }
            crate::coordinate_system::CoordinateSystem::Custom(_) => {
                // Conservative check for custom coordinate systems
                required_space <= (self.page_height - self.margins.top - self.margins.bottom) / 2.0
            }
        }
    }

    /// Get the current available space remaining on the page
    pub fn remaining_space(&self) -> f64 {
        match self.coordinate_system {
            crate::coordinate_system::CoordinateSystem::PdfStandard => {
                (self.current_y - self.margins.bottom).max(0.0)
            }
            crate::coordinate_system::CoordinateSystem::ScreenSpace => {
                (self.page_height - self.margins.bottom - self.current_y).max(0.0)
            }
            crate::coordinate_system::CoordinateSystem::Custom(_) => {
                self.page_height / 2.0 // Conservative estimate
            }
        }
    }

    /// Reserve space for an element and return its Y position
    ///
    /// Returns `None` if the element doesn't fit on the current page.
    /// If it fits, returns the Y coordinate where the element should be placed
    /// and updates the internal current_y for the next element.
    pub fn add_element(&mut self, element_height: f64) -> Option<f64> {
        if !self.will_fit(element_height) {
            return None;
        }

        let position_y = match self.coordinate_system {
            crate::coordinate_system::CoordinateSystem::PdfStandard => {
                // Position element at current_y (top of element)
                // Then move current_y down by element height + spacing
                let y_position = self.current_y - element_height;
                self.current_y = y_position - self.element_spacing;
                self.current_y + element_height // Return the bottom Y of the element area
            }
            crate::coordinate_system::CoordinateSystem::ScreenSpace => {
                // Position element at current_y (top of element)
                // Then move current_y down by element height + spacing
                let y_position = self.current_y;
                self.current_y += element_height + self.element_spacing;
                y_position
            }
            crate::coordinate_system::CoordinateSystem::Custom(_) => {
                // Simple implementation for custom coordinate systems
                let y_position = self.current_y;
                self.current_y -= element_height + self.element_spacing;
                y_position
            }
        };

        Some(position_y)
    }

    /// Reset the layout manager for a new page
    pub fn new_page(&mut self) {
        self.current_y = match self.coordinate_system {
            crate::coordinate_system::CoordinateSystem::PdfStandard => {
                self.page_height - self.margins.top
            }
            crate::coordinate_system::CoordinateSystem::ScreenSpace => self.margins.top,
            crate::coordinate_system::CoordinateSystem::Custom(_) => self.page_height / 2.0,
        };
    }

    /// Get the X position for centering an element of given width
    pub fn center_x(&self, element_width: f64) -> f64 {
        let available_width = self.page_width - self.margins.left - self.margins.right;
        self.margins.left + (available_width - element_width) / 2.0
    }

    /// Get the left margin X position
    pub fn left_x(&self) -> f64 {
        self.margins.left
    }

    /// Get the right margin X position minus element width
    pub fn right_x(&self, element_width: f64) -> f64 {
        self.page_width - self.margins.right - element_width
    }
}

#[cfg(test)]
mod layout_manager_tests {
    use super::*;
    use crate::coordinate_system::CoordinateSystem;

    #[test]
    fn test_layout_manager_pdf_standard() {
        let page = Page::a4(); // 595 x 842
        let mut layout = LayoutManager::new(&page, CoordinateSystem::PdfStandard);

        // Check initial position (should be near top in PDF coords)
        // A4 height is 842, with default margin of 72, so current_y should be 842 - 72 = 770
        assert!(layout.current_y > 750.0); // Near top of A4, adjusted for actual margins

        // Add an element
        let element_height = 100.0;
        let position = layout.add_element(element_height);

        assert!(position.is_some());
        let y_pos = position.unwrap();
        assert!(y_pos > 700.0); // Should be positioned high up

        // Current Y should have moved down
        assert!(layout.current_y < y_pos);
    }

    #[test]
    fn test_layout_manager_screen_space() {
        let page = Page::a4();
        let mut layout = LayoutManager::new(&page, CoordinateSystem::ScreenSpace);

        // Check initial position (should be near top in screen coords)
        assert!(layout.current_y < 100.0); // Near top margin

        // Add an element
        let element_height = 100.0;
        let position = layout.add_element(element_height);

        assert!(position.is_some());
        let y_pos = position.unwrap();
        assert!(y_pos < 100.0); // Should be positioned near top

        // Current Y should have moved down (increased)
        assert!(layout.current_y > y_pos);
    }

    #[test]
    fn test_layout_manager_overflow() {
        let page = Page::a4();
        let mut layout = LayoutManager::new(&page, CoordinateSystem::PdfStandard);

        // Try to add an element that's too large
        let huge_element = 900.0; // Larger than page height
        let position = layout.add_element(huge_element);

        assert!(position.is_none()); // Should not fit

        // Fill the page with smaller elements
        let mut count = 0;
        while layout.add_element(50.0).is_some() {
            count += 1;
            if count > 100 {
                break;
            } // Safety valve
        }

        // Should have added multiple elements
        assert!(count > 5);

        // Next element should not fit
        assert!(layout.add_element(50.0).is_none());
    }

    #[test]
    fn test_layout_manager_centering() {
        let page = Page::a4();
        let layout = LayoutManager::new(&page, CoordinateSystem::PdfStandard);

        let element_width = 200.0;
        let center_x = layout.center_x(element_width);

        // Should be centered considering margins
        let expected_center = page.margins().left
            + (page.width() - page.margins().left - page.margins().right - element_width) / 2.0;
        assert_eq!(center_x, expected_center);
    }
}