-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1658 lines (1435 loc) · 61.2 KB
/
Copy pathProgram.cs
File metadata and controls
1658 lines (1435 loc) · 61.2 KB
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
using System.Buffers;
using System.Globalization;
using System.IO.Ports;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using Windows.Data.Pdf;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
internal static class Program
{
private const double MmPerInch = 25.4;
private const int FallbackDpi = 203;
private static async Task<int> Main(string[] args)
{
if (!OperatingSystem.IsWindows())
{
Console.Error.WriteLine("This tool only runs on Windows.");
return 1;
}
var options = LabelPrintOptions.Parse(args);
if (options is null)
{
LabelPrintOptions.PrintUsage();
return 1;
}
if (options.ListPrinters)
{
Console.WriteLine("=== Installed Printers (use with --printer) ===");
foreach (var printer in PrinterUtilities.GetInstalledPrinters())
{
Console.WriteLine($" {printer}");
}
Console.WriteLine();
Console.WriteLine("=== COM Ports (use with --port for Bluetooth SPP) ===");
foreach (var port in SerialPortSender.GetPortNames())
{
Console.WriteLine($" {port}");
}
return 0;
}
if (options.ShowVersion)
{
Console.WriteLine(LabelPrintOptions.GetVersionString());
return 0;
}
if (options.Install)
{
return VirtualPrinterInstaller.Install(
options.VirtualPrinterName!,
options.WatchFolder!,
options.PrinterName,
options.Port,
options.Baud,
options);
}
if (options.Uninstall)
{
return VirtualPrinterInstaller.Uninstall(options.VirtualPrinterName!);
}
if (options.RegisterStartup)
{
return StartupTaskRegistrar.Register(options);
}
if (options.UnregisterStartup)
{
return StartupTaskRegistrar.Unregister();
}
if (options.Watch)
{
return await WatchMode.RunAsync(options).ConfigureAwait(false);
}
if (!File.Exists(options.PdfPath))
{
Console.Error.WriteLine($"PDF file not found: {options.PdfPath}");
return 1;
}
try
{
return await PrintPdfAsync(options).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Print failed: {ex.Message}");
return 1;
}
}
internal static async Task<int> PrintPdfAsync(LabelPrintOptions options)
{
var dpi = options.Dpi
?? (options.Port is null ? PrinterUtilities.TryGetPrinterDpi(options.PrinterName!) : null)
?? FallbackDpi;
var resolvedOptions = options with { Dpi = dpi };
var bitmap = await RenderPdfPageAsync(resolvedOptions).ConfigureAwait(false);
var tspl = TsplBuilder.Build(resolvedOptions, bitmap);
if (options.Port is not null)
{
SerialPortSender.Send(options.Port, options.Baud, tspl);
}
else
{
RawPrinterSender.Send(resolvedOptions.PrinterName!, tspl);
}
Console.WriteLine("Print job sent.");
return 0;
}
private static async Task<BitmapData> RenderPdfPageAsync(LabelPrintOptions options)
{
var storageFile = await StorageFile.GetFileFromPathAsync(options.PdfPath);
var pdf = await PdfDocument.LoadFromFileAsync(storageFile);
if (options.PageIndex < 0 || options.PageIndex >= pdf.PageCount)
{
throw new ArgumentOutOfRangeException(nameof(options.PageIndex), $"PDF page index {options.PageIndex} is out of range.");
}
using var page = pdf.GetPage((uint)options.PageIndex);
// Dpi is always resolved to a concrete value before RenderPdfPageAsync is called.
var dpi = options.Dpi!.Value;
var widthPx = (int)Math.Round(options.LabelWidthMm * dpi / MmPerInch);
var heightPx = (int)Math.Round(options.LabelHeightMm * dpi / MmPerInch);
var renderOptions = new PdfPageRenderOptions
{
DestinationWidth = (uint)widthPx,
DestinationHeight = (uint)heightPx,
// Construct white explicitly; Windows.UI.Colors static class requires the old SDK package.
BackgroundColor = new Windows.UI.Color { A = 255, R = 255, G = 255, B = 255 },
};
using var stream = new InMemoryRandomAccessStream();
await page.RenderToStreamAsync(stream, renderOptions);
stream.Seek(0);
var decoder = await BitmapDecoder.CreateAsync(stream);
var pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
new BitmapTransform(),
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage);
var pixels = pixelData.DetachPixelData();
return new BitmapData(widthPx, heightPx, pixels);
}
}
internal sealed record LabelPrintOptions(
string? PdfPath,
string? PrinterName,
double LabelWidthMm,
double LabelHeightMm,
int PageIndex,
byte Threshold,
int? Dpi,
double? GapMm,
double? GapOffsetMm,
double? OffsetMm,
int? Speed,
int? Density,
int? Direction,
bool Tear,
bool Peel,
bool ListPrinters,
bool ShowVersion,
string? Port,
int Baud,
// Watch / install / startup modes
bool Watch,
string? WatchFolder,
bool Install,
bool Uninstall,
string? VirtualPrinterName,
bool RegisterStartup,
bool UnregisterStartup,
double? FeedMm,
bool NoTear)
{
public static LabelPrintOptions? Parse(string[] args)
{
if (args.Length == 0)
{
return null;
}
string? pdfPath = null;
string? printerName = null;
int? dpi = null;
var widthMm = 100.0; // 10 cm
var heightMm = 150.0; // 15 cm
var pageIndex = 0;
var threshold = (byte)180;
double? gapMm = 3.0;
double? gapOffsetMm = null;
double? offsetMm = null;
int? speed = null;
int? density = null;
int? direction = null;
var tear = true;
var peel = false;
var listPrinters = false;
var showVersion = false;
string? port = null;
var baud = 9600;
var watch = false;
string? watchFolder = null;
var install = false;
var uninstall = false;
string? virtualPrinterName = "Label Printer";
var registerStartup = false;
var unregisterStartup = false;
double? feedMm = null;
var noTear = false;
for (var i = 0; i < args.Length; i++)
{
var value = args[i];
switch (value)
{
case "--list-printers":
listPrinters = true;
break;
case "--version":
showVersion = true;
break;
case "--pdf" when i + 1 < args.Length:
pdfPath = args[++i];
break;
case "--printer" when i + 1 < args.Length:
printerName = args[++i];
break;
case "--dpi" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedDpi) || parsedDpi <= 0)
{
Console.Error.WriteLine("Invalid value supplied to --dpi.");
return null;
}
dpi = parsedDpi;
break;
case "--width-mm" when i + 1 < args.Length:
if (!double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out widthMm) || widthMm <= 0)
{
Console.Error.WriteLine("Invalid value supplied to --width-mm.");
return null;
}
break;
case "--height-mm" when i + 1 < args.Length:
if (!double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out heightMm) || heightMm <= 0)
{
Console.Error.WriteLine("Invalid value supplied to --height-mm.");
return null;
}
break;
case "--page" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out pageIndex) || pageIndex < 1)
{
Console.Error.WriteLine("Invalid value supplied to --page.");
return null;
}
pageIndex -= 1;
break;
case "--threshold" when i + 1 < args.Length:
if (!byte.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out threshold))
{
Console.Error.WriteLine("Invalid value supplied to --threshold.");
return null;
}
break;
case "--gap-mm" when i + 1 < args.Length:
if (!double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedGap) || parsedGap < 0)
{
Console.Error.WriteLine("Invalid value supplied to --gap-mm.");
return null;
}
gapMm = parsedGap;
break;
case "--gap-offset-mm" when i + 1 < args.Length:
if (!double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedGapOffset) || parsedGapOffset < 0)
{
Console.Error.WriteLine("Invalid value supplied to --gap-offset-mm.");
return null;
}
gapOffsetMm = parsedGapOffset;
break;
case "--offset-mm" when i + 1 < args.Length:
if (!double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedOffset) || parsedOffset < 0)
{
Console.Error.WriteLine("Invalid value supplied to --offset-mm.");
return null;
}
offsetMm = parsedOffset;
break;
case "--speed" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedSpeed) || parsedSpeed <= 0)
{
Console.Error.WriteLine("Invalid value supplied to --speed.");
return null;
}
speed = parsedSpeed;
break;
case "--density" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedDensity) || parsedDensity <= 0)
{
Console.Error.WriteLine("Invalid value supplied to --density.");
return null;
}
density = parsedDensity;
break;
case "--direction" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedDirection) || (parsedDirection != 0 && parsedDirection != 1))
{
Console.Error.WriteLine("Invalid value supplied to --direction. Use 0 or 1.");
return null;
}
direction = parsedDirection;
break;
case "--tear":
tear = true;
break;
case "--no-tear":
noTear = true;
tear = false;
break;
case "--peel":
peel = true;
break;
case "--feed" when i + 1 < args.Length:
if (!double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedFeed) || parsedFeed < 0)
{
Console.Error.WriteLine("Invalid value supplied to --feed.");
return null;
}
feedMm = parsedFeed;
break;
case "--watch":
watch = true;
break;
case "--watch-folder" when i + 1 < args.Length:
watchFolder = args[++i];
break;
case "--install":
install = true;
break;
case "--uninstall":
uninstall = true;
break;
case "--virtual-printer-name" when i + 1 < args.Length:
virtualPrinterName = args[++i];
break;
case "--register-startup":
registerStartup = true;
break;
case "--unregister-startup":
unregisterStartup = true;
break;
case "--port" when i + 1 < args.Length:
port = args[++i];
break;
case "--baud" when i + 1 < args.Length:
if (!int.TryParse(args[++i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBaud) || parsedBaud <= 0)
{
Console.Error.WriteLine("Invalid value supplied to --baud.");
return null;
}
baud = parsedBaud;
break;
default:
Console.Error.WriteLine($"Unknown argument '{value}'.");
return null;
}
}
if (listPrinters)
{
return new LabelPrintOptions(
null, null,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, listPrinters, showVersion,
port, baud,
watch, watchFolder, install, uninstall, virtualPrinterName,
registerStartup, unregisterStartup,
feedMm, noTear);
}
if (showVersion)
{
return new LabelPrintOptions(
null, null,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, false, true,
port, baud,
false, null, false, false, virtualPrinterName,
false, false,
feedMm, noTear);
}
if (unregisterStartup)
{
return new LabelPrintOptions(
null, null,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, false, false,
port, baud,
false, null, false, false, virtualPrinterName,
false, true,
feedMm, noTear);
}
if (registerStartup)
{
if (string.IsNullOrWhiteSpace(watchFolder))
{
Console.Error.WriteLine("--register-startup requires --watch-folder.");
return null;
}
if (string.IsNullOrWhiteSpace(printerName) && string.IsNullOrWhiteSpace(port))
{
Console.Error.WriteLine("--register-startup requires --printer or --port.");
return null;
}
return new LabelPrintOptions(
null, printerName,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, false, false,
port, baud,
false, watchFolder, false, false, virtualPrinterName,
true, false,
feedMm, noTear);
}
if (install)
{
if (string.IsNullOrWhiteSpace(watchFolder))
{
Console.Error.WriteLine("--install requires --watch-folder.");
return null;
}
if (string.IsNullOrWhiteSpace(printerName) && string.IsNullOrWhiteSpace(port))
{
Console.Error.WriteLine("--install requires --printer or --port (the physical label printer).");
return null;
}
return new LabelPrintOptions(
null, printerName,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, false, false,
port, baud,
false, watchFolder, install, false, virtualPrinterName,
false, false,
feedMm, noTear);
}
if (uninstall)
{
return new LabelPrintOptions(
null, null,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, false, false,
port, baud,
false, null, false, true, virtualPrinterName,
false, false,
feedMm, noTear);
}
if (watch)
{
if (string.IsNullOrWhiteSpace(watchFolder))
{
Console.Error.WriteLine("--watch requires --watch-folder.");
return null;
}
if (string.IsNullOrWhiteSpace(printerName) && string.IsNullOrWhiteSpace(port))
{
Console.Error.WriteLine("--watch requires --printer or --port (the physical label printer).");
return null;
}
return new LabelPrintOptions(
null, printerName,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, false, false,
port, baud,
true, watchFolder, false, false, virtualPrinterName,
false, false,
feedMm, noTear);
}
if (string.IsNullOrWhiteSpace(pdfPath))
{
return null;
}
if (string.IsNullOrWhiteSpace(printerName) && string.IsNullOrWhiteSpace(port))
{
Console.Error.WriteLine("Either --printer or --port must be specified.");
return null;
}
if (!string.IsNullOrWhiteSpace(printerName) && !string.IsNullOrWhiteSpace(port))
{
Console.Error.WriteLine("--printer and --port cannot be used together.");
return null;
}
return new LabelPrintOptions(
pdfPath,
printerName,
widthMm, heightMm, pageIndex, threshold,
dpi, gapMm, gapOffsetMm, offsetMm,
speed, density, direction,
tear, peel, listPrinters, false,
port, baud,
false, null, false, false, null,
false, false,
feedMm, noTear);
}
public static string GetVersionString()
{
var assembly = typeof(LabelPrintOptions).Assembly;
var informationalVersion = assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
.InformationalVersion;
var version = !string.IsNullOrWhiteSpace(informationalVersion)
? informationalVersion
: assembly.GetName().Version?.ToString() ?? "unknown";
return $"LabelPrint {version}";
}
public static void PrintUsage()
{
Console.WriteLine(GetVersionString());
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine(" LabelPrint --pdf <path> [--printer <name> | --port <COMn>] [options] Print a single PDF");
Console.WriteLine(" LabelPrint --watch --watch-folder <dir> [--printer <name> | --port <COMn>] [options] Watch folder mode");
Console.WriteLine(" LabelPrint --install --watch-folder <dir> [--printer <name> | --port <COMn>] [options] Install virtual printer (default: 'Label Printer') (run as admin)");
Console.WriteLine(" LabelPrint --uninstall [--virtual-printer-name <name>] Remove virtual printer (default: 'Label Printer') (run as admin)");
Console.WriteLine(" LabelPrint --register-startup --watch-folder <dir> [--printer <name> | --port <COMn>] [options] Register as logon task");
Console.WriteLine(" LabelPrint --unregister-startup Remove logon task");
Console.WriteLine(" LabelPrint --list-printers List printers and COM ports");
Console.WriteLine(" LabelPrint --version Print version");
Console.WriteLine();
Console.WriteLine("Transport (one required for print/watch/install):");
Console.WriteLine(" --printer <name> Windows printer name (use --list-printers to see names).");
Console.WriteLine(" --port <COMn> COM port for Bluetooth SPP printers (e.g. COM4).");
Console.WriteLine(" --baud <n> Baud rate for --port (default 9600).");
Console.WriteLine();
Console.WriteLine("Watch / install options:");
Console.WriteLine(" --watch-folder <dir> Folder to watch for new PDF files.");
Console.WriteLine(" --virtual-printer-name <name> Name of the virtual printer (default: 'Label Printer').");
Console.WriteLine();
Console.WriteLine("Label options:");
Console.WriteLine(" --dpi <n> Render DPI (defaults to printer capability or 203).");
Console.WriteLine(" --width-mm <n> Label width in mm (default 100).");
Console.WriteLine(" --height-mm <n> Label height in mm (default 150).");
Console.WriteLine(" --page <n> 1-based page index (default 1).");
Console.WriteLine(" --threshold <n> 0-255 threshold for black/white (default 180).");
Console.WriteLine(" --gap-mm <n> Gap in mm (defaults to printer setting).");
Console.WriteLine(" --gap-offset-mm <n> Gap offset in mm (defaults to printer setting).");
Console.WriteLine(" --offset-mm <n> Vertical label offset in mm (defaults to printer setting).");
Console.WriteLine(" --speed <n> Print speed (TSPL SPEED).");
Console.WriteLine(" --density <n> Print density (TSPL DENSITY).");
Console.WriteLine(" --direction <n> Print direction 0 or 1 (defaults to printer setting).");
Console.WriteLine(" --tear Enable tear mode (default).");
Console.WriteLine(" --no-tear Disable tear mode.");
Console.WriteLine(" --peel Enable peel mode.");
Console.WriteLine(" --feed <n> Feed n mm after print.");
}
}
internal sealed record BitmapData(int Width, int Height, byte[] Pixels);
internal static class TsplBuilder
{
public static byte[] Build(LabelPrintOptions options, BitmapData bitmap)
{
var widthBytes = (bitmap.Width + 7) / 8;
var dataSize = widthBytes * bitmap.Height;
var raster = ArrayPool<byte>.Shared.Rent(dataSize);
try
{
Array.Clear(raster, 0, dataSize);
FillRaster(options, bitmap, raster, widthBytes);
// Fix inverted output
InvertRaster(raster, dataSize);
var header = new StringBuilder();
// SIZE uses integer mm to match vendor driver behaviour (LABELCORE.dll uses %d format).
header.Append(CultureInfo.InvariantCulture, $"SIZE {(int)options.LabelWidthMm} mm,{(int)options.LabelHeightMm} mm\r\n");
if (options.GapMm is not null || options.GapOffsetMm is not null)
{
// GAP uses integer mm to match vendor driver behaviour.
var gap = (int)(options.GapMm ?? 0.0);
var gapOffset = (int)(options.GapOffsetMm ?? 0.0);
header.Append(CultureInfo.InvariantCulture, $"GAP {gap} mm,{gapOffset} mm\r\n");
}
if (options.OffsetMm is not null)
{
header.Append(CultureInfo.InvariantCulture, $"OFFSET {(int)options.OffsetMm.Value} mm\r\n");
}
if (options.Direction is not null)
{
header.Append(CultureInfo.InvariantCulture, $"DIRECTION {options.Direction.Value}\r\n");
}
if (options.Speed is not null)
{
header.Append(CultureInfo.InvariantCulture, $"SPEED {options.Speed.Value}\r\n");
}
if (options.Density is not null)
{
header.Append(CultureInfo.InvariantCulture, $"DENSITY {options.Density.Value}\r\n");
}
if (options.Tear)
{
header.Append("SET TEAR ON\r\n");
}
if (options.Peel)
{
header.Append("SET PEEL ON\r\n");
}
if (options.FeedMm is not null)
{
header.Append(CultureInfo.InvariantCulture, $"FEED {(int)options.FeedMm.Value} mm\r\n");
}
header.Append("CLS\r\n");
header.Append(CultureInfo.InvariantCulture, $"BITMAP 0,0,{widthBytes},{bitmap.Height},0,");
var footer = "\r\nPRINT 1,1\r\n";
var headerBytes = Encoding.ASCII.GetBytes(header.ToString());
var footerBytes = Encoding.ASCII.GetBytes(footer);
var payload = new byte[headerBytes.Length + dataSize + footerBytes.Length];
// Qualify System.Buffer to avoid ambiguity with Windows.Storage.Streams.Buffer.
System.Buffer.BlockCopy(headerBytes, 0, payload, 0, headerBytes.Length);
System.Buffer.BlockCopy(raster, 0, payload, headerBytes.Length, dataSize);
System.Buffer.BlockCopy(footerBytes, 0, payload, headerBytes.Length + dataSize, footerBytes.Length);
return payload;
}
finally
{
ArrayPool<byte>.Shared.Return(raster);
}
}
private static void FillRaster(LabelPrintOptions options, BitmapData bitmap, byte[] raster, int widthBytes)
{
var threshold = options.Threshold;
var pixels = bitmap.Pixels;
var stride = bitmap.Width * 4;
for (var y = 0; y < bitmap.Height; y++)
{
var rowOffset = y * stride;
var outOffset = y * widthBytes;
for (var x = 0; x < bitmap.Width; x++)
{
var pixelOffset = rowOffset + (x * 4);
var b = pixels[pixelOffset];
var g = pixels[pixelOffset + 1];
var r = pixels[pixelOffset + 2];
// Integer approximation of BT.601 luma (equivalent to float but ~3x faster in a tight loop).
var luminance = (byte)((r * 299 + g * 587 + b * 114) / 1000);
var isBlack = luminance < threshold;
if (!isBlack)
{
continue;
}
var byteIndex = outOffset + (x / 8);
var bitIndex = 7 - (x % 8);
raster[byteIndex] |= (byte)(1 << bitIndex);
}
}
}
private static void InvertRaster(byte[] raster, int length)
{
for (var i = 0; i < length; i++)
{
raster[i] = (byte)~raster[i];
}
}
}
internal static class RawPrinterSender
{
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);
[DllImport("winspool.drv", SetLastError = true)]
private static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StartDocPrinter(IntPtr hPrinter, int level, [In] ref DOC_INFO_1 docInfo);
[DllImport("winspool.drv", SetLastError = true)]
private static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.drv", SetLastError = true)]
private static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.drv", SetLastError = true)]
private static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.drv", SetLastError = true)]
private static extern bool WritePrinter(IntPtr hPrinter, byte[] pBytes, int dwCount, out int dwWritten);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DOC_INFO_1
{
public string pDocName;
public string pOutputFile;
public string pDatatype;
}
public static void Send(string printerName, byte[] payload)
{
if (!OpenPrinter(printerName, out var printerHandle, IntPtr.Zero))
{
throw new InvalidOperationException($"OpenPrinter failed: {Marshal.GetLastWin32Error()}");
}
try
{
var docInfo = new DOC_INFO_1
{
pDocName = "Label Print",
pOutputFile = string.Empty,
pDatatype = "RAW",
};
if (StartDocPrinter(printerHandle, 1, ref docInfo) == 0)
{
throw new InvalidOperationException($"StartDocPrinter failed: {Marshal.GetLastWin32Error()}");
}
try
{
if (!StartPagePrinter(printerHandle))
{
throw new InvalidOperationException($"StartPagePrinter failed: {Marshal.GetLastWin32Error()}");
}
try
{
if (!WritePrinter(printerHandle, payload, payload.Length, out var written) || written != payload.Length)
{
throw new InvalidOperationException($"WritePrinter failed: {Marshal.GetLastWin32Error()}");
}
}
finally
{
EndPagePrinter(printerHandle);
}
}
finally
{
EndDocPrinter(printerHandle);
}
}
finally
{
ClosePrinter(printerHandle);
}
}
}
internal static class PrinterUtilities
{
private const int PrinterEnumLocal = 0x00000002;
private const int PrinterEnumConnections = 0x00000004;
private const int ErrorInsufficientBuffer = 122;
private const int LOGPIXELSX = 88;
private const int LOGPIXELSY = 90;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct PRINTER_INFO_4
{
public string pPrinterName;
public string pServerName;
public uint Attributes;
}
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool EnumPrinters(int flags, string? name, int level, IntPtr pPrinterEnum, int cbBuf, out int pcbNeeded, out int pcReturned);
[DllImport("gdi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string? lpszOutput, IntPtr lpInitData);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteDC(IntPtr hdc);
public static IEnumerable<string> GetInstalledPrinters()
{
var flags = PrinterEnumLocal | PrinterEnumConnections;
if (!EnumPrinters(flags, null, 4, IntPtr.Zero, 0, out var needed, out _))
{
var error = Marshal.GetLastWin32Error();
if (error != ErrorInsufficientBuffer)
{
yield break;
}
}
if (needed <= 0)
{
yield break;
}
var buffer = Marshal.AllocHGlobal(needed);
try
{
if (!EnumPrinters(flags, null, 4, buffer, needed, out _, out var returned))
{
yield break;
}
var offset = buffer;
var structSize = Marshal.SizeOf<PRINTER_INFO_4>();
for (var i = 0; i < returned; i++)
{
var info = Marshal.PtrToStructure<PRINTER_INFO_4>(offset);
if (!string.IsNullOrWhiteSpace(info.pPrinterName))
{
yield return info.pPrinterName;
}
offset = IntPtr.Add(offset, structSize);
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
public static int? TryGetPrinterDpi(string printerName)
{
var hdc = CreateDC("WINSPOOL", printerName, null, IntPtr.Zero);
if (hdc == IntPtr.Zero)
{
return null;
}
try
{
var x = GetDeviceCaps(hdc, LOGPIXELSX);
var y = GetDeviceCaps(hdc, LOGPIXELSY);
if (x <= 0 && y <= 0)
{
return null;
}
if (x > 0 && y > 0)
{
return (x + y) / 2;
}
return x > 0 ? x : y;
}
finally
{
DeleteDC(hdc);
}
}
}
/// <summary>
/// Sends raw TSPL bytes directly to a serial COM port (Bluetooth SPP profile).
/// Use when the printer appears as a virtual COM port rather than a Windows printer.
/// </summary>
internal static class SerialPortSender
{
/// <summary>Returns the names of all available serial COM ports on this machine.</summary>
public static IEnumerable<string> GetPortNames() => SerialPort.GetPortNames().OrderBy(p => p);
/// <summary>
/// Opens <paramref name="portName"/> at <paramref name="baud"/> baud (8N1, no flow control),
/// writes <paramref name="payload"/>, and closes the port.
/// </summary>
public static void Send(string portName, int baud, byte[] payload)
{
using var port = new SerialPort(portName, baud, Parity.None, 8, StopBits.One)
{
Handshake = Handshake.None,
WriteTimeout = 30_000,
};
port.Open();
port.BaseStream.Write(payload, 0, payload.Length);
port.BaseStream.Flush();
}
}
/// <summary>
/// Watches a folder for new PDF files and prints each one automatically.
/// Run with Ctrl+C to stop.
/// </summary>
internal static class WatchMode
{
// How long to wait after a file appears before trying to open it (gives the writer time to finish).
private static readonly TimeSpan SettleDelay = TimeSpan.FromMilliseconds(800);
public static async Task<int> RunAsync(LabelPrintOptions options)
{
var folder = options.WatchFolder!;
Directory.CreateDirectory(folder);
Console.WriteLine($"Watching '{folder}' for PDF files. Press Ctrl+C to stop.");
Console.WriteLine($"Printing to: {(options.Port is not null ? $"COM port {options.Port}" : options.PrinterName)}");