File: PDF_plotter.cpp

package info (click to toggle)
kicad 9.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 770,320 kB
  • sloc: cpp: 961,692; ansic: 121,001; xml: 66,428; python: 18,387; sh: 1,010; awk: 301; asm: 292; makefile: 227; javascript: 167; perl: 10
file content (1770 lines) | stat: -rw-r--r-- 55,959 bytes parent folder | download | duplicates (3)
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
/**
 * @file PDF_plotter.cpp
 * @brief KiCad: specialized plotter for PDF files format
 */

/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 1992-2012 Lorenzo Marcantonio, l.marcantonio@logossrl.com
 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <algorithm>
#include <cstdio> // snprintf
#include <stack>

#include <wx/filename.h>
#include <wx/mstream.h>
#include <wx/zstream.h>
#include <wx/wfstream.h>
#include <wx/datstrm.h>
#include <wx/tokenzr.h>

#include <advanced_config.h>
#include <common.h>               // ResolveUriByEnvVars
#include <eda_text.h>             // for IsGotoPageHref
#include <font/font.h>
#include <core/ignore.h>
#include <macros.h>
#include <trigo.h>
#include <string_utils.h>

#include <plotters/plotters_pslike.h>


std::string PDF_PLOTTER::encodeStringForPlotter( const wxString& aText )
{
    // returns a string compatible with PDF string convention from a unicode string.
    // if the initial text is only ASCII7, return the text between ( and ) for a good readability
    // if the initial text is no ASCII7, return the text between < and >
    // and encoded using 16 bits hexa (4 digits) by wide char (unicode 16)
    std::string result;

    // Is aText only ASCII7 ?
    bool is_ascii7 = true;

    for( size_t ii = 0; ii < aText.Len(); ii++ )
    {
        if( aText[ii] >= 0x7F )
        {
            is_ascii7 = false;
            break;
        }
    }

    if( is_ascii7 )
    {
        result = '(';

        for( unsigned ii = 0; ii < aText.Len(); ii++ )
        {
            unsigned int code = aText[ii];

            // These characters must be escaped
            switch( code )
            {
            case '(':
            case ')':
            case '\\':
                result += '\\';
                KI_FALLTHROUGH;

            default:
                result += code;
                break;
            }
        }

        result += ')';
    }
    else
    {
        result = "<FEFF";


        for( size_t ii = 0; ii < aText.Len(); ii++ )
        {
            unsigned int code = aText[ii];
            char buffer[16];
            std::snprintf( buffer, sizeof( buffer ), "%4.4X", code );
            result += buffer;

        }

        result += '>';
    }

    return result;
}


bool PDF_PLOTTER::OpenFile( const wxString& aFullFilename )
{
    m_filename = aFullFilename;

    wxASSERT( !m_outputFile );

    // Open the PDF file in binary mode
    m_outputFile = wxFopen( m_filename, wxT( "wb" ) );

    if( m_outputFile == nullptr )
        return false ;

    return true;
}


void PDF_PLOTTER::SetViewport( const VECTOR2I& aOffset, double aIusPerDecimil,
                               double aScale, bool aMirror )
{
    m_plotMirror    = aMirror;
    m_plotOffset    = aOffset;
    m_plotScale     = aScale;
    m_IUsPerDecimil = aIusPerDecimil;

    // The CTM is set to 1 user unit per decimal
    m_iuPerDeviceUnit = 1.0 / aIusPerDecimil;

    /* The paper size in this engine is handled page by page
       Look in the StartPage function */
}


void PDF_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
{
    wxASSERT( m_workFile );

    if( aWidth == DO_NOT_SET_LINE_WIDTH )
        return;
    else if( aWidth == USE_DEFAULT_LINE_WIDTH )
        aWidth = m_renderSettings->GetDefaultPenWidth();

    if( aWidth == 0 )
        aWidth = 1;

    wxASSERT_MSG( aWidth > 0, "Plotter called to set negative pen width" );

    if( aWidth != m_currentPenWidth )
        fprintf( m_workFile, "%g w\n", userToDeviceSize( aWidth ) );

    m_currentPenWidth = aWidth;
}


void PDF_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
{
    wxASSERT( m_workFile );

    // PDF treats all colors as opaque, so the best we can do with alpha is generate an
    // appropriate blended color assuming white paper.
    if( a < 1.0 )
    {
        r = ( r * a ) + ( 1 - a );
        g = ( g * a ) + ( 1 - a );
        b = ( b * a ) + ( 1 - a );
    }

    fprintf( m_workFile, "%g %g %g rg %g %g %g RG\n", r, g, b, r, g, b );
}


void PDF_PLOTTER::SetDash( int aLineWidth, LINE_STYLE aLineStyle )
{
    wxASSERT( m_workFile );

    switch( aLineStyle )
    {
    case LINE_STYLE::DASH:
        fprintf( m_workFile, "[%d %d] 0 d\n",
                (int) GetDashMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) );
        break;

    case LINE_STYLE::DOT:
        fprintf( m_workFile, "[%d %d] 0 d\n",
                (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) );
        break;

    case LINE_STYLE::DASHDOT:
        fprintf( m_workFile, "[%d %d %d %d] 0 d\n",
                (int) GetDashMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ),
                (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) );
        break;

    case LINE_STYLE::DASHDOTDOT:
        fprintf( m_workFile, "[%d %d %d %d %d %d] 0 d\n",
                (int) GetDashMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ),
                (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ),
                (int) GetDotMarkLenIU( aLineWidth ), (int) GetDashGapLenIU( aLineWidth ) );
        break;

    default:
        fputs( "[] 0 d\n", m_workFile );
    }
}


void PDF_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width )
{
    wxASSERT( m_workFile );

    if( fill == FILL_T::NO_FILL && width <= 0 )
        return;

    SetCurrentLineWidth( width );

    VECTOR2I size = p2 - p1;

    if( size.x == 0 && size.y == 0 )
    {
        // Can't draw zero-sized rectangles
        MoveTo( VECTOR2I( p1.x, p1.y ) );
        FinishTo( VECTOR2I( p1.x, p1.y ) );

        return;
    }

    if( std::min( std::abs( size.x ), std::abs( size.y ) ) < width )
    {
        // Too thick stroked rectangles are buggy, draw as polygon
        std::vector<VECTOR2I> cornerList;

        cornerList.emplace_back( p1.x, p1.y );
        cornerList.emplace_back( p2.x, p1.y );
        cornerList.emplace_back( p2.x, p2.y );
        cornerList.emplace_back( p1.x, p2.y );
        cornerList.emplace_back( p1.x, p1.y );

        PlotPoly( cornerList, fill, width, nullptr );

        return;
    }

    VECTOR2D p1_dev = userToDeviceCoordinates( p1 );
    VECTOR2D p2_dev = userToDeviceCoordinates( p2 );

    char paintOp;

    if( fill == FILL_T::NO_FILL )
        paintOp = 'S';
    else
        paintOp = width > 0 ? 'B' : 'f';

    fprintf( m_workFile, "%g %g %g %g re %c\n", p1_dev.x, p1_dev.y, p2_dev.x - p1_dev.x,
             p2_dev.y - p1_dev.y, paintOp );
}


void PDF_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T aFill, int width )
{
    wxASSERT( m_workFile );

    if( aFill == FILL_T::NO_FILL && width <= 0 )
        return;

    VECTOR2D pos_dev = userToDeviceCoordinates( pos );
    double   radius = userToDeviceSize( diametre / 2.0 );

    /* OK. Here's a trick. PDF doesn't support circles or circular angles, that's
       a fact. You'll have to do with cubic beziers. These *can't* represent
       circular arcs (NURBS can, beziers don't). But there is a widely known
       approximation which is really good
    */

    SetCurrentLineWidth( width );

    // If diameter is less than width, switch to filled mode
    if( aFill == FILL_T::NO_FILL && diametre < width )
    {
        aFill = FILL_T::FILLED_SHAPE;
        SetCurrentLineWidth( 0 );

        radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
    }

    double magic = radius * 0.551784; // You don't want to know where this come from

    // This is the convex hull for the bezier approximated circle
    fprintf( m_workFile,
             "%g %g m "
             "%g %g %g %g %g %g c "
             "%g %g %g %g %g %g c "
             "%g %g %g %g %g %g c "
             "%g %g %g %g %g %g c %c\n",
             pos_dev.x - radius, pos_dev.y,

             pos_dev.x - radius, pos_dev.y + magic,
             pos_dev.x - magic, pos_dev.y + radius,
             pos_dev.x, pos_dev.y + radius,

             pos_dev.x + magic, pos_dev.y + radius,
             pos_dev.x + radius, pos_dev.y + magic,
             pos_dev.x + radius, pos_dev.y,

             pos_dev.x + radius, pos_dev.y - magic,
             pos_dev.x + magic, pos_dev.y - radius,
             pos_dev.x, pos_dev.y - radius,

             pos_dev.x - magic, pos_dev.y - radius,
             pos_dev.x - radius, pos_dev.y - magic,
             pos_dev.x - radius, pos_dev.y,

             aFill == FILL_T::NO_FILL ? 's' : 'b' );
}


void PDF_PLOTTER::Arc( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
                       const EDA_ANGLE& aAngle, double aRadius, FILL_T aFill, int aWidth )
{
    wxASSERT( m_workFile );

    if( aRadius <= 0 )
    {
        Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
        return;
    }

    /*
     * Arcs are not so easily approximated by beziers (in the general case), so we approximate
     * them in the old way
     */
    EDA_ANGLE       startAngle = -aStartAngle;
    EDA_ANGLE       endAngle = startAngle - aAngle;
    VECTOR2I        start;
    VECTOR2I        end;
    const EDA_ANGLE delta( 5, DEGREES_T );   // increment to draw circles

    if( startAngle > endAngle )
        std::swap( startAngle, endAngle );

    SetCurrentLineWidth( aWidth );

    // Usual trig arc plotting routine...
    start.x = KiROUND( aCenter.x + aRadius * ( -startAngle ).Cos() );
    start.y = KiROUND( aCenter.y + aRadius * ( -startAngle ).Sin() );
    VECTOR2D pos_dev = userToDeviceCoordinates( start );
    fprintf( m_workFile, "%g %g m ", pos_dev.x, pos_dev.y );

    for( EDA_ANGLE ii = startAngle + delta; ii < endAngle; ii += delta )
    {
        end.x = KiROUND( aCenter.x + aRadius * ( -ii ).Cos() );
        end.y = KiROUND( aCenter.y + aRadius * ( -ii ).Sin() );
        pos_dev = userToDeviceCoordinates( end );
        fprintf( m_workFile, "%g %g l ", pos_dev.x, pos_dev.y );
    }

    end.x = KiROUND( aCenter.x + aRadius * ( -endAngle ).Cos() );
    end.y = KiROUND( aCenter.y + aRadius * ( -endAngle ).Sin() );
    pos_dev = userToDeviceCoordinates( end );
    fprintf( m_workFile, "%g %g l ", pos_dev.x, pos_dev.y );

    // The arc is drawn... if not filled we stroke it, otherwise we finish
    // closing the pie at the center
    if( aFill == FILL_T::NO_FILL )
    {
        fputs( "S\n", m_workFile );
    }
    else
    {
        pos_dev = userToDeviceCoordinates( aCenter );
        fprintf( m_workFile, "%g %g l b\n", pos_dev.x, pos_dev.y );
    }
}


void PDF_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill, int aWidth,
                            void* aData )
{
    wxASSERT( m_workFile );

    if( aFill == FILL_T::NO_FILL && aWidth <= 0 )
        return;

    if( aCornerList.size() <= 1 )
        return;

    SetCurrentLineWidth( aWidth );

    VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
    fprintf( m_workFile, "%f %f m\n", pos.x, pos.y );

    for( unsigned ii = 1; ii < aCornerList.size(); ii++ )
    {
        pos = userToDeviceCoordinates( aCornerList[ii] );
        fprintf( m_workFile, "%f %f l\n", pos.x, pos.y );
    }

    // Close path and stroke and/or fill
    if( aFill == FILL_T::NO_FILL )
        fputs( "S\n", m_workFile );
    else if( aWidth == 0 )
        fputs( "f\n", m_workFile );
    else
        fputs( "b\n", m_workFile );
}


void PDF_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
{
    wxASSERT( m_workFile );

    if( plume == 'Z' )
    {
        if( m_penState != 'Z' )
        {
            fputs( "S\n", m_workFile );
            m_penState     = 'Z';
            m_penLastpos.x = -1;
            m_penLastpos.y = -1;
        }

        return;
    }

    if( m_penState != plume || pos != m_penLastpos )
    {
        VECTOR2D pos_dev = userToDeviceCoordinates( pos );
        fprintf( m_workFile, "%f %f %c\n",
                 pos_dev.x, pos_dev.y,
                 ( plume=='D' ) ? 'l' : 'm' );
    }

    m_penState   = plume;
    m_penLastpos = pos;
}


void PDF_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
{
    wxASSERT( m_workFile );
    VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );

    // Requested size (in IUs)
    VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );

    // calculate the bitmap start position
    VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y + drawsize.y / 2 );
    VECTOR2D dev_start = userToDeviceCoordinates( start );

    // Deduplicate images
    auto findHandleForImage = [&]( const wxImage& aCurrImage ) -> int
    {
        for( const auto& [imgHandle, image] : m_imageHandles )
        {
            if( image.IsSameAs( aCurrImage ) )
                return imgHandle;

            if( image.GetWidth() != aCurrImage.GetWidth() )
                continue;

            if( image.GetHeight() != aCurrImage.GetHeight() )
                continue;

            if( image.GetType() != aCurrImage.GetType() )
                continue;

            if( image.HasAlpha() != aCurrImage.HasAlpha() )
                continue;

            if( image.HasMask() != aCurrImage.HasMask()
              || image.GetMaskRed() != aCurrImage.GetMaskRed()
              || image.GetMaskGreen() != aCurrImage.GetMaskGreen()
              || image.GetMaskBlue() != aCurrImage.GetMaskBlue() )
                continue;

            int pixCount = image.GetWidth() * image.GetHeight();

            if( memcmp( image.GetData(), aCurrImage.GetData(), pixCount * 3 ) != 0 )
                continue;

            if( image.HasAlpha()
              && memcmp( image.GetAlpha(), aCurrImage.GetAlpha(), pixCount ) != 0 )
                continue;

            return imgHandle;
        }

        return -1;
    };

    int imgHandle = findHandleForImage( aImage );

    if( imgHandle == -1 )
    {
        imgHandle = allocPdfObject();
        m_imageHandles.emplace( imgHandle, aImage );
    }

    /* PDF has an uhm... simplified coordinate system handling. There is
       *one* operator to do everything (the PS concat equivalent). At least
       they kept the matrix stack to save restore environments. Also images
       are always emitted at the origin with a size of 1x1 user units.
       What we need to do is:
       1) save the CTM end establish the new one
       2) plot the image
       3) restore the CTM
       4) profit
     */
    fprintf( m_workFile, "q %g 0 0 %g %g %g cm\n", // Step 1
             userToDeviceSize( drawsize.x ),
             userToDeviceSize( drawsize.y ),
             dev_start.x, dev_start.y );

    fprintf( m_workFile, "/Im%d Do\n", imgHandle );
    fputs( "Q\n", m_workFile );
}


int PDF_PLOTTER::allocPdfObject()
{
    m_xrefTable.push_back( 0 );
    return m_xrefTable.size() - 1;
}


int PDF_PLOTTER::startPdfObject(int handle)
{
    wxASSERT( m_outputFile );
    wxASSERT( !m_workFile );

    if( handle < 0)
        handle = allocPdfObject();

    m_xrefTable[handle] = ftell( m_outputFile );
    fprintf( m_outputFile, "%d 0 obj\n", handle );
    return handle;
}


void PDF_PLOTTER::closePdfObject()
{
    wxASSERT( m_outputFile );
    wxASSERT( !m_workFile );
    fputs( "endobj\n", m_outputFile );
}


int PDF_PLOTTER::startPdfStream( int handle )
{
    wxASSERT( m_outputFile );
    wxASSERT( !m_workFile );
    handle = startPdfObject( handle );

    // This is guaranteed to be handle+1 but needs to be allocated since
    // you could allocate more object during stream preparation
    m_streamLengthHandle = allocPdfObject();

    if( ADVANCED_CFG::GetCfg().m_DebugPDFWriter )
    {
        fprintf( m_outputFile,
                 "<< /Length %d 0 R >>\n" // Length is deferred
                 "stream\n", handle + 1 );
    }
    else
    {
        fprintf( m_outputFile,
                 "<< /Length %d 0 R /Filter /FlateDecode >>\n" // Length is deferred
                 "stream\n", handle + 1 );
    }

    // Open a temporary file to accumulate the stream
    m_workFilename = wxFileName::CreateTempFileName( "" );
    m_workFile = wxFopen( m_workFilename, wxT( "w+b" ) );
    wxASSERT( m_workFile );
    return handle;
}


void PDF_PLOTTER::closePdfStream()
{
    wxASSERT( m_workFile );

    long stream_len = ftell( m_workFile );

    if( stream_len < 0 )
    {
        wxASSERT( false );
        return;
    }

    // Rewind the file, read in the page stream and DEFLATE it
    fseek( m_workFile, 0, SEEK_SET );
    unsigned char *inbuf = new unsigned char[stream_len];

    int rc = fread( inbuf, 1, stream_len, m_workFile );
    wxASSERT( rc == stream_len );
    ignore_unused( rc );

    // We are done with the temporary file, junk it
    fclose( m_workFile );
    m_workFile = nullptr;
    ::wxRemoveFile( m_workFilename );

    unsigned out_count;

    if( ADVANCED_CFG::GetCfg().m_DebugPDFWriter )
    {
        out_count = stream_len;
        fwrite( inbuf, out_count, 1, m_outputFile );
    }
    else
    {
        // NULL means memos owns the memory, but provide a hint on optimum size needed.
        wxMemoryOutputStream    memos( nullptr, std::max( 2000l, stream_len ) ) ;

        {
            /* Somewhat standard parameters to compress in DEFLATE. The PDF spec is
             * misleading, it says it wants a DEFLATE stream but it really want a ZLIB
             * stream! (a DEFLATE stream would be generated with -15 instead of 15)
             * rc = deflateInit2( &zstrm, Z_BEST_COMPRESSION, Z_DEFLATED, 15,
             *                    8, Z_DEFAULT_STRATEGY );
             */

            wxZlibOutputStream      zos( memos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );

            zos.Write( inbuf, stream_len );
        }   // flush the zip stream using zos destructor

        wxStreamBuffer* sb = memos.GetOutputStreamBuffer();

        out_count = sb->Tell();
        fwrite( sb->GetBufferStart(), 1, out_count, m_outputFile );
    }

    delete[] inbuf;
    fputs( "\nendstream\n", m_outputFile );
    closePdfObject();

    // Writing the deferred length as an indirect object
    startPdfObject( m_streamLengthHandle );
    fprintf( m_outputFile, "%u\n", out_count );
    closePdfObject();
}


void PDF_PLOTTER::StartPage( const wxString& aPageNumber, const wxString& aPageName,
                             const wxString& aParentPageNumber, const wxString& aParentPageName )
{
    wxASSERT( m_outputFile );
    wxASSERT( !m_workFile );

    m_pageNumbers.push_back( aPageNumber );
    m_pageName = aPageName.IsEmpty()
                    ? wxString::Format( _( "Page %s" ), aPageNumber )
                    : wxString::Format( _( "%s (Page %s)" ), aPageName, aPageNumber );
    m_parentPageName = aParentPageName.IsEmpty()
                    ? wxString::Format( _( "Page %s" ), aParentPageNumber )
                    : wxString::Format( _( "%s (Page %s)" ), aParentPageName, aParentPageNumber );

    // Compute the paper size in IUs
    m_paperSize = m_pageInfo.GetSizeMils();
    m_paperSize.x *= 10.0 / m_iuPerDeviceUnit;
    m_paperSize.y *= 10.0 / m_iuPerDeviceUnit;

    // Set m_currentPenWidth to a unused value to ensure the pen width
    // will be initialized to a the right value in pdf file by the first item to plot
    m_currentPenWidth = 0;

    // Open the content stream; the page object will go later
    m_pageStreamHandle = startPdfStream();

    /* Now, until ClosePage *everything* must be wrote in workFile, to be
       compressed later in closePdfStream */

    // Default graphic settings (coordinate system, default color and line style)
    fprintf( m_workFile,
             "%g 0 0 %g 0 0 cm 1 J 1 j 0 0 0 rg 0 0 0 RG %g w\n",
             0.0072 * plotScaleAdjX, 0.0072 * plotScaleAdjY,
             userToDeviceSize( m_renderSettings->GetDefaultPenWidth() ) );
}


void WriteImageStream( const wxImage& aImage, wxDataOutputStream& aOut, wxColor bg, bool colorMode )
{
    int w = aImage.GetWidth();
    int h = aImage.GetHeight();

    for( int y = 0; y < h; y++ )
    {
        for( int x = 0; x < w; x++ )
        {
            unsigned char r = aImage.GetRed( x, y ) & 0xFF;
            unsigned char g = aImage.GetGreen( x, y ) & 0xFF;
            unsigned char b = aImage.GetBlue( x, y ) & 0xFF;

            if( aImage.HasMask() )
            {
                if( r == aImage.GetMaskRed() && g == aImage.GetMaskGreen()
                    && b == aImage.GetMaskBlue() )
                {
                    r = bg.Red();
                    g = bg.Green();
                    b = bg.Blue();
                }
            }

            if( colorMode )
            {
                aOut.Write8( r );
                aOut.Write8( g );
                aOut.Write8( b );
            }
            else
            {
                // Greyscale conversion (CIE 1931)
                unsigned char grey = KiROUND( r * 0.2126 + g * 0.7152 + b * 0.0722 );

                aOut.Write8( grey );
            }
        }
    }
}


void WriteImageSMaskStream( const wxImage& aImage, wxDataOutputStream& aOut )
{
    int w = aImage.GetWidth();
    int h = aImage.GetHeight();

    if( aImage.HasMask() )
    {
        for( int y = 0; y < h; y++ )
        {
            for( int x = 0; x < w; x++ )
            {
                unsigned char a = 255;
                unsigned char r = aImage.GetRed( x, y );
                unsigned char g = aImage.GetGreen( x, y );
                unsigned char b = aImage.GetBlue( x, y );

                if( r == aImage.GetMaskRed() && g == aImage.GetMaskGreen()
                    && b == aImage.GetMaskBlue() )
                {
                    a = 0;
                }

                aOut.Write8( a );
            }
        }
    }
    else if( aImage.HasAlpha() )
    {
        int size = w * h;
        aOut.Write8( aImage.GetAlpha(), size );
    }
}


void PDF_PLOTTER::ClosePage()
{
    wxASSERT( m_workFile );

    // Close the page stream (and compress it)
    closePdfStream();

    // Page size is in 1/72 of inch (default user space units).  Works like the bbox in postscript
    // but there is no need for swapping the sizes, since PDF doesn't require a portrait page.
    // We use the MediaBox but PDF has lots of other less-used boxes that could be used.
    const double PTsPERMIL = 0.072;
    VECTOR2D     psPaperSize = VECTOR2D( m_pageInfo.GetSizeMils() ) * PTsPERMIL;

    auto iuToPdfUserSpace =
            [&]( const VECTOR2I& aCoord ) -> VECTOR2D
            {
                VECTOR2D pos = VECTOR2D( aCoord ) * PTsPERMIL / ( m_IUsPerDecimil * 10 );

                // PDF y=0 is at bottom of page, invert coordinate
                VECTOR2D retval( pos.x, psPaperSize.y - pos.y );

                // The pdf plot can be mirrored (from left to right). So mirror the
                // x coordinate if m_plotMirror is set
                if( m_plotMirror )
                {
                    if( m_mirrorIsHorizontal )
                        retval.x = ( psPaperSize.x - pos.x );
                    else
                        retval.y = pos.y;
                }

                return retval;
            };

    // Handle annotations (at the moment only "link" type objects)
    std::vector<int> hyperlinkHandles;

    // Allocate all hyperlink objects for the page and calculate their position in user space
    // coordinates
    for( const std::pair<BOX2I, wxString>& linkPair : m_hyperlinksInPage )
    {
        const BOX2I&    box = linkPair.first;
        const wxString& url = linkPair.second;

        VECTOR2D bottomLeft = iuToPdfUserSpace( box.GetPosition() );
        VECTOR2D topRight = iuToPdfUserSpace( box.GetEnd() );

        BOX2D userSpaceBox;
        userSpaceBox.SetOrigin( bottomLeft );
        userSpaceBox.SetEnd( topRight );

        hyperlinkHandles.push_back( allocPdfObject() );

        m_hyperlinkHandles.insert( { hyperlinkHandles.back(), { userSpaceBox, url } } );
    }

    for( const std::pair<BOX2I, std::vector<wxString>>& menuPair : m_hyperlinkMenusInPage )
    {
        const BOX2I&                 box = menuPair.first;
        const std::vector<wxString>& urls = menuPair.second;

        VECTOR2D bottomLeft = iuToPdfUserSpace( box.GetPosition() );
        VECTOR2D topRight = iuToPdfUserSpace( box.GetEnd() );

        BOX2D userSpaceBox;
        userSpaceBox.SetOrigin( bottomLeft );
        userSpaceBox.SetEnd( topRight );

        hyperlinkHandles.push_back( allocPdfObject() );

        m_hyperlinkMenuHandles.insert( { hyperlinkHandles.back(), { userSpaceBox, urls } } );
    }

    int hyperLinkArrayHandle = -1;

    // If we have added any annotation links, create an array containing all the objects
    if( hyperlinkHandles.size() > 0 )
    {
        hyperLinkArrayHandle = startPdfObject();
        bool isFirst = true;

        fputs( "[", m_outputFile );

        for( int handle : hyperlinkHandles )
        {
            if( isFirst )
                isFirst = false;
            else
                fprintf( m_outputFile, " " );

            fprintf( m_outputFile, "%d 0 R", handle );
        }

        fputs( "]\n", m_outputFile );
        closePdfObject();
    }

    // Emit the page object and put it in the page list for later
    int pageHandle = startPdfObject();
    m_pageHandles.push_back( pageHandle );

    fprintf( m_outputFile,
             "<<\n"
             "/Type /Page\n"
             "/Parent %d 0 R\n"
             "/Resources <<\n"
             "    /ProcSet [/PDF /Text /ImageC /ImageB]\n"
             "    /Font %d 0 R\n"
             "    /XObject %d 0 R >>\n"
             "/MediaBox [0 0 %g %g]\n"
             "/Contents %d 0 R\n",
             m_pageTreeHandle,
             m_fontResDictHandle,
             m_imgResDictHandle,
             psPaperSize.x,
             psPaperSize.y,
             m_pageStreamHandle );

    if( hyperlinkHandles.size() > 0 )
        fprintf( m_outputFile, "/Annots %d 0 R", hyperLinkArrayHandle );

    fputs( ">>\n", m_outputFile );

    closePdfObject();

    // Mark the page stream as idle
    m_pageStreamHandle = 0;

    int                        actionHandle = emitGoToAction( pageHandle );
    PDF_PLOTTER::OUTLINE_NODE* parent_node = m_outlineRoot.get();

    if( !m_parentPageName.IsEmpty() )
    {
        // Search for the parent node iteratively through the entire tree
        std::stack<OUTLINE_NODE*> nodes;
        nodes.push( m_outlineRoot.get() );

        while( !nodes.empty() )
        {
            OUTLINE_NODE* node = nodes.top();
            nodes.pop();

            // Check if this node matches
            if( node->title == m_parentPageName )
            {
                parent_node = node;
                break;
            }

            // Add all children to the stack
            for( OUTLINE_NODE* child : node->children )
                nodes.push( child );
        }
    }

    OUTLINE_NODE* pageOutlineNode = addOutlineNode( parent_node, actionHandle, m_pageName );

    // let's reorg the symbol bookmarks under a page handle
    // let's reorg the symbol bookmarks under a page handle
    for( const auto& [groupName, groupVector] : m_bookmarksInPage )
    {
        OUTLINE_NODE* groupOutlineNode = addOutlineNode( pageOutlineNode, actionHandle, groupName );

        for( const std::pair<BOX2I, wxString>& bookmarkPair : groupVector )
        {
            const BOX2I&    box = bookmarkPair.first;
            const wxString& ref = bookmarkPair.second;

            VECTOR2I bottomLeft = iuToPdfUserSpace( box.GetPosition() );
            VECTOR2I topRight = iuToPdfUserSpace( box.GetEnd() );

            actionHandle = emitGoToAction( pageHandle, bottomLeft, topRight );

            addOutlineNode( groupOutlineNode, actionHandle, ref );
        }

        std::sort( groupOutlineNode->children.begin(), groupOutlineNode->children.end(),
                   []( const OUTLINE_NODE* a, const OUTLINE_NODE* b ) -> bool
                   {
                       return a->title < b->title;
                   } );
    }

    // Clean up
    m_hyperlinksInPage.clear();
    m_hyperlinkMenusInPage.clear();
    m_bookmarksInPage.clear();
}


bool PDF_PLOTTER::StartPlot( const wxString& aPageNumber )
{
    return StartPlot( aPageNumber, wxEmptyString );
}


bool PDF_PLOTTER::StartPlot( const wxString& aPageNumber, const wxString& aPageName )
{
    wxASSERT( m_outputFile );

    // First things first: the customary null object
    m_xrefTable.clear();
    m_xrefTable.push_back( 0 );
    m_hyperlinksInPage.clear();
    m_hyperlinkMenusInPage.clear();
    m_hyperlinkHandles.clear();
    m_hyperlinkMenuHandles.clear();
    m_bookmarksInPage.clear();
    m_totalOutlineNodes = 0;

    m_outlineRoot = std::make_unique<OUTLINE_NODE>();

    /* The header (that's easy!). The second line is binary junk required
       to make the file binary from the beginning (the important thing is
       that they must have the bit 7 set) */
    fputs("%PDF-1.5\n%\200\201\202\203\n", m_outputFile);

    /* Allocate an entry for the page tree root, it will go in every page parent entry */
    m_pageTreeHandle = allocPdfObject();

    /* In the same way, the font resource dictionary is used by every page
       (it *could* be inherited via the Pages tree */
    m_fontResDictHandle = allocPdfObject();

    m_imgResDictHandle = allocPdfObject();

    m_jsNamesHandle = allocPdfObject();

    /* Now, the PDF is read from the end, (more or less)... so we start
       with the page stream for page 1. Other more important stuff is written
       at the end */
    StartPage( aPageNumber, aPageName );
    return true;
}


int PDF_PLOTTER::emitGoToAction( int aPageHandle, const VECTOR2I& aBottomLeft,
                                 const VECTOR2I& aTopRight )
{
    int actionHandle = allocPdfObject();
    startPdfObject( actionHandle );

    fprintf( m_outputFile,
             "<</S /GoTo /D [%d 0 R /FitR %d %d %d %d]\n"
             ">>\n",
             aPageHandle, aBottomLeft.x, aBottomLeft.y, aTopRight.x, aTopRight.y );

    closePdfObject();

    return actionHandle;
}


int PDF_PLOTTER::emitGoToAction( int aPageHandle )
{
    int actionHandle = allocPdfObject();
    startPdfObject( actionHandle );

    fprintf( m_outputFile,
             "<</S /GoTo /D [%d 0 R /Fit]\n"
             ">>\n",
             aPageHandle );

    closePdfObject();

    return actionHandle;
}


void PDF_PLOTTER::emitOutlineNode( OUTLINE_NODE* node, int parentHandle, int nextNode,
                                   int prevNode )
{
    int nodeHandle = node->entryHandle;
    int prevHandle = -1;
    int nextHandle = -1;

    for( std::vector<OUTLINE_NODE*>::iterator it = node->children.begin();
         it != node->children.end(); it++ )
    {
        if( it >= node->children.end() - 1 )
        {
            nextHandle = -1;
        }
        else
        {
            nextHandle = ( *( it + 1 ) )->entryHandle;
        }

        emitOutlineNode( *it, nodeHandle, nextHandle, prevHandle );

        prevHandle = ( *it )->entryHandle;
    }

    // -1 for parentHandle is the outline root itself which is handed elsewhere.
    if( parentHandle != -1 )
    {
        startPdfObject( nodeHandle );

        fprintf( m_outputFile,
                 "<<\n"
                 "/Title %s\n"
                 "/Parent %d 0 R\n",
                 encodeStringForPlotter(node->title ).c_str(),
                 parentHandle);

        if( nextNode > 0 )
        {
            fprintf( m_outputFile, "/Next %d 0 R\n", nextNode );
        }

        if( prevNode > 0 )
        {
            fprintf( m_outputFile, "/Prev %d 0 R\n", prevNode );
        }

        if( node->children.size() > 0 )
        {
            fprintf( m_outputFile, "/Count %zd\n", -1 * node->children.size() );
            fprintf( m_outputFile, "/First %d 0 R\n", node->children.front()->entryHandle );
            fprintf( m_outputFile, "/Last %d 0 R\n", node->children.back()->entryHandle );
        }

        if( node->actionHandle != -1 )
        {
            fprintf( m_outputFile, "/A %d 0 R\n", node->actionHandle );
        }

        fputs( ">>\n", m_outputFile );
        closePdfObject();
    }
}


PDF_PLOTTER::OUTLINE_NODE* PDF_PLOTTER::addOutlineNode( OUTLINE_NODE* aParent, int aActionHandle,
                                                        const wxString& aTitle )
{
    OUTLINE_NODE *node = aParent->AddChild( aActionHandle, aTitle, allocPdfObject() );
    m_totalOutlineNodes++;

    return node;
}


int PDF_PLOTTER::emitOutline()
{
    if( m_outlineRoot->children.size() > 0 )
    {
        // declare the outline object
        m_outlineRoot->entryHandle = allocPdfObject();

        emitOutlineNode( m_outlineRoot.get(), -1, -1, -1 );

        startPdfObject( m_outlineRoot->entryHandle );

        fprintf( m_outputFile,
                 "<< /Type /Outlines\n"
                 "   /Count %d\n"
                 "   /First %d 0 R\n"
                 "   /Last %d 0 R\n"
                 ">>\n",
                 m_totalOutlineNodes,
                 m_outlineRoot->children.front()->entryHandle,
                 m_outlineRoot->children.back()->entryHandle
        );

        closePdfObject();

        return m_outlineRoot->entryHandle;
    }

    return -1;
}


bool PDF_PLOTTER::EndPlot()
{
    // We can end up here if there was nothing to plot
    if( !m_outputFile )
        return false;

    // Close the current page (often the only one)
    ClosePage();

    /* We need to declare the resources we're using (fonts in particular)
       The useful standard one is the Helvetica family. Adding external fonts
       is *very* involved! */
    struct {
        const char *psname;
        const char *rsname;
        int font_handle;
    } fontdefs[4] = {
        { "/Helvetica",             "/KicadFont",   0 },
        { "/Helvetica-Oblique",     "/KicadFontI",  0 },
        { "/Helvetica-Bold",        "/KicadFontB",  0 },
        { "/Helvetica-BoldOblique", "/KicadFontBI", 0 }
    };

    /* Declare the font resources. Since they're builtin fonts, no descriptors (yay!)
       We'll need metrics anyway to do any alignment (these are in the shared with
       the postscript engine) */
    for( int i = 0; i < 4; i++ )
    {
        fontdefs[i].font_handle = startPdfObject();
        fprintf( m_outputFile,
                 "<< /BaseFont %s\n"
                 "   /Type /Font\n"
                 "   /Subtype /Type1\n"
                 /* Adobe is so Mac-based that the nearest thing to Latin1 is
                    the Windows ANSI encoding! */
                 "   /Encoding /WinAnsiEncoding\n"
                 ">>\n",
                 fontdefs[i].psname );
        closePdfObject();
    }

    // Named font dictionary (was allocated, now we emit it)
    startPdfObject( m_fontResDictHandle );
    fputs( "<<\n", m_outputFile );

    for( int i = 0; i < 4; i++ )
    {
        fprintf( m_outputFile, "    %s %d 0 R\n",
                 fontdefs[i].rsname, fontdefs[i].font_handle );
    }

    fputs( ">>\n", m_outputFile );
    closePdfObject();

    // Named image dictionary (was allocated, now we emit it)
    startPdfObject( m_imgResDictHandle );
    fputs( "<<\n", m_outputFile );

    for( const auto& [imgHandle, image] : m_imageHandles )
    {
        fprintf( m_outputFile, "    /Im%d %d 0 R\n", imgHandle, imgHandle );
    }

    fputs( ">>\n", m_outputFile );
    closePdfObject();

    // Emit images with optional SMask for transparency
    for( const auto& [imgHandle, image] : m_imageHandles )
    {
        // Init wxFFile so wxFFileOutputStream won't close file in dtor.
        wxFFile outputFFile( m_outputFile );

        // Image
        startPdfObject( imgHandle );
        int imgLenHandle = allocPdfObject();
        int smaskHandle = ( image.HasAlpha() || image.HasMask() ) ? allocPdfObject() : -1;

        fprintf( m_outputFile,
                 "<<\n"
                 "/Type /XObject\n"
                 "/Subtype /Image\n"
                 "/BitsPerComponent 8\n"
                 "/ColorSpace %s\n"
                 "/Width %d\n"
                 "/Height %d\n"
                 "/Filter /FlateDecode\n"
                 "/Length %d 0 R\n", // Length is deferred
                 m_colorMode ? "/DeviceRGB" : "/DeviceGray", image.GetWidth(), image.GetHeight(),
                 imgLenHandle );

        if( smaskHandle != -1 )
            fprintf( m_outputFile, "/SMask %d 0 R\n", smaskHandle );

        fputs( ">>\n", m_outputFile );
        fputs( "stream\n", m_outputFile );

        long imgStreamStart = ftell( m_outputFile );

        {
            wxFFileOutputStream ffos( outputFFile );
            wxZlibOutputStream  zos( ffos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
            wxDataOutputStream  dos( zos );

            WriteImageStream( image, dos, m_renderSettings->GetBackgroundColor().ToColour(),
                              m_colorMode );
        }

        long imgStreamSize = ftell( m_outputFile ) - imgStreamStart;

        fputs( "\nendstream\n", m_outputFile );
        closePdfObject();

        startPdfObject( imgLenHandle );
        fprintf( m_outputFile, "%ld\n", imgStreamSize );
        closePdfObject();

        if( smaskHandle != -1 )
        {
            // SMask
            startPdfObject( smaskHandle );
            int smaskLenHandle = allocPdfObject();

            fprintf( m_outputFile,
                     "<<\n"
                     "/Type /XObject\n"
                     "/Subtype /Image\n"
                     "/BitsPerComponent 8\n"
                     "/ColorSpace /DeviceGray\n"
                     "/Width %d\n"
                     "/Height %d\n"
                     "/Length %d 0 R\n"
                     "/Filter /FlateDecode\n"
                     ">>\n", // Length is deferred
                     image.GetWidth(), image.GetHeight(), smaskLenHandle );

            fputs( "stream\n", m_outputFile );

            long smaskStreamStart = ftell( m_outputFile );

            {
                wxFFileOutputStream ffos( outputFFile );
                wxZlibOutputStream  zos( ffos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
                wxDataOutputStream  dos( zos );

                WriteImageSMaskStream( image, dos );
            }

            long smaskStreamSize = ftell( m_outputFile ) - smaskStreamStart;

            fputs( "\nendstream\n", m_outputFile );
            closePdfObject();

            startPdfObject( smaskLenHandle );
            fprintf( m_outputFile, "%u\n", (unsigned) smaskStreamSize );
            closePdfObject();
        }

        outputFFile.Detach(); // Don't close it
    }

    for( const auto& [ linkHandle, linkPair ] : m_hyperlinkHandles )
    {
        BOX2D    box = linkPair.first;
        wxString url = linkPair.second;

        startPdfObject( linkHandle );

        fprintf( m_outputFile,
                 "<<\n"
                 "/Type /Annot\n"
                 "/Subtype /Link\n"
                 "/Rect [%g %g %g %g]\n"
                 "/Border [16 16 0]\n",
                 box.GetLeft(), box.GetBottom(), box.GetRight(), box.GetTop() );

        wxString pageNumber;
        bool     pageFound = false;

        if( EDA_TEXT::IsGotoPageHref( url, &pageNumber ) )
        {
            for( size_t ii = 0; ii < m_pageNumbers.size(); ++ii )
            {
                if( m_pageNumbers[ii] == pageNumber )
                {
                    fprintf( m_outputFile,
                             "/Dest [%d 0 R /FitB]\n"
                             ">>\n",
                             m_pageHandles[ii] );

                    pageFound = true;
                    break;
                }
            }

            if( !pageFound )
            {
                // destination page is not being plotted, assign the NOP action to the link
                fprintf( m_outputFile, "/A << /Type /Action /S /NOP >>\n"
                                       ">>\n" );
            }
        }
        else
        {
            if( m_project )
                url = ResolveUriByEnvVars( url, m_project );

            fprintf( m_outputFile,
                     "/A << /Type /Action /S /URI /URI %s >>\n"
                     ">>\n",
                     encodeStringForPlotter( url ).c_str() );
        }

        closePdfObject();
    }

    for( const auto& [ menuHandle, menuPair ] : m_hyperlinkMenuHandles )
    {
        const BOX2D&                 box = menuPair.first;
        const std::vector<wxString>& urls = menuPair.second;
        wxString                     js = wxT( "ShM([\n" );

        for( const wxString& url : urls )
        {
            if( url.StartsWith( "!" ) )
            {
                wxString property = url.AfterFirst( '!' );

                if( property.Find( "http:" ) >= 0 )
                {
                    wxString href = property.substr( property.Find( "http:" ) );

                    if( m_project )
                        href = ResolveUriByEnvVars( href, m_project );

                    js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ),
                                            EscapeString( href, CTX_JS_STR ),
                                            EscapeString( href, CTX_JS_STR ) );
                }
                else if( property.Find( "https:" ) >= 0 )
                {
                    wxString href = property.substr( property.Find( "https:" ) );

                    if( m_project )
                        href = ResolveUriByEnvVars( href, m_project );

                    js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ),
                                            EscapeString( href, CTX_JS_STR ),
                                            EscapeString( href, CTX_JS_STR ) );
                }
                else if( property.Find( "file:" ) >= 0 )
                {
                    wxString href = property.substr( property.Find( "file:" ) );

                    if( m_project )
                        href = ResolveUriByEnvVars( href, m_project );

                    href = NormalizeFileUri( href );

                    js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ),
                                            EscapeString( href, CTX_JS_STR ),
                                            EscapeString( href, CTX_JS_STR ) );
                }
                else
                {
                    js += wxString::Format( wxT( "[\"%s\"],\n" ),
                                            EscapeString( property, CTX_JS_STR ) );
                }
            }
            else if( url.StartsWith( "#" ) )
            {
                wxString pageNumber = url.AfterFirst( '#' );

                for( size_t ii = 0; ii < m_pageNumbers.size(); ++ii )
                {
                    if( m_pageNumbers[ii] == pageNumber )
                    {
                        wxString menuText = wxString::Format( _( "Show Page %s" ), pageNumber );

                        js += wxString::Format( wxT( "[\"%s\", \"#%d\"],\n" ),
                                                EscapeString( menuText, CTX_JS_STR ),
                                                static_cast<int>( ii ) );
                        break;
                    }
                }
            }
            else if( url.StartsWith( "http:" ) || url.StartsWith( "https:" )
                   || url.StartsWith( "file:" ) )
            {
                wxString href = url;

                if( m_project )
                    href = ResolveUriByEnvVars( url, m_project );

                if( url.StartsWith( "file:" ) )
                    href = NormalizeFileUri( href );

                wxString menuText = wxString::Format( _( "Open %s" ), href );

                js += wxString::Format( wxT( "[\"%s\", \"%s\"],\n" ),
                                        EscapeString( href, CTX_JS_STR ),
                                        EscapeString( href, CTX_JS_STR ) );
            }
        }

        js += wxT( "]);" );

        startPdfObject( menuHandle );

        fprintf( m_outputFile,
                 "<<\n"
                 "/Type /Annot\n"
                 "/Subtype /Link\n"
                 "/Rect [%g %g %g %g]\n"
                 "/Border [16 16 0]\n",
                 box.GetLeft(), box.GetBottom(), box.GetRight(), box.GetTop() );

        fprintf( m_outputFile,
                 "/A << /Type /Action /S /JavaScript /JS %s >>\n"
                 ">>\n",
                 encodeStringForPlotter( js ).c_str() );

        closePdfObject();
    }

    {
        startPdfObject( m_jsNamesHandle );

        wxString js = R"JS(
function ShM(aEntries) {
    var aParams = [];
    for (var i in aEntries) {
        aParams.push({
            cName: aEntries[i][0],
            cReturn: aEntries[i][1]
        })
    }

    var cChoice = app.popUpMenuEx.apply(app, aParams);
    if (cChoice != null && cChoice.substring(0, 1) == '#') this.pageNum = parseInt(cChoice.slice(1));
    else if (cChoice != null && cChoice.substring(0, 4) == 'http') app.launchURL(cChoice);
    else if (cChoice != null && cChoice.substring(0, 4) == 'file') app.openDoc(cChoice.substring(7));
}
)JS";

        fprintf( m_outputFile,
                 "<< /JavaScript\n"
                 " << /Names\n"
                 "    [ (JSInit) << /Type /Action /S /JavaScript /JS %s >> ]\n"
                 " >>\n"
                 ">>\n",
                 encodeStringForPlotter( js ).c_str() );

        closePdfObject();
    }

    /* The page tree: it's a B-tree but luckily we only have few pages!
       So we use just an array... The handle was allocated at the beginning,
       now we instantiate the corresponding object */
    startPdfObject( m_pageTreeHandle );
    fputs( "<<\n"
           "/Type /Pages\n"
           "/Kids [\n", m_outputFile );

    for( unsigned i = 0; i < m_pageHandles.size(); i++ )
        fprintf( m_outputFile, "%d 0 R\n", m_pageHandles[i] );

    fprintf( m_outputFile,
            "]\n"
            "/Count %ld\n"
            ">>\n", (long) m_pageHandles.size() );
    closePdfObject();

    // The info dictionary
    int infoDictHandle = startPdfObject();
    char date_buf[250];
    time_t ltime = time( nullptr );
    strftime( date_buf, 250, "D:%Y%m%d%H%M%S", localtime( &ltime ) );

    if( m_title.IsEmpty() )
    {
        // Windows uses '\' and other platforms use '/' as separator
        m_title = m_filename.AfterLast( '\\' );
        m_title = m_title.AfterLast( '/' );
    }

    fprintf( m_outputFile,
             "<<\n"
             "/Producer (KiCad PDF)\n"
             "/CreationDate (%s)\n"
             "/Creator %s\n"
             "/Title %s\n"
             "/Author %s\n"
             "/Subject %s\n",
             date_buf,
             encodeStringForPlotter( m_creator ).c_str(),
             encodeStringForPlotter( m_title ).c_str(),
             encodeStringForPlotter( m_author ).c_str(),
             encodeStringForPlotter( m_subject ).c_str() );

    fputs( ">>\n", m_outputFile );
    closePdfObject();

    // Let's dump in the outline
    int outlineHandle = emitOutline();

    // The catalog, at last
    int catalogHandle = startPdfObject();

    if( outlineHandle > 0 )
    {
        fprintf( m_outputFile,
                 "<<\n"
                 "/Type /Catalog\n"
                 "/Pages %d 0 R\n"
                 "/Version /1.5\n"
                 "/PageMode /UseOutlines\n"
                 "/Outlines %d 0 R\n"
                 "/Names %d 0 R\n"
                 "/PageLayout /SinglePage\n"
                 ">>\n",
                 m_pageTreeHandle,
                 outlineHandle,
                 m_jsNamesHandle );
    }
    else
    {
        fprintf( m_outputFile,
                 "<<\n"
                 "/Type /Catalog\n"
                 "/Pages %d 0 R\n"
                 "/Version /1.5\n"
                 "/PageMode /UseNone\n"
                 "/PageLayout /SinglePage\n"
                 ">>\n",
                 m_pageTreeHandle );
    }

    closePdfObject();

    /* Emit the xref table (format is crucial to the byte, each entry must
       be 20 bytes long, and object zero must be done in that way). Also
       the offset must be kept along for the trailer */
    long xref_start = ftell( m_outputFile );
    fprintf( m_outputFile,
             "xref\n"
             "0 %ld\n"
             "0000000000 65535 f \n", (long) m_xrefTable.size() );

    for( unsigned i = 1; i < m_xrefTable.size(); i++ )
    {
        fprintf( m_outputFile, "%010ld 00000 n \n", m_xrefTable[i] );
    }

    // Done the xref, go for the trailer
    fprintf( m_outputFile,
             "trailer\n"
             "<< /Size %lu /Root %d 0 R /Info %d 0 R >>\n"
             "startxref\n"
             "%ld\n" // The offset we saved before
             "%%%%EOF\n",
             (unsigned long) m_xrefTable.size(), catalogHandle, infoDictHandle, xref_start );

    fclose( m_outputFile );
    m_outputFile = nullptr;

    return true;
}


void PDF_PLOTTER::Text( const VECTOR2I&        aPos,
                        const COLOR4D&         aColor,
                        const wxString&        aText,
                        const EDA_ANGLE&       aOrient,
                        const VECTOR2I&        aSize,
                        enum GR_TEXT_H_ALIGN_T aH_justify,
                        enum GR_TEXT_V_ALIGN_T aV_justify,
                        int                    aWidth,
                        bool                   aItalic,
                        bool                   aBold,
                        bool                   aMultilineAllowed,
                        KIFONT::FONT*          aFont,
                        const KIFONT::METRICS& aFontMetrics,
                        void*                  aData )
{
    // PDF files do not like 0 sized texts which create broken files.
    if( aSize.x == 0 || aSize.y == 0 )
        return;

    // Render phantom text (which will be searchable) behind the stroke font.  This won't
    // be pixel-accurate, but it doesn't matter for searching.
    int render_mode = 3;    // invisible

    VECTOR2I pos( aPos );
    const char *fontname = aItalic ? ( aBold ? "/KicadFontBI" : "/KicadFontI" )
                                   : ( aBold ? "/KicadFontB"  : "/KicadFont"  );

    // Compute the copious transformation parameters of the Current Transform Matrix
    double ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f;
    double wideningFactor, heightFactor;

    VECTOR2I t_size( std::abs( aSize.x ), std::abs( aSize.y ) );
    bool     textMirrored = aSize.x < 0;

    computeTextParameters( aPos, aText, aOrient, t_size, textMirrored, aH_justify, aV_justify,
                           aWidth, aItalic, aBold, &wideningFactor, &ctm_a, &ctm_b, &ctm_c, &ctm_d,
                           &ctm_e, &ctm_f, &heightFactor );

    SetColor( aColor );
    SetCurrentLineWidth( aWidth, aData );

    wxStringTokenizer str_tok( aText, " ", wxTOKEN_RET_DELIMS );

    // If aFont is not specilied (== nullptr), use the default kicad stroke font
    if( !aFont )
        aFont = KIFONT::FONT::GetFont();

    VECTOR2I full_box( aFont->StringBoundaryLimits( aText, t_size, aWidth, aBold, aItalic,
                                                    aFontMetrics ) );

    if( textMirrored )
        full_box.x *= -1;

    VECTOR2I box_x( full_box.x, 0 );
    VECTOR2I box_y( 0, full_box.y );

    RotatePoint( box_x, aOrient );
    RotatePoint( box_y, aOrient );

    if( aH_justify == GR_TEXT_H_ALIGN_CENTER )
        pos -= box_x / 2;
    else if( aH_justify == GR_TEXT_H_ALIGN_RIGHT )
        pos -= box_x;

    if( aV_justify == GR_TEXT_V_ALIGN_CENTER )
        pos += box_y / 2;
    else if( aV_justify == GR_TEXT_V_ALIGN_TOP )
        pos += box_y;

    while( str_tok.HasMoreTokens() )
    {
        wxString word = str_tok.GetNextToken();

        computeTextParameters( pos, word, aOrient, t_size, textMirrored, GR_TEXT_H_ALIGN_LEFT,
                               GR_TEXT_V_ALIGN_BOTTOM, aWidth, aItalic, aBold, &wideningFactor,
                               &ctm_a, &ctm_b, &ctm_c, &ctm_d, &ctm_e, &ctm_f, &heightFactor );

        // Extract the changed width and rotate by the orientation to get the offset for the
        // next word
        VECTOR2I bbox( aFont->StringBoundaryLimits( word, t_size, aWidth,
                                                    aBold, aItalic, aFontMetrics ).x, 0 );

        if( textMirrored )
            bbox.x *= -1;

        RotatePoint( bbox, aOrient );
        pos += bbox;

        // Don't try to output a blank string
        if( word.Trim( false ).Trim( true ).empty() )
            continue;

        /* We use the full CTM instead of the text matrix because the same
           coordinate system will be used for the overlining. Also the %f
           for the trig part of the matrix to avoid %g going in exponential
           format (which is not supported) */
        fprintf( m_workFile, "q %f %f %f %f %f %f cm BT %s %g Tf %d Tr %g Tz ",
                 ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f,
                 fontname, heightFactor, render_mode, wideningFactor * 100 );

        std::string txt_pdf = encodeStringForPlotter( word );
        fprintf( m_workFile, "%s Tj ET\n", txt_pdf.c_str() );
        // Restore the CTM
        fputs( "Q\n", m_workFile );
    }

    // Plot the stroked text (if requested)
    PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify, aWidth, aItalic,
                   aBold, aMultilineAllowed, aFont, aFontMetrics );
}


void PDF_PLOTTER::PlotText( const VECTOR2I&        aPos,
                            const COLOR4D&         aColor,
                            const wxString&        aText,
                            const TEXT_ATTRIBUTES& aAttributes,
                            KIFONT::FONT*          aFont,
                            const KIFONT::METRICS& aFontMetrics,
                            void*                  aData )
{
    VECTOR2I size = aAttributes.m_Size;

    // PDF files do not like 0 sized texts which create broken files.
    if( size.x == 0 || size.y == 0 )
        return;

    if( aAttributes.m_Mirrored )
        size.x = -size.x;

    PDF_PLOTTER::Text( aPos, aColor, aText, aAttributes.m_Angle, size, aAttributes.m_Halign,
                       aAttributes.m_Valign, aAttributes.m_StrokeWidth, aAttributes.m_Italic,
                       aAttributes.m_Bold, aAttributes.m_Multiline, aFont, aFontMetrics, aData );
}


void PDF_PLOTTER::HyperlinkBox( const BOX2I& aBox, const wxString& aDestinationURL )
{
    m_hyperlinksInPage.push_back( std::make_pair( aBox, aDestinationURL ) );
}


void PDF_PLOTTER::HyperlinkMenu( const BOX2I& aBox, const std::vector<wxString>& aDestURLs )
{
    m_hyperlinkMenusInPage.push_back( std::make_pair( aBox, aDestURLs ) );
}


void PDF_PLOTTER::Bookmark( const BOX2I& aLocation, const wxString& aSymbolReference,
                            const wxString &aGroupName )
{

    m_bookmarksInPage[aGroupName].push_back( std::make_pair( aLocation, aSymbolReference ) );
}