summaryrefslogtreecommitdiff
path: root/doc/src/LanguageBindingsCSharp.rst
blob: 34932da236f61dbbe6bebe7a73d4c7ec34b11a94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
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
.. Copyright (C) 2001-2023 Artifex Software, Inc.
.. All Rights Reserved.

.. title:: C#


.. include:: header.rst

Introduction
=======================

In the GhostPDL repository a sample C# project can be found in ``/demos/csharp``.

Within this project the following namespaces and corresponding C# files are of relevance:

- GhostAPI_ ``ghostapi.cs``
- GhostNET_ ``ghostnet.cs``
- GhostMono_ ``ghostmono.cs``



Platform & setup
=======================

Ghostscript should be built as a shared library for your platform.

See :ref:`Building Ghostscript<Make.htm>`.


GhostAPI
=======================

:title:`GhostAPI` is the main wrapper responsible for bridging over to the C library and ensuring that the correct DLLs are imported.

:title:`GhostAPI` contains the ``ghostapi`` class which does not need to be instantiated as it provides public static methods. These methods, which mirror their C counterparts, are as follows:


.. list-table::
   :header-rows: 1
   :widths: 25 75

   * - Method
     - Description
   * - gsapi_revision_
     - Returns the revision numbers and strings of the Ghostscript interpreter library.
   * - gsapi_new_instance_
     - Create a new instance of Ghostscript.
   * - gsapi_delete_instance_
     - Destroy an instance of Ghostscript.
   * - gsapi_set_stdio_with_handle_
     - Set the callback functions for ``stdio``, together with the handle to use in the callback functions.
   * - gsapi_set_stdio_
     - Set the callback functions for ``stdio``.
   * - gsapi_set_poll_with_handle_
     - Set the callback function for polling, together with the handle to pass to the callback function.
   * - gsapi_set_poll_
     - Set the callback function for polling.
   * - gsapi_set_display_callback_
     - *deprecated*
   * - gsapi_register_callout_
     - This call registers a callout handler.
   * - gsapi_deregister_callout_
     - This call deregisters a previously registered callout handler.
   * - gsapi_set_arg_encoding_
     - Set the encoding used for the interpretation of all subsequent args supplied via the gsapi interface on this instance.
   * - gsapi_set_default_device_list_
     - Set the string containing the list of default device names.
   * - gsapi_get_default_device_list_
     - Returns a pointer to the current default device string.
   * - gsapi_init_with_args_
     - Initialise the interpreter.
   * - :ref:`gsapi_run_*<gsapi_run_asterisk>`
     - (Wildcard for various "run" methods).
   * - gsapi_exit_
     - Exit the interpreter.
   * - gsapi_set_param_
     - Set a parameter.
   * - gsapi_get_param_
     - Get a parameter.
   * - gsapi_enumerate_params_
     - Enumerate the current parameters.
   * - gsapi_add_control_path_
     - Add a (case sensitive) path to one of the lists of permitted paths for file access.
   * - gsapi_remove_control_path_
     - Remove a (case sensitive) path from one of the lists of permitted paths for file access.
   * - gsapi_purge_control_paths_
     - Clear all the paths from one of the lists of permitted paths for file access.
   * - gsapi_activate_path_control_
     - Enable/Disable path control.
   * - gsapi_is_path_control_active_
     - Query whether path control is activated or not.


:title:`GhostAPI` contains some essential structs & enums as well as a static class for some constants, finally it contains the main ``GSAPI`` class which holds the key methods which interface with the C library.





Structs and Enums
-------------------


``gsapi_revision_t``
~~~~~~~~~~~~~~~~~~~~~~~~~

This struct is used to contain information pertinent to the version of Ghostscript.


.. code-block:: csharp

  public struct gsapi_revision_t
  {
      public IntPtr product;
      public IntPtr copyright;
      public int revision;
      public int revisiondate;
  }


``gs_set_param_type``
~~~~~~~~~~~~~~~~~~~~~~~


.. code-block:: csharp

  public enum gs_set_param_type
  {
      gs_spt_invalid = -1,
      gs_spt_null =    0, /* void * is NULL */
      gs_spt_bool =    1, /* void * is NULL (false) or non-NULL (true) */
      gs_spt_int = 2, /* void * is a pointer to an int */
      gs_spt_float = 3, /* void * is a float * */
      gs_spt_name = 4, /* void * is a char * */
      gs_spt_string =    5, /* void * is a char * */
      gs_spt_long =    6, /* void * is a long * */
      gs_spt_i64 = 7, /* void * is an int64_t * */
      gs_spt_size_t =    8, /* void * is a size_t * */
      gs_spt_parsed =    9, /* void * is a pointer to a char * to be parsed */
      gs_spt_more_to_come = 1 << 31
  };


``gsEncoding``
~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public enum gsEncoding
  {
      GS_ARG_ENCODING_LOCAL = 0,
      GS_ARG_ENCODING_UTF8 = 1,
      GS_ARG_ENCODING_UTF16LE = 2
  };



Constants
-------------------

Constants are stored in the static class ``gsConstants`` for direct referencing.


``gsConstants``
~~~~~~~~~~~~~~~~~~~


.. code-block:: csharp

  static class gsConstants
  {
      public const int E_QUIT = -101;
      public const int GS_READ_BUFFER = 32768;
      public const int DISPLAY_UNUSED_LAST = (1 << 7);
      public const int DISPLAY_COLORS_RGB = (1 << 2);
      public const int DISPLAY_DEPTH_8 = (1 << 11);
      public const int DISPLAY_LITTLEENDIAN = (1 << 16);
      public const int DISPLAY_BIGENDIAN = (0 << 16);
  }




GSAPI
-------------------



Methods contained within are explained below.

:ref:`gsapi_run_*<csharp_gsapi_run_asterisk>` and gsapi_exit_ methods return an ``int`` code which can be interpreted as follows:


.. list-table::
   :header-rows: 1

   * - code
     - status
   * - ``0``
     - no error
   * - ``gsConstants.E_QUIT``
     - "quit" has been executed. This is not an error. gsapi_exit_ must be called next
   * - ``<0``
     - error



.. note::

  For full details on these return codes please see :ref:`The C API return codes<API_Return codes>`.

  All :title:`GSAPI` methods aside from ``gsapi_revision`` and ``gsapi_new_instance`` should pass an instance of Ghostscript as their first parameter with an ``IntPtr`` instance





``gsapi_revision``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This method returns the revision numbers and strings of the Ghostscript interpreter library; you should call it before any other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been loaded.



.. code-block:: csharp

  public static extern int gsapi_revision(ref gsapi_revision_t vers, int size);


.. note::

  The method should write to a reference variable which conforms to the struct `gsapi_revision_t`_.




``gsapi_new_instance``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Creates a new instance of Ghostscript. This instance is passed to most other :title:`GSAPI` methods. Unless Ghostscript has been compiled with the ``GS_THREADSAFE`` define, only one instance at a time is supported.

.. code-block:: csharp

  public static extern int gsapi_new_instance(out IntPtr pinstance,
                                                  IntPtr caller_handle);

.. note::

  The method returns a pointer which represents your instance of Ghostscript.





``gsapi_delete_instance``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Destroy an instance of Ghostscript. Before you call this, Ghostscript must have finished. If Ghostscript has been initialised, you must call gsapi_exit_ beforehand.


.. code-block:: csharp

  public static extern void gsapi_delete_instance(IntPtr instance);


**Sample code:**

.. code-block:: csharp

  GSAPI.gsapi_delete_instance(gsInstance);
  gsInstance = IntPtr.Zero;




``gsapi_set_stdio_with_handle``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set the callback functions for ``stdio``, together with the handle to use in the callback functions. The stdin callback function should return the number of characters read, ``0`` for ``EOF``, or ``-1`` for ``error``. The ``stdout`` and ``stderr`` callback functions should return the number of characters written.

.. note::

  These callbacks do not affect output device I/O when using "%stdout" as the output file. In that case, device output will still be directed to the process "stdout" file descriptor, not to the ``stdio`` callback.


.. code-block:: csharp

  public static extern int gsapi_set_stdio_with_handle(IntPtr instance,
                                             gs_stdio_handler stdin,
                                             gs_stdio_handler stdout,
                                             gs_stdio_handler stderr,
                                                       IntPtr caller_handle);




``gsapi_set_stdio``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set the callback functions for ``stdio``. The handle used in the callbacks will be taken from the value passed to gsapi_new_instance_. Otherwise the behaviour of this function matches gsapi_set_stdio_with_handle_.


.. code-block:: csharp

  public static extern int gsapi_set_stdio_with_handle(IntPtr instance,
                                             gs_stdio_handler stdin,
                                             gs_stdio_handler stdout,
                                             gs_stdio_handler stderr);




``gsapi_set_poll_with_handle``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set the callback function for polling, together with the handle to pass to the callback function. This function will only be called if the Ghostscript interpreter was compiled with ``CHECK_INTERRUPTS`` as described in ``gpcheck.h``.

The polling function should return zero if all is well, and return negative if it wants Ghostscript to abort. This is often used for checking for a user cancel. This can also be used for handling window events or cooperative multitasking.

The polling function is called very frequently during interpretation and rendering so it must be fast. If the function is slow, then using a counter to return 0 immediately some number of times can be used to reduce the performance impact.


.. code-block:: csharp

  public static extern int gsapi_set_poll_with_handle(IntPtr instance,
                                               gsPollHandler pollfn,
                                                      IntPtr caller_handle);



``gsapi_set_poll``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set the callback function for polling. The handle passed to the callback function will be taken from the handle passed to gsapi_new_instance_. Otherwise the behaviour of this function matches gsapi_set_poll_with_handle_.


.. code-block:: csharp

  public static extern int gsapi_set_poll(IntPtr instance,
                                    gsPollHandler pollfn);



``gsapi_set_display_callback``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This call is deprecated; please use gsapi_register_callout_ to register a :ref:`callout handler<gs_callout>` for the display device in preference.


.. code-block:: csharp

  public static extern int gsapi_set_display_callback(IntPtr pinstance,
                                                      IntPtr caller_handle);


``gsapi_register_callout``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This call registers a :ref:`callout handler<gs_callout>`.

.. code-block:: csharp

  public static extern int gsapi_register_callout(IntPtr instance,
                                               gsCallOut callout,
                                                  IntPtr callout_handle);



``gsapi_deregister_callout``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This call deregisters a :ref:`callout handler<gs_callout>` previously registered with gsapi_register_callout_. All three arguments must match exactly for the :ref:`callout handler<gs_callout>` to be deregistered.

.. code-block:: csharp

  public static extern int gsapi_deregister_callout(IntPtr instance,
                                                 gsCallOut callout,
                                                    IntPtr callout_handle);




``gsapi_set_arg_encoding``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set the encoding used for the interpretation of all subsequent arguments supplied via the :title:`GhostAPI` interface on this instance. By default we expect args to be in encoding 0 (the 'local' encoding for this OS). On Windows this means "the currently selected codepage". On Linux this typically means ``utf8``. This means that omitting to call this function will leave Ghostscript running exactly as it always has. Please note that use of the 'local' encoding is now deprecated and should be avoided in new code. This must be called after gsapi_new_instance_ and before gsapi_init_with_args_.


.. code-block:: csharp

  public static extern int gsapi_set_arg_encoding(IntPtr instance,
                                                     int encoding);



``gsapi_set_default_device_list``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Set the string containing the list of default device names, for example "display x11alpha x11 bbox". Allows the calling application to influence which device(s) Ghostscript will try, in order, in its selection of the default device. This must be called after gsapi_new_instance_ and before gsapi_init_with_args_.

.. code-block:: csharp

  public static extern int gsapi_set_default_device_list(IntPtr instance,
                                                         IntPtr list,
                                                        ref int listlen);



``gsapi_get_default_device_list``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Returns a pointer to the current default device string. This must be called after gsapi_new_instance_ and before gsapi_init_with_args_.


.. code-block:: csharp

  public static extern int gsapi_get_default_device_list(IntPtr instance,
                                                     ref IntPtr list,
                                                        ref int listlen);

``gsapi_init_with_args``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To initialise the interpreter, pass your ``instance`` of Ghostscript, your argument count, ``argc`` and your argument variables, ``argv``.


.. code-block:: csharp

  public static extern int gsapi_init_with_args(IntPtr instance,
                                                   int argc,
                                                IntPtr argv);




.. _csharp_gsapi_run_asterisk:


``gsapi_run_*``
~~~~~~~~~~~~~~~~~~

If these functions return ``<= -100``, either quit or a fatal error has occured. You must call gsapi_exit_ next. The only exception is gsapi_run_string_continue_ which will return ``gs_error_NeedInput`` if all is well.

There is a 64 KB length limit on any buffer submitted to a ``gsapi_run_*`` function for processing. If you have more than 65535 bytes of input then you must split it into smaller pieces and submit each in a separate gsapi_run_string_continue_ call.


``gsapi_run_string_begin``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public static extern int gsapi_run_string_begin(IntPtr instance,
                                                     int usererr,
                                                 ref int exitcode);

``gsapi_run_string_continue``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public static extern int gsapi_run_string_continue(IntPtr instance,
                                                     IntPtr command,
                                                        int count,
                                                        int usererr,
                                                    ref int exitcode);



``gsapi_run_string_with_length``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public static extern int gsapi_run_string_with_length(IntPtr instance,
                                                           IntPtr command,
                                                             uint length,
                                                              int usererr,
                                                          ref int exitcode);

``gsapi_run_string``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public static extern int gsapi_run_string(IntPtr instance,
                                            IntPtr command,
                                               int usererr,
                                           ref int exitcode);

``gsapi_run_string_end``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public static extern int gsapi_run_string_end(IntPtr instance,
                                                   int usererr,
                                               ref int exitcode);


``gsapi_run_file``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: csharp

  public static extern int gsapi_run_file(IntPtr instance,
                                          IntPtr filename,
                                             int usererr,
                                         ref int exitcode);




``gsapi_exit``
~~~~~~~~~~~~~~~~


Exit the interpreter. This must be called on shutdown if gsapi_init_with_args_ has been called, and just before gsapi_delete_instance_.


.. code-block:: csharp

  public static extern int gsapi_exit(IntPtr instance);



``gsapi_set_param``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sets a parameter.

Broadly, this is equivalent to setting a parameter using ``-d``, ``-s`` or ``-p`` on the command line. This call cannot be made during a gsapi_run_string_ operation.

Parameters in this context are not the same as 'arguments' as processed by gsapi_init_with_args_, but often the same thing can be achieved. For example, with gsapi_init_with_args_, we can pass "-r200" to change the resolution. Broadly the same thing can be achieved by using gsapi_set_param_ to set a parsed value of "<</HWResolution [ 200.0 200.0 ]>>".

Internally, when we set a parameter, we perform an ``initgraphics`` operation. This means that using gsapi_set_param_ other than at the start of a page is likely to give unexpected results.

Attempting to set a parameter that the device does not recognise will be silently ignored, and that parameter will not be found in subsequent gsapi_get_param_ calls.


.. code-block:: csharp

  public static extern int gsapi_set_param(IntPtr instance,
                                           IntPtr param,
                                           IntPtr value,
                                gs_set_param_type type);



.. note::

  The type argument, as a ``gs_set_param_type``, dictates the kind of object that the value argument points to.

  For more on the C implementation of parameters see: :ref:`Ghostscript parameters in C<Use_Setting Parameters>`.



``gsapi_get_param``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Retrieve the current value of a parameter.

If an error occurs, the return value is negative. Otherwise the return value is the number of bytes required for storage of the value. Call once with value ``NULL`` to get the number of bytes required, then call again with value pointing to at least the required number of bytes where the value will be copied out. Note that the caller is required to know the type of value in order to get it. For all types other than ``gs_spt_string``, ``gs_spt_name``, and ``gs_spt_parsed`` knowing the type means you already know the size required.

This call retrieves parameters/values that have made it to the device. Thus, any values set using ``gs_spt_more_to_come`` without a following call omitting that flag will not be retrieved. Similarly, attempting to get a parameter before gsapi_init_with_args_ has been called will not list any, even if gsapi_set_param_ has been used.

Attempting to read a parameter that is not set will return ``gs_error_undefined`` (-21). Note that calling gsapi_set_param_ followed by gsapi_get_param_ may not find the value, if the device did not recognise the key as being one of its configuration keys.

For further documentation please refer to :ref:`the C API<API_gsapi_get_param>`.


.. code-block:: csharp

  public static extern int gsapi_get_param(IntPtr instance,
                                           IntPtr param,
                                           IntPtr value,
                                gs_set_param_type type);



``gsapi_enumerate_params``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enumerate the current parameters. Call repeatedly to list out the current parameters.

The first call should have ``iter = NULL``. Subsequent calls should pass the same pointer in so the iterator can be updated. Negative return codes indicate error, 0 success, and 1 indicates that there are no more keys to read. On success, key will be updated to point to a null terminated string with the key name that is guaranteed to be valid until the next call to gsapi_enumerate_params_. If type is non ``NULL`` then the pointer type will be updated to have the type of the parameter.

.. note::

  Only one enumeration can happen at a time. Starting a second enumeration will reset the first.

The enumeration only returns parameters/values that have made it to the device. Thus, any values set using the ``gs_spt_more_to_come`` without a following call omitting that flag will not be retrieved. Similarly, attempting to enumerate parameters before gsapi_init_with_args_ has been called will not list any, even if gsapi_set_param_ has been used.


.. code-block:: csharp

  public static extern int gsapi_enumerate_params(IntPtr instance,
                                              out IntPtr iter,
                                              out IntPtr key,
                                                  IntPtr type);



``gsapi_add_control_path``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Add a (case sensitive) path to one of the lists of :ref:`permitted paths<Use Safer>` for file access.


.. code-block:: csharp

  public static extern int gsapi_add_control_path(IntPtr instance,
                                                     int type,
                                                  IntPtr path);

``gsapi_remove_control_path``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Remove a (case sensitive) path from one of the lists of :ref:`permitted paths<Use Safer>` for file access.


.. code-block:: csharp

  public static extern int gsapi_remove_control_path(IntPtr instance,
                                                        int type,
                                                     IntPtr path);

``gsapi_purge_control_paths``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Clear all the paths from one of the lists of :ref:`permitted paths<Use Safer>` for file access.


.. code-block:: csharp

  public static extern void gsapi_purge_control_paths(IntPtr instance,
                                                         int type);



``gsapi_activate_path_control``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enable/Disable path control (i.e. whether paths are checked against :ref:`permitted paths<Use Safer>` before access is granted).


.. code-block:: csharp

  public static extern void gsapi_activate_path_control(IntPtr instance,
                                                           int enable);


``gsapi_is_path_control_active``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Query whether path control is activated or not.

.. code-block:: csharp

  public static extern int gsapi_is_path_control_active(IntPtr instance);



Callback and Callout prototypes
--------------------------------------

:title:`GSAPI` also defines some prototype pointers which are defined as follows.

``gs_stdio_handler``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


.. code-block:: csharp

  /* Callback proto for stdio */
  public delegate int gs_stdio_handler(IntPtr caller_handle,
                                       IntPtr buffer,
                                          int len);

``gsPollHandler``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


.. code-block:: csharp

  /* Callback proto for poll function */
  public delegate int gsPollHandler(IntPtr caller_handle);


.. _gs_callout:

``gsCallOut``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


.. code-block:: csharp

  /* Callout proto */
  public delegate int gsCallOut(IntPtr callout_handle,
                                IntPtr device_name,
                                   int id,
                                   int size,
                                IntPtr data);


GhostNET
=======================

:title:`GhostNET` is the `.NET`_ interface into :title:`GhostAPI`. It exemplifies how to do more complex operations involving multiple API calls and sequences. See the table below for the main methods:


.. list-table::
   :header-rows: 1
   :widths: 20 75 5

   * - Method
     - Description
     - Notes
   * - :ref:`GetVersion<GhostNET_GetVersion>`
     - Returns the version of Ghostscript.
     -
   * - :ref:`DisplayDeviceOpen<GhostNET_DisplayDeviceOpen>`
     - Sets up the display device ahead of time.
     -
   * - :ref:`DisplayDeviceClose<GhostNET_DisplayDeviceClose>`
     - Closes the display device and deletes the instance.
     -
   * - :ref:`GetPageCount<GhostNET_GetPageCount>`
     - Returns the page count for the document.
     -
   * - :ref:`CreateXPS<GhostNET_CreateXPS>`
     - Launches a thread to create an XPS document for Windows printing.
     - :ref:`asynchronous<Delegates>`
   * - :ref:`DistillPS<GhostNET_DistillPS>`
     - Launches a thread rendering all the pages of a supplied PostScript file to a PDF.
     - :ref:`asynchronous<GhostNET_Delegates>`
   * - :ref:`DisplayDeviceRunFile<GhostNET_DisplayDeviceRunFile>`
     - Launches a thread to run a file with the display device.
     - :ref:`asynchronous<GhostNET_Delegates>`
   * - :ref:`DisplayDeviceRenderThumbs<GhostNET_DisplayDeviceRenderThumbs>`
     - Launches a thread rendering all the pages with the display device to collect thumbnail images.
     - :ref:`asynchronous<GhostNET_Delegates>`
   * - :ref:`DisplayDeviceRenderPages<GhostNET_DisplayDeviceRenderPages>`
     - Launches a thread rendering a set of pages with the display device.
     - :ref:`asynchronous<GhostNET_Delegates>`
   * - :ref:`GetStatus<GhostNET_GetStatus>`
     - Returns the current status of Ghostscript.
     -
   * - :ref:`Cancel<GhostNET_Cancel>`
     - Cancels asynchronous operations.
     -
   * - :ref:`GhostscriptException<GhostNET_GhostscriptException>`
     - An application developer can log any exceptions in this public class.
     -


In ``demos/csharp/windows/ghostnet.sln`` there is a sample C# demo project.

This project can be opened in `Visual Studio`_ and used to test the Ghostscript API alongside a UI which handles opening PostScript and PDF files. The sample application here allows for file browsing and Ghostscript file viewing.

Below is a screenshot of the sample application with a PDF open:


.. note we embedd the image with raw HTML because Sphinx is incapable of doing percentage style widths ... :(

.. raw:: html

   <img src="_static/ghostnet-wpf-example.png" width=100%/>




Enums
--------


Tasks
~~~~~~~~~~~~~~~~

The Ghostscript task type ``enum`` is used to inform :title:`GhostAPI` of the type of operation which is being requested.


.. list-table::
   :header-rows: 1

   * - Task
     - Description
   * - ``PS_DISTILL``
     - Task associated with converting a PostScript stream to a PDF document.
   * - ``CREATE_XPS``
     - Task associated with outputting a copy of a document to XPS.
   * - ``SAVE_RESULT``
     - Task associated with saving documents.
   * - ``GET_PAGE_COUNT``
     - Task associated with getting the page count of a document.
   * - ``GENERIC``
     - Generic task identifier.
   * - ``DISPLAY_DEV_THUMBS``
     - Display Device task associated with rendering thumbnails.
   * - ``DISPLAY_DEV_NON_PDF``
     - Display Device task associated with non-PDF or non-XPS rendering (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`).
   * - ``DISPLAY_DEV_PDF``
     - Display Device task associated with PDF & XPS rendering (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`).
   * - ``DISPLAY_DEV_RUN_FILE``
     - Display Device task associated with running files.


Task types are defined as ``GS_Task_t``.


.. code-block:: csharp

  public enum GS_Task_t
  {
      PS_DISTILL,
      CREATE_XPS,
      SAVE_RESULT,
      GET_PAGE_COUNT,
      GENERIC,
      DISPLAY_DEV_THUMBS,
      DISPLAY_DEV_NON_PDF,
      DISPLAY_DEV_PDF,
      DISPLAY_DEV_RUN_FILE
  }







Results
~~~~~~~~~~~~~~~~

Result types are defined as ``GS_Result_t``.


.. code-block:: csharp

  public enum GS_Result_t
  {
      gsOK,
      gsFAILED,
      gsCANCELLED
  }


.. _GhostNET_Status:

Status
~~~~~~~~~~~~~~~~

Status types are defined as ``gsStatus``.


.. code-block:: csharp

  public enum gsStatus
  {
      GS_READY,
      GS_BUSY,
      GS_ERROR
  }



The Parameter Struct
-------------------------

The parameter struct ``gsParamState_t`` allows for bundles of information to be processed by Ghostscript to complete overall requests.


.. code-block:: csharp

  public struct gsParamState_t
  {
      public String outputfile;
      public String inputfile;
      public GS_Task_t task;
      public GS_Result_t result;
      public int num_pages;
      public List<int> pages;
      public int firstpage;
      public int lastpage;
      public int currpage;
      public List<String> args;
      public int return_code;
      public double zoom;
      public bool aa;
      public bool is_valid;
  };


Parameters explained
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Setting up your parameters (with any dedicated bespoke method(s) which your application requires) is needed when communicating directly with :title:`GhostAPI`.

When requesting Ghostscript to process an operation an application developer should send a parameter payload which defines the details for the operation.

For example in :title:`GhostNET` we can see the public method as follows:


.. code-block:: csharp

  public gsStatus DistillPS(String fileName, int resolution)
  {
      gsParamState_t gsparams = new gsParamState_t();
      gsparams.args = new List<string>();

      gsparams.inputfile = fileName;
      gsparams.args.Add("gs");
      gsparams.args.Add("-sDEVICE=pdfwrite");
      gsparams.outputfile = Path.GetTempFileName();
      gsparams.args.Add("-o" + gsparams.outputfile);
      gsparams.task = GS_Task_t.PS_DISTILL;

      return RunGhostscriptAsync(gsparams);
  }



Here we can see a parameter payload being setup before being passed on to the asynchronous method ``RunGhostscriptAsync`` which sets up a worker thread to run according to the task type in the payload.

:title:`GhostNET` handles many common operations on an application developer's behalf, however if you require to write your own methods to interface with :title:`GhostAPI` then referring to the public methods in :title:`GhostNET` is a good starting point.

For full documentation on parameters refer to :ref:`Ghostscript parameters<Use_Setting Parameters>`.





The Event class
------------------

:title:`GhostNET` contains a public class ``gsEventArgs`` which is an extension of the C# class ``EventArgs``. This class is used to set and get events as they occur. :title:`GhostNET` will create these payloads and deliver them back to the application layer's ``ProgressCallBack`` method asynchronously.


.. code-block:: csharp

  public class gsEventArgs : EventArgs
  {
      private bool m_completed;
      private int m_progress;
      private gsParamState_t m_param;
      public bool Completed
      {
          get { return m_completed; }
      }
      public gsParamState_t Params
      {
          get { return m_param; }
      }
      public int Progress
      {
          get { return m_progress; }
      }
      public gsEventArgs(bool completed, int progress, gsParamState_t param)
      {
          m_completed = completed;
          m_progress = progress;
          m_param = param;
      }
  }


GSNET
-----------

This class should be instantiated as a member variable in your application with callback definitions setup as required.

Handlers for asynchronous operations can injected by providing your own bespoke callback methods to your instance's ``ProgressCallBack`` function.


Sample code
~~~~~~~~~~~~~~~~

.. code-block:: csharp

  /* Set up ghostscript with callbacks for system updates */
  m_ghostscript = new GSNET();
  m_ghostscript.ProgressCallBack += new GSNET.Progress(gsProgress);
  m_ghostscript.StdIOCallBack += new GSNET.StdIO(gsIO);
  m_ghostscript.DLLProblemCallBack += new GSNET.DLLProblem(gsDLL);
  m_ghostscript.PageRenderedCallBack += new GSNET.PageRendered(gsPageRendered);
  m_ghostscript.DisplayDeviceOpen();

  /* example callback stubs for asynchronous operations */
  private void gsProgress(gsEventArgs asyncInformation)
  {
      Console.WriteLine($"gsProgress().progress:{asyncInformation.Progress}");

      if (asyncInformation.Completed) // task complete
      {
          // what was the task?
          switch (asyncInformation.Params.task)
          {
              case GS_Task_t.CREATE_XPS:
                  Console.WriteLine($"CREATE_XPS.outputfile:");
                  Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
                  break;

              case GS_Task_t.PS_DISTILL:
                  Console.WriteLine($"PS_DISTILL.outputfile:");
                  Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
                  break;

              case GS_Task_t.SAVE_RESULT:

                  break;

              case GS_Task_t.DISPLAY_DEV_THUMBS:

                  break;

              case GS_Task_t.DISPLAY_DEV_RUN_FILE:

                  break;

              case GS_Task_t.DISPLAY_DEV_PDF:

                  break;

              case GS_Task_t.DISPLAY_DEV_NON_PDF:

                  break;

              default:

                  break;
          }

          // task failed
          if (asyncInformation.Params.result == GS_Result_t.gsFAILED)
          {
              switch (asyncInformation.Params.task)
              {
                  case GS_Task_t.CREATE_XPS:

                      break;

                  case GS_Task_t.PS_DISTILL:

                      break;

                  case GS_Task_t.SAVE_RESULT:

                      break;

                  default:

                      break;
              }
              return;
          }

          // task cancelled
          if (asyncInformation.Params.result == GS_Result_t.gsCANCELLED)
          {

          }
      }
      else // task is still running
      {
          switch (asyncInformation.Params.task)
          {
              case GS_Task_t.CREATE_XPS:

                  break;

              case GS_Task_t.PS_DISTILL:

                  break;

              case GS_Task_t.SAVE_RESULT:

                  break;
          }
      }
  }

  private void gsIO(String message, int len)
  {
      Console.WriteLine($"gsIO().message:{message}, length:{len}");
  }

  private void gsDLL(String message)
  {
      Console.WriteLine($"gsDLL().message:{message}");
  }

  private void gsPageRendered(int width,
                              int height,
                              int raster,
                              IntPtr data,
                              gsParamState_t state)
  {

  };


.. note::

  Once a Ghostscript operation is in progress any defined callback functions will be called as the operation runs up unto completion. These callback methods are essential for your application to interpret activity events and react accordingly.

An explanation of callbacks and the available public methods within ``GSNET`` are explained below.



.. _GhostNET_Delegates:

Delegates
~~~~~~~~~~~~~~~

To handle *asynchronous* events :title:`GhostNET` has four delegates which define callback methods that an application can assign to.



.. list-table::
   :header-rows: 1

   * - Callback
     - Description
   * - ``DLLProblemCallBack``
     - Occurs if there is some issue with the Ghostscript DLL.
   * - ``StdIOCallBack``
     - Occurs if Ghostscript outputs something to ``stderr`` or ``stdout``.
   * - ``ProgressCallBack``
     - Occurs as Ghostscript makes its way through a file.
   * - ``PageRenderedCallBack``
     - Occurs when a page has been rendered and the data from the display device is ready.



``DLLProblemCallBack``
"""""""""""""""""""""""""

.. code-block:: csharp

  internal delegate void DLLProblem(String mess);
  internal event DLLProblem DLLProblemCallBack;


``StdIOCallBack``
""""""""""""""""""""""

.. code-block:: csharp

  internal delegate void StdIO(String mess,
                               int len);
  internal event StdIO StdIOCallBack;

``ProgressCallBack``
""""""""""""""""""""""


.. code-block:: csharp

  internal delegate void Progress(gsEventArgs info);
  internal event Progress ProgressCallBack;


``PageRenderedCallBack``
""""""""""""""""""""""""""""

.. code-block:: csharp

  internal delegate void PageRendered(int width,
                                      int height,
                                      int raster,
                                   IntPtr data,
                           gsParamState_t state);
  internal event PageRendered PageRenderedCallBack;



.. _GhostNET_GetVersion:


``GetVersion``
~~~~~~~~~~~~~~

Use this method to get Ghostscript version info as a ``String``.


.. code-block:: csharp

  public String GetVersion()


**Sample code:**

.. code-block:: csharp

  String gs_vers = m_ghostscript.GetVersion();


.. note::

  An exception will be thrown if there is any issue with the Ghostscript DLL.




.. _GhostNET_DisplayDeviceOpen:

``DisplayDeviceOpen``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sets up the :ref:`display device<Devices_Display_Devices>` ahead of time.

.. code-block:: csharp

  public gsParamState_t DisplayDeviceOpen()


**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceOpen();


.. note::

  Calling this method instantiates Ghostscript and configures the encoding and the callbacks for the display device.



.. _GhostNET_DisplayDeviceClose:


``DisplayDeviceClose``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Closes the :ref:`display device<Devices_Display_Devices>` and deletes the instance.


.. code-block:: csharp

  public gsParamState_t DisplayDeviceClose()

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceClose();


.. note::

  Calling this method :ref:`deletes Ghostscript<gsapi_delete_instance>`.



.. _GhostNET_GetPageCount:


``GetPageCount``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use this method to get the number of pages in a supplied document.


.. code-block:: csharp

  public int GetPageCount(String fileName)

**Sample code:**

.. code-block:: csharp

  int page_number = m_ghostscript.GetPageCount("my_document.pdf");

.. note::

  If Ghostscript is unable to determine the page count then this method will return ``-1``.


.. _GhostNET_CreateXPS:

``CreateXPS``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread to create an XPS document for Windows printing. This method is :ref:`asynchronous<GhostNET_Delegates>` and logic should be hooked into your application upon :ref:`GSNET instantiation<GSNET>` to interpret progress.


.. code-block:: csharp

  public gsStatus CreateXPS(String fileName,
                               int resolution,
                               int num_pages,
                            double width,
                            double height,
                              bool fit_page,
                               int firstpage,
                               int lastpage)

**Sample code:**

.. code-block:: csharp

  m_ghostscript.CreateXPS("my_document.pdf",
                          300,
                          10,
                          1000,
                          1000,
                          true,
                          0,
                          9);


.. _GhostNET_DistillPS:


``DistillPS``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering all the pages of a supplied PostScript file to a PDF.


.. code-block:: csharp

  public gsStatus DistillPS(String fileName, int resolution)


**Sample code:**

.. code-block:: csharp

  m_ghostscript.DistillPS("my_postscript_document.ps", 300);



.. _GhostNET_DisplayDeviceRunFile:


``DisplayDeviceRunFile``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread to run a file with the :ref:`display device<Devices_Display_Devices>`.


.. code-block:: csharp

  public gsStatus DisplayDeviceRunFile(String fileName,
                                       double zoom,
                                         bool aa, // anti-aliasing value
                                          int firstpage,
                                          int lastpage)

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceRunFile("my_document.pdf",
                                     1.0,
                                     true,
                                     0,
                                     9);


.. _GhostNET_DisplayDeviceRenderThumbs:

``DisplayDeviceRenderThumbs``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering all the pages with the :ref:`display device<Devices_Display_Devices>` to collect thumbnail images.

Recommended zoom level for thumbnails is between 0.05 and 0.2, additionally anti-aliasing is probably not required.


.. code-block:: csharp

  public gsStatus DisplayDeviceRenderThumbs(String fileName,
                                            double zoom,
                                              bool aa)

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceRenderThumbs("my_document.pdf",
                                          0.1,
                                          false);



.. _GhostNET_DisplayDeviceRenderPages:


``DisplayDeviceRenderPages``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering a set of pages with the :ref:`display device<Devices_Display_Devices>`. For use with languages that can be indexed via pages which include PDF and XPS. (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`)


.. code-block:: csharp

  public gsStatus DisplayDeviceRenderPages(String fileName,
                                              int first_page,
                                              int last_page,
                                           double zoom)

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceRenderPages("my_document.pdf",
                                         0,
                                         9,
                                         1.0);


.. _GhostNET_GetStatus:

``GetStatus``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Returns the current :ref:`status<GhostNET_Status>` of Ghostscript.


.. code-block:: csharp

  public gsStatus GetStatus()

**Sample code:**

.. code-block:: csharp

  gsStatus status = m_ghostscript.GetStatus();



.. _GhostNET_Cancel:


``Cancel``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Cancels :ref:`asynchronous<GhostNET_Delegates>` operations.


.. code-block:: csharp

  public void Cancel()


**Sample code:**

.. code-block:: csharp

  m_ghostscript.Cancel();



.. _GhostNET_GhostscriptException:


``GhostscriptException``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

An application developer can log any exceptions in this public class as required by editing the constructor.


.. code-block:: csharp

  public class GhostscriptException : Exception
  {
      public GhostscriptException(string message) : base(message)
      {
          // Report exceptions as required
      }
  }










GhostMono
=======================

:title:`GhostMono` is the C# interface into the :title:`GhostAPI` library and is developed for Linux systems.

As such :title:`GhostMono` is the Mono_ equivalent of :title:`GhostNET` with no dependency on a Windows environment.






Enums
--------


Tasks
~~~~~~~~~~~~~~~~

The Ghostscript task type ``enum`` is used to inform :title:`GhostAPI` of the type of operation which is being requested.


.. list-table::
   :header-rows: 1

   * - Task
     - Description
   * - ``PS_DISTILL``
     - Task associated with converting a PostScript stream to a PDF document.
   * - ``CREATE_XPS``
     - Task associated with outputting a copy of a document to XPS.
   * - ``SAVE_RESULT``
     - Task associated with saving documents.
   * - ``GET_PAGE_COUNT``
     - Task associated with getting the page count of a document.
   * - ``GENERIC``
     - Generic task identifier.
   * - ``DISPLAY_DEV_THUMBS``
     - Display Device task associated with rendering thumbnails.
   * - ``DISPLAY_DEV_NON_PDF``
     - Display Device task associated with non-PDF or non-XPS rendering (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`).
   * - ``DISPLAY_DEV_PDF``
     - Display Device task associated with PDF & XPS rendering (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`).
   * - ``DISPLAY_DEV_RUN_FILE``
     - Display Device task associated with running files.


Task types are defined as ``GS_Task_t``.


.. code-block:: csharp

  public enum GS_Task_t
  {
      PS_DISTILL,
      CREATE_XPS,
      SAVE_RESULT,
      GET_PAGE_COUNT,
      GENERIC,
      DISPLAY_DEV_THUMBS,
      DISPLAY_DEV_NON_PDF,
      DISPLAY_DEV_PDF,
      DISPLAY_DEV_RUN_FILE
  }







Results
~~~~~~~~~~~~~~~~

Result types are defined as ``GS_Result_t``.


.. code-block:: csharp

  public enum GS_Result_t
  {
      gsOK,
      gsFAILED,
      gsCANCELLED
  }


Status
~~~~~~~~~~~~~~~~

Status types are defined as ``gsStatus``.


.. code-block:: csharp

  public enum gsStatus
  {
      GS_READY,
      GS_BUSY,
      GS_ERROR
  }



The Parameter Struct
-------------------------

The parameter struct ``gsParamState_t`` allows for bundles of information to be processed by Ghostscript to complete overall requests.


.. code-block:: csharp

  public struct gsParamState_t
  {
      public String outputfile;
      public String inputfile;
      public GS_Task_t task;
      public GS_Result_t result;
      public int num_pages;
      public List<int> pages;
      public int firstpage;
      public int lastpage;
      public int currpage;
      public List<String> args;
      public int return_code;
      public double zoom;
  };


Parameters explained
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Setting up your parameters (with any dedicated bespoke method(s) which your application requires) is needed when communicating directly with :title:`GhostAPI`.

When requesting Ghostscript to process an operation an application developer should send a parameter payload which defines the details for the operation.

For example in :title:`GhostMono` we can see the public method as follows:

.. code-block:: csharp

  public gsStatus DistillPS(String fileName, int resolution)
  {
      gsParamState_t gsparams = new gsParamState_t();
      gsparams.args = new List<string>();

      gsparams.inputfile = fileName;
      gsparams.args.Add("gs");
      gsparams.args.Add("-dNOPAUSE");
      gsparams.args.Add("-dBATCH");
      gsparams.args.Add("-I%rom%Resource/Init/");
      gsparams.args.Add("-dSAFER");
      gsparams.args.Add("-sDEVICE=pdfwrite");
      gsparams.outputfile = Path.GetTempFileName();
      gsparams.args.Add("-o" + gsparams.outputfile);
      gsparams.task = GS_Task_t.PS_DISTILL;

      return RunGhostscriptAsync(gsparams);
  }


Here we can see a parameter payload being setup before being passed on to the asynchronous method ``RunGhostscriptAsync`` which sets up a worker thread to run according to the task type in the payload.

:title:`GhostMono` handles many common operations on an application developer's behalf, however if you require to write your own methods to interface with :title:`GhostAPI` then referring to the public methods in :title:`GhostMono` is a good starting point.

For full documentation on parameters refer to :ref:`Ghostscript parameters in C<Use_Setting Parameters>`.




The Event class
--------------------

:title:`GhostMono` contains a public class ``gsThreadCallBack``. This class is used to set and get callback information as they occur. :title:`GhostMono` will create these payloads and deliver them back to the application layer's ``ProgressCallBack`` method asynchronously.


.. code-block:: csharp

  public class gsThreadCallBack
  {
      private bool m_completed;
      private int m_progress;
      private gsParamState_t m_param;
      public bool Completed
      {
          get { return m_completed; }
      }
      public gsParamState_t Params
      {
          get { return m_param; }
      }
      public int Progress
      {
          get { return m_progress; }
      }
      public gsThreadCallBack(bool completed, int progress, gsParamState_t param)
      {
          m_completed = completed;
          m_progress = progress;
          m_param = param;
      }
  }


GSMONO
----------

This class should be instantiated as a member variable in your application with callback definitions setup as required.

Handlers for asynchronous operations can injected by providing your own bespoke callback methods to your instance's ``ProgressCallBack`` function.


.. code-block:: csharp

  /* Set up Ghostscript with callbacks for system updates */
  m_ghostscript = new GSMONO();
  m_ghostscript.ProgressCallBack += new GSMONO.Progress(gsProgress);
  m_ghostscript.StdIOCallBack += new GSMONO.StdIO(gsIO);
  m_ghostscript.DLLProblemCallBack += new GSMONO.DLLProblem(gsDLL);
  m_ghostscript.PageRenderedCallBack += new GSMONO.PageRendered(gsPageRendered);
  m_ghostscript.DisplayDeviceOpen();

  /* example callback stubs for asynchronous operations */
  private void gsProgress(gsThreadCallBack asyncInformation)
  {
      Console.WriteLine($"gsProgress().progress:{asyncInformation.Progress}");

      if (asyncInformation.Completed) // task complete
      {
          // what was the task?
          switch (asyncInformation.Params.task)
          {
              case GS_Task_t.CREATE_XPS:
                  Console.WriteLine($"CREATE_XPS.outputfile:");
                  Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
                  break;

              case GS_Task_t.PS_DISTILL:
                  Console.WriteLine($"PS_DISTILL.outputfile:");
                  Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
                  break;

              case GS_Task_t.SAVE_RESULT:

                  break;

              case GS_Task_t.DISPLAY_DEV_THUMBS:

                  break;

              case GS_Task_t.DISPLAY_DEV_RUN_FILE:

                  break;

              case GS_Task_t.DISPLAY_DEV_PDF:

                  break;

              case GS_Task_t.DISPLAY_DEV_NON_PDF:

                  break;

              default:

                  break;
          }

          // task failed
          if (asyncInformation.Params.result == GS_Result_t.gsFAILED)
          {
              switch (asyncInformation.Params.task)
              {
                  case GS_Task_t.CREATE_XPS:

                      break;

                  case GS_Task_t.PS_DISTILL:

                      break;

                  case GS_Task_t.SAVE_RESULT:

                      break;

                  default:

                      break;
              }
              return;
          }

          // task cancelled
          if (asyncInformation.Params.result == GS_Result_t.gsCANCELLED)
          {

          }
      }
      else // task is still running
      {
          switch (asyncInformation.Params.task)
          {
              case GS_Task_t.CREATE_XPS:

                  break;

              case GS_Task_t.PS_DISTILL:

                  break;

              case GS_Task_t.SAVE_RESULT:

                  break;
          }
      }
  }

  private void gsIO(String message, int len)
  {
      Console.WriteLine($"gsIO().message:{message}, length:{len}");
  }

  private void gsDLL(String message)
  {
      Console.WriteLine($"gsDLL().message:{message}");
  }

  private void gsPageRendered(int width,
                              int height,
                              int raster,
                              IntPtr data,
                              gsParamState_t state)
  {

  };



.. note::

  Once a Ghostscript operation is in progress any defined callback functions will be called as the operation runs up unto completion. These callback methods are essential for your application to interpret activity events and react accordingly.


An explanation of callbacks and the available public methods within :title:`GSMONO` are explained below.




Delegates
~~~~~~~~~~~~~~

To handle *asynchronous events* :title:`GhostMONO` has four delegates which define callback methods that an application can assign to.


.. list-table::
   :header-rows: 1

   * - Callback
     - Description
   * - ``DLLProblemCallBack``
     - Occurs if there is some issue with the Ghostscript Shared Object (libgpdl.so)
   * - ``StdIOCallBack``
     - Occurs if Ghostscript outputs something to ``stderr`` or ``stdout``.
   * - ``ProgressCallBack``
     - Occurs as Ghostscript makes its way through a file.
   * - ``PageRenderedCallBack``
     - Occurs when a page has been rendered and the data from the display device is ready.



``DLLProblemCallBack``
"""""""""""""""""""""""""

.. code-block:: csharp

  internal delegate void DLLProblem(String mess);
  internal event DLLProblem DLLProblemCallBack;


``StdIOCallBack``
""""""""""""""""""""""

.. code-block:: csharp

  internal delegate void StdIO(String mess,
                               int len);
  internal event StdIO StdIOCallBack;

``ProgressCallBack``
""""""""""""""""""""""


.. code-block:: csharp

  internal delegate void Progress(gsEventArgs info);
  internal event Progress ProgressCallBack;


``PageRenderedCallBack``
""""""""""""""""""""""""""""

.. code-block:: csharp

  internal delegate void PageRendered(int width,
                                      int height,
                                      int raster,
                                   IntPtr data,
                           gsParamState_t state);
  internal event PageRendered PageRenderedCallBack;





``GetVersion``
~~~~~~~~~~~~~~

Use this method to get Ghostscript version info as a ``String``.


.. code-block:: csharp

  public String GetVersion()


**Sample code:**

.. code-block:: csharp

  String gs_vers = m_ghostscript.GetVersion();


.. note::

  An exception will be thrown if there is any issue with the Ghostscript DLL.






``DisplayDeviceOpen``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sets up the :ref:`display device<Devices_Display_Devices>` ahead of time.

.. code-block:: csharp

  public gsParamState_t DisplayDeviceOpen()


**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceOpen();


.. note::

  Calling this method instantiates Ghostscript and configures the encoding and the callbacks for the display device.




``DisplayDeviceClose``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Closes the :ref:`display device<Devices_Display_Devices>` and deletes the instance.


.. code-block:: csharp

  public gsParamState_t DisplayDeviceClose()

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceClose();


.. note::

  Calling this method :ref:`deletes Ghostscript<gsapi_delete_instance>`.




``GetPageCount``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use this method to get the number of pages in a supplied document.


.. code-block:: csharp

  public int GetPageCount(String fileName)

**Sample code:**

.. code-block:: csharp

  int page_number = m_ghostscript.GetPageCount("my_document.pdf");

.. note::

  If Ghostscript is unable to determine the page count then this method will return ``-1``.



``DistillPS``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering all the pages of a supplied PostScript file to a PDF.


.. code-block:: csharp

  public gsStatus DistillPS(String fileName, int resolution)


**Sample code:**

.. code-block:: csharp

  m_ghostscript.DistillPS("my_postscript_document.ps", 300);



``DisplayDeviceRenderAll``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering all the document pages with the :ref:`display device<Devices_Display_Devices>`. For use with languages that can be indexed via pages which include PDF and XPS. (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`)


.. code-block:: csharp

  public gsStatus DisplayDeviceRenderAll(String fileName, double zoom, bool aa, GS_Task_t task)


**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceRenderAll("my_document.pdf",
                                       0.1,
                                       false,
                                       GS_Task_t.DISPLAY_DEV_THUMBS_NON_PDF);



``DisplayDeviceRenderThumbs``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering all the pages with the :ref:`display device<Devices_Display_Devices>` to collect thumbnail images.

Recommended zoom level for thumbnails is between 0.05 and 0.2, additionally anti-aliasing is probably not required.


.. code-block:: csharp

  public gsStatus DisplayDeviceRenderThumbs(String fileName,
                                            double zoom,
                                              bool aa)

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceRenderThumbs("my_document.pdf",
                                          0.1,
                                          false);



``DisplayDeviceRenderPages``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Launches a thread rendering a set of pages with the :ref:`display device<Devices_Display_Devices>`. For use with languages that can be indexed via pages which include PDF and XPS. (see: :ref:`Ghostscript & Page Description Languages<gs_and_PDL>`)


.. code-block:: csharp

  public gsStatus DisplayDeviceRenderPages(String fileName,
                                              int first_page,
                                              int last_page,
                                           double zoom)

**Sample code:**

.. code-block:: csharp

  m_ghostscript.DisplayDeviceRenderPages("my_document.pdf",
                                         0,
                                         9,
                                         1.0);



``GetStatus``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Returns the current :ref:`status<GhostNET_Status>` of Ghostscript.


.. code-block:: csharp

  public gsStatus GetStatus()

**Sample code:**

.. code-block:: csharp

  gsStatus status = m_ghostscript.GetStatus();



``GhostscriptException``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

An application developer can log any exceptions in this public class as required by editing the constructor.


.. code-block:: csharp

  public class GhostscriptException : Exception
  {
      public GhostscriptException(string message) : base(message)
      {
          // Report exceptions as required
      }
  }




.. _gs_and_PDL:


.. note::

  Ghostscript & Page Description Languages

  Ghostscript handles the following `PDLs`_: PCL PDF PS XPS.

  PCL and PS do not allow random access, meaning that, to print page 2 in a 100 page document, Ghostscript has to read the entire document stream of 100 pages.

  On the other hand, PDF and XPS allow for going directly to page 2 and then only dealing with that content. The tasks ``DISPLAY_DEV_NON_PDF`` and ``DISPLAY_DEV_PDF`` keep track of what sort of input Ghostscript is dealing with and enables the application to direct progress or completion callbacks accordingly.










.. External links

.. _commercial license: https://artifex.com/licensing/commercial/
.. _.NET: https://dotnet.microsoft.com/
.. _Visual Studio: https://visualstudio.microsoft.com/
.. _Mono: https://www.mono-project.com/
.. _GhostPDL repository: https://ghostscript.com/releases/gpdldnld.html


.. _PDLs: https://en.wikipedia.org/wiki/Page_description_language