a4-printer-interface 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ """Public package exports for a4-printer-interface."""
2
+
3
+ from .main import (
4
+ ColorMode,
5
+ DefaultSettings,
6
+ GrayscaleSettings,
7
+ PrinterInterface,
8
+ PrinterManager,
9
+ PrintSettings,
10
+ )
11
+
12
+ __all__ = [
13
+ "ColorMode",
14
+ "DefaultSettings",
15
+ "GrayscaleSettings",
16
+ "PrinterInterface",
17
+ "PrinterManager",
18
+ "PrintSettings",
19
+ ]
@@ -0,0 +1,5 @@
1
+ """Command-line entry point for printer discovery."""
2
+
3
+ from .main import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,628 @@
1
+ """Cross-platform A4 PDF and image printing without a GUI framework."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import uuid as uuid_module
12
+ from enum import Enum
13
+ from importlib.resources import as_file, files
14
+ from io import BytesIO
15
+ from pathlib import Path
16
+ from tempfile import TemporaryDirectory
17
+ from typing import Iterator, List, Optional
18
+
19
+ import pypdfium2 as pdfium
20
+ from PIL import Image, ImageOps, UnidentifiedImageError
21
+ from reportlab.lib.pagesizes import A4
22
+ from reportlab.lib.utils import ImageReader
23
+ from reportlab.pdfgen import canvas
24
+
25
+
26
+ class ColorMode(Enum):
27
+ COLOR = "color"
28
+ GREY_SCALE = "grey_scale"
29
+
30
+
31
+ class PrintSettings:
32
+ def __init__(self):
33
+ self._color_mode = ColorMode.COLOR
34
+
35
+ def get_color_mode(self) -> ColorMode:
36
+ return self._color_mode
37
+
38
+
39
+ class DefaultSettings(PrintSettings):
40
+ def get_color_mode(self) -> ColorMode:
41
+ return ColorMode.COLOR
42
+
43
+
44
+ class GrayscaleSettings(PrintSettings):
45
+ def get_color_mode(self) -> ColorMode:
46
+ return ColorMode.GREY_SCALE
47
+
48
+
49
+ class PrinterInterface:
50
+ def __init__(self):
51
+ self._name: Optional[str] = None
52
+ self._uuid: Optional[str] = None
53
+ self._backend: Optional[str] = None
54
+
55
+ def get_name(self) -> str:
56
+ if self._name is None:
57
+ raise RuntimeError(
58
+ "This printer is not connected to an operating-system queue"
59
+ )
60
+ return self._name
61
+
62
+ def get_uuid(self) -> str:
63
+ if self._uuid is None:
64
+ raise RuntimeError(
65
+ "This printer is not connected to an operating-system queue"
66
+ )
67
+ return self._uuid
68
+
69
+ def print(
70
+ self, document_path: str, settings: Optional[PrintSettings] = None
71
+ ) -> None:
72
+ if settings is None:
73
+ settings = DefaultSettings()
74
+
75
+ if not isinstance(settings, PrintSettings):
76
+ raise TypeError("settings must be a PrintSettings instance")
77
+
78
+ color_mode = settings.get_color_mode()
79
+ if not isinstance(color_mode, ColorMode):
80
+ raise ValueError("PrintSettings.get_color_mode() must return a ColorMode")
81
+
82
+ path = Path(document_path).expanduser()
83
+ if not path.is_file():
84
+ raise FileNotFoundError(f"Document does not exist or is not a file: {path}")
85
+ if self._backend is None:
86
+ raise RuntimeError(
87
+ "This printer is not connected to a supported print backend"
88
+ )
89
+
90
+ _print_document(self._backend, self.get_name(), path.resolve(), color_mode)
91
+
92
+ def print_test_page(self, settings: Optional[PrintSettings] = None) -> None:
93
+ if settings is None:
94
+ settings = DefaultSettings()
95
+ resource = files("a4_printer_interface").joinpath(
96
+ os.path.join("assets", "printer_test_page.pdf")
97
+ )
98
+ with as_file(resource) as test_page:
99
+ self.print(str(test_page), settings)
100
+
101
+ def get_busy(self) -> bool:
102
+ if self._backend is None:
103
+ raise RuntimeError(
104
+ "This printer is not connected to a supported print backend"
105
+ )
106
+ return _get_printer_busy(self._backend, self.get_name())
107
+
108
+
109
+ class PrinterManager:
110
+ def __init__(self):
111
+ self._printers = _discover_printers()
112
+
113
+ def list_printers(self) -> List[PrinterInterface]:
114
+ return list(self._printers)
115
+
116
+ def get_printer_by_name(self, name: str) -> List[PrinterInterface]:
117
+ if not isinstance(name, str):
118
+ raise TypeError("name must be a string")
119
+ target = name.casefold()
120
+ return [
121
+ printer
122
+ for printer in self._printers
123
+ if printer.get_name().casefold() == target
124
+ ]
125
+
126
+ def get_printer_by_uuid(self, uuid: str) -> Optional[PrinterInterface]:
127
+ if not isinstance(uuid, str):
128
+ raise TypeError("uuid must be a string")
129
+ target = uuid.casefold()
130
+ return next(
131
+ (
132
+ printer
133
+ for printer in self._printers
134
+ if printer.get_uuid().casefold() == target
135
+ ),
136
+ None,
137
+ )
138
+
139
+
140
+ _RENDER_DPI = 300
141
+ _A4_PIXELS = (
142
+ round(210 / 25.4 * _RENDER_DPI),
143
+ round(297 / 25.4 * _RENDER_DPI),
144
+ )
145
+
146
+
147
+ def _backend_name() -> str:
148
+ if sys.platform == "win32":
149
+ return "windows"
150
+ if sys.platform == "darwin" or os.name == "posix":
151
+ return "cups"
152
+ raise RuntimeError(f"Unsupported operating system: {sys.platform}")
153
+
154
+
155
+ def _make_printer(name: str, identity: str, backend: str) -> PrinterInterface:
156
+ printer = PrinterInterface()
157
+ printer._name = name
158
+ printer._uuid = str(
159
+ uuid_module.uuid5(
160
+ uuid_module.NAMESPACE_URL,
161
+ f"a4-printer-interface:{backend}:{identity}",
162
+ )
163
+ )
164
+ printer._backend = backend
165
+ return printer
166
+
167
+
168
+ def _discover_printers() -> List[PrinterInterface]:
169
+ backend = _backend_name()
170
+ if backend == "windows":
171
+ return _discover_windows_printers()
172
+ return _discover_cups_printers()
173
+
174
+
175
+ def _windows_printer_records() -> list[dict[str, object]]:
176
+ try:
177
+ import win32print
178
+
179
+ flags = win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
180
+ return list(win32print.EnumPrinters(flags, None, 2))
181
+ except ImportError as error:
182
+ raise RuntimeError(
183
+ "pywin32 is required by the Windows print backend"
184
+ ) from error
185
+ except Exception as error:
186
+ raise RuntimeError(f"Could not discover Windows printers: {error}") from error
187
+
188
+
189
+ def _discover_windows_printers() -> List[PrinterInterface]:
190
+ printers = []
191
+ for record in _windows_printer_records():
192
+ name = str(record.get("pPrinterName") or "").strip()
193
+ if not name:
194
+ continue
195
+ identity = "\0".join(
196
+ str(record.get(field) or "")
197
+ for field in ("pServerName", "pPrinterName", "pPortName", "pDriverName")
198
+ )
199
+ printers.append(_make_printer(name, identity, "windows"))
200
+ return sorted(printers, key=lambda printer: printer.get_name().casefold())
201
+
202
+
203
+ def _windows_printer_busy(name: str) -> bool:
204
+ try:
205
+ import win32print
206
+ except ImportError as error:
207
+ raise RuntimeError(
208
+ "pywin32 is required by the Windows print backend"
209
+ ) from error
210
+
211
+ handle = None
212
+ try:
213
+ handle = win32print.OpenPrinter(name)
214
+ printer = win32print.GetPrinter(handle, 2)
215
+ printer_status = int(printer.get("Status") or 0)
216
+ if printer_status & win32print.PRINTER_STATUS_PRINTING:
217
+ return True
218
+
219
+ job_count = int(printer.get("cJobs") or 0)
220
+ jobs = win32print.EnumJobs(handle, 0, job_count, 1)
221
+ return any(
222
+ int(job.get("Status") or 0) & win32print.JOB_STATUS_PRINTING for job in jobs
223
+ )
224
+ except Exception as error:
225
+ raise RuntimeError(
226
+ f"Could not query Windows printer status for {name}: {error}"
227
+ ) from error
228
+ finally:
229
+ if handle is not None:
230
+ win32print.ClosePrinter(handle)
231
+
232
+
233
+ def _run_command(
234
+ command: List[str], *, env: Optional[dict[str, str]] = None
235
+ ) -> subprocess.CompletedProcess[str]:
236
+ try:
237
+ return subprocess.run(
238
+ command,
239
+ capture_output=True,
240
+ text=True,
241
+ encoding="utf-8",
242
+ errors="replace",
243
+ timeout=30,
244
+ check=False,
245
+ env=env,
246
+ )
247
+ except (OSError, subprocess.SubprocessError) as error:
248
+ raise RuntimeError(f"Could not run {command[0]}: {error}") from error
249
+
250
+
251
+ def _cups_environment() -> dict[str, str]:
252
+ environment = os.environ.copy()
253
+ environment["LC_ALL"] = "C"
254
+ return environment
255
+
256
+
257
+ def _cups_printer_busy(name: str) -> bool:
258
+ lpstat = shutil.which("lpstat")
259
+ if lpstat is None:
260
+ raise RuntimeError("CUPS is required, but the lpstat command was not found")
261
+
262
+ result = _run_command([lpstat, "-p", name], env=_cups_environment())
263
+ if result.returncode != 0:
264
+ detail = result.stderr.strip() or result.stdout.strip() or "unknown CUPS error"
265
+ raise RuntimeError(f"Could not query CUPS printer status: {detail}")
266
+
267
+ printing_pattern = re.compile(
268
+ rf"^printer\s+{re.escape(name)}\s+(?:now|is)\s+printing\b",
269
+ re.IGNORECASE,
270
+ )
271
+ return any(
272
+ printing_pattern.search(line.strip()) for line in result.stdout.splitlines()
273
+ )
274
+
275
+
276
+ def _get_printer_busy(backend: str, name: str) -> bool:
277
+ if backend == "windows":
278
+ return _windows_printer_busy(name)
279
+ if backend == "cups":
280
+ return _cups_printer_busy(name)
281
+ raise RuntimeError(f"Unsupported print backend: {backend}")
282
+
283
+
284
+ def _discover_cups_printers() -> List[PrinterInterface]:
285
+ lpstat = shutil.which("lpstat")
286
+ if lpstat is None:
287
+ raise RuntimeError("CUPS is required, but the lpstat command was not found")
288
+
289
+ environment = _cups_environment()
290
+ names_result = _run_command([lpstat, "-e"], env=environment)
291
+ names = [line.strip() for line in names_result.stdout.splitlines() if line.strip()]
292
+
293
+ if names_result.returncode != 0 or not names:
294
+ legacy_result = _run_command([lpstat, "-p"], env=environment)
295
+ names = []
296
+ if legacy_result.returncode == 0:
297
+ for line in legacy_result.stdout.splitlines():
298
+ match = re.match(r"^printer\s+(\S+)", line)
299
+ if match:
300
+ names.append(match.group(1))
301
+
302
+ devices_result = _run_command([lpstat, "-v"], env=environment)
303
+ devices = {}
304
+ if devices_result.returncode == 0:
305
+ for line in devices_result.stdout.splitlines():
306
+ match = re.match(r"^device for (.+?):\s*(.+)$", line)
307
+ if match:
308
+ devices[match.group(1)] = match.group(2).strip()
309
+
310
+ printers = [
311
+ _make_printer(name, f"{name}\0{devices.get(name, '')}", "cups")
312
+ for name in dict.fromkeys(names)
313
+ ]
314
+ return sorted(printers, key=lambda printer: printer.get_name().casefold())
315
+
316
+
317
+ def _open_pdf(path: Path) -> pdfium.PdfDocument:
318
+ try:
319
+ document = pdfium.PdfDocument(str(path))
320
+ document.init_forms()
321
+ if len(document) == 0:
322
+ document.close()
323
+ raise ValueError(f"PDF document has no pages: {path}")
324
+ return document
325
+ except ValueError:
326
+ raise
327
+ except Exception as error:
328
+ raise ValueError(f"Could not load PDF document: {path} ({error})") from error
329
+
330
+
331
+ def _render_pdf_a4_pages(path: Path, color_mode: ColorMode) -> Iterator[Image.Image]:
332
+ document = _open_pdf(path)
333
+ output_mode = "RGB" if color_mode is ColorMode.COLOR else "L"
334
+ try:
335
+ for page_number in range(len(document)):
336
+ page = document[page_number]
337
+ try:
338
+ try:
339
+ width, height = page.get_size()
340
+ if width <= 0 or height <= 0:
341
+ raise ValueError(
342
+ f"PDF page {page_number + 1} has an invalid size"
343
+ )
344
+
345
+ rotation = 90 if width > height else 0
346
+ if rotation:
347
+ width, height = height, width
348
+ scale = min(_A4_PIXELS[0] / width, _A4_PIXELS[1] / height)
349
+ bitmap = page.render(
350
+ scale=scale,
351
+ rotation=rotation,
352
+ fill_color=(255, 255, 255, 255),
353
+ grayscale=color_mode is ColorMode.GREY_SCALE,
354
+ optimize_mode="print",
355
+ draw_annots=True,
356
+ )
357
+ try:
358
+ pil_image = bitmap.to_pil()
359
+ try:
360
+ rendered = pil_image.convert(output_mode).copy()
361
+ finally:
362
+ pil_image.close()
363
+ finally:
364
+ bitmap.close()
365
+
366
+ if (
367
+ rendered.width > _A4_PIXELS[0]
368
+ or rendered.height > _A4_PIXELS[1]
369
+ ):
370
+ rendered.thumbnail(_A4_PIXELS, Image.Resampling.LANCZOS)
371
+ a4_page = Image.new(output_mode, _A4_PIXELS, "white")
372
+ offset = (
373
+ (_A4_PIXELS[0] - rendered.width) // 2,
374
+ (_A4_PIXELS[1] - rendered.height) // 2,
375
+ )
376
+ a4_page.paste(rendered, offset)
377
+ rendered.close()
378
+ yield a4_page
379
+ except ValueError:
380
+ raise
381
+ except Exception as error:
382
+ raise ValueError(
383
+ f"Could not render PDF page {page_number + 1}: {error}"
384
+ ) from error
385
+ finally:
386
+ page.close()
387
+ finally:
388
+ document.close()
389
+
390
+
391
+ def _render_image_a4_page(path: Path, color_mode: ColorMode) -> Image.Image:
392
+ output_mode = "RGB" if color_mode is ColorMode.COLOR else "L"
393
+ try:
394
+ with Image.open(path) as source:
395
+ source.seek(0)
396
+ transposed = ImageOps.exif_transpose(source)
397
+ try:
398
+ transposed.load()
399
+ if transposed.width <= 0 or transposed.height <= 0:
400
+ raise ValueError(f"Image has an invalid size: {path}")
401
+
402
+ if (
403
+ transposed.mode in {"RGBA", "LA"}
404
+ or "transparency" in transposed.info
405
+ ):
406
+ rgba = transposed.convert("RGBA")
407
+ try:
408
+ background = Image.new("RGBA", rgba.size, "white")
409
+ background.alpha_composite(rgba)
410
+ prepared = background.convert(output_mode)
411
+ background.close()
412
+ finally:
413
+ rgba.close()
414
+ else:
415
+ prepared = transposed.convert(output_mode)
416
+ finally:
417
+ if transposed is not source:
418
+ transposed.close()
419
+ except ValueError:
420
+ raise
421
+ except (UnidentifiedImageError, OSError) as error:
422
+ raise ValueError(
423
+ f"Document is neither a PDF nor a supported image: {path}"
424
+ ) from error
425
+
426
+ try:
427
+ if prepared.width > prepared.height:
428
+ portrait = prepared.transpose(Image.Transpose.ROTATE_90)
429
+ prepared.close()
430
+ prepared = portrait
431
+ return ImageOps.fit(
432
+ prepared,
433
+ _A4_PIXELS,
434
+ method=Image.Resampling.LANCZOS,
435
+ centering=(0.5, 0.5),
436
+ )
437
+ finally:
438
+ prepared.close()
439
+
440
+
441
+ def _render_a4_pages(path: Path, color_mode: ColorMode) -> Iterator[Image.Image]:
442
+ if path.suffix.casefold() == ".pdf":
443
+ yield from _render_pdf_a4_pages(path, color_mode)
444
+ return
445
+ yield _render_image_a4_page(path, color_mode)
446
+
447
+
448
+ def _write_normalized_pdf(path: Path, output_path: Path, color_mode: ColorMode) -> None:
449
+ pages = iter(_render_a4_pages(path, color_mode))
450
+ first_page = next(pages)
451
+ output = canvas.Canvas(str(output_path), pagesize=A4, pageCompression=1)
452
+ first_page_pending = True
453
+ try:
454
+ for page in itertools.chain((first_page,), pages):
455
+ encoded = BytesIO()
456
+ try:
457
+ page.save(
458
+ encoded,
459
+ format="JPEG",
460
+ quality=95,
461
+ subsampling=0,
462
+ dpi=(_RENDER_DPI, _RENDER_DPI),
463
+ )
464
+ encoded.seek(0)
465
+ output.drawImage(ImageReader(encoded), 0, 0, width=A4[0], height=A4[1])
466
+ output.showPage()
467
+ finally:
468
+ page.close()
469
+ if page is first_page:
470
+ first_page_pending = False
471
+ encoded.close()
472
+ output.save()
473
+ finally:
474
+ if first_page_pending:
475
+ first_page.close()
476
+ pages.close()
477
+
478
+
479
+ def _print_document(backend: str, name: str, path: Path, color_mode: ColorMode) -> None:
480
+ if backend not in {"windows", "cups"}:
481
+ raise RuntimeError(f"Unsupported print backend: {backend}")
482
+ if backend == "windows" and path.suffix.casefold() == ".pdf":
483
+ _print_with_windows(name, path, color_mode)
484
+ return
485
+
486
+ with TemporaryDirectory(prefix="a4-printer-interface-") as directory:
487
+ normalized_path = Path(directory) / "print-ready.pdf"
488
+ _write_normalized_pdf(path, normalized_path, color_mode)
489
+ if backend == "windows":
490
+ _print_with_windows(name, normalized_path, color_mode)
491
+ else:
492
+ _print_with_cups(name, normalized_path, color_mode)
493
+
494
+
495
+ def _print_with_cups(name: str, path: Path, color_mode: ColorMode) -> None:
496
+ lp = shutil.which("lp")
497
+ if lp is None:
498
+ raise RuntimeError("CUPS is required, but the lp command was not found")
499
+
500
+ ipp_color_mode = "color" if color_mode is ColorMode.COLOR else "monochrome"
501
+ result = _run_command(
502
+ [
503
+ lp,
504
+ "-d",
505
+ name,
506
+ "-o",
507
+ "media=A4",
508
+ "-o",
509
+ "orientation-requested=3",
510
+ "-o",
511
+ f"print-color-mode={ipp_color_mode}",
512
+ str(path),
513
+ ],
514
+ env=_cups_environment(),
515
+ )
516
+ if result.returncode != 0:
517
+ detail = result.stderr.strip() or result.stdout.strip() or "unknown CUPS error"
518
+ raise RuntimeError(f"CUPS rejected the print job: {detail}")
519
+
520
+
521
+ def _windows_devmode(name: str, color_mode: ColorMode):
522
+ import win32con
523
+ import win32print
524
+
525
+ handle = win32print.OpenPrinter(name)
526
+ try:
527
+ devmode = win32print.GetPrinter(handle, 2).get("pDevMode")
528
+ if devmode is None:
529
+ raise RuntimeError(f"Printer driver did not provide settings: {name}")
530
+ devmode.Fields |= (
531
+ win32con.DM_ORIENTATION | win32con.DM_PAPERSIZE | win32con.DM_COLOR
532
+ )
533
+ devmode.Orientation = win32con.DMORIENT_PORTRAIT
534
+ devmode.PaperSize = win32con.DMPAPER_A4
535
+ devmode.Color = (
536
+ win32con.DMCOLOR_COLOR
537
+ if color_mode is ColorMode.COLOR
538
+ else win32con.DMCOLOR_MONOCHROME
539
+ )
540
+ return devmode
541
+ finally:
542
+ win32print.ClosePrinter(handle)
543
+
544
+
545
+ def _fit_device_rect(
546
+ image_size: tuple[int, int], device_size: tuple[int, int]
547
+ ) -> tuple[int, int, int, int]:
548
+ scale = min(device_size[0] / image_size[0], device_size[1] / image_size[1])
549
+ width = round(image_size[0] * scale)
550
+ height = round(image_size[1] * scale)
551
+ left = (device_size[0] - width) // 2
552
+ top = (device_size[1] - height) // 2
553
+ return left, top, left + width, top + height
554
+
555
+
556
+ def _print_with_windows(name: str, path: Path, color_mode: ColorMode) -> None:
557
+ try:
558
+ import win32con
559
+ import win32gui
560
+ import win32ui
561
+ from PIL import ImageWin
562
+ except ImportError as error:
563
+ raise RuntimeError(
564
+ "pywin32 is required by the Windows print backend"
565
+ ) from error
566
+
567
+ pages = iter(_render_a4_pages(path, color_mode))
568
+ first_page = next(pages)
569
+ first_page_pending = True
570
+ device_context = None
571
+ document_started = False
572
+ try:
573
+ devmode = _windows_devmode(name, color_mode)
574
+ handle = win32gui.CreateDC("WINSPOOL", name, devmode)
575
+ device_context = win32ui.CreateDCFromHandle(handle)
576
+ printable_size = (
577
+ device_context.GetDeviceCaps(win32con.HORZRES),
578
+ device_context.GetDeviceCaps(win32con.VERTRES),
579
+ )
580
+ target = _fit_device_rect(_A4_PIXELS, printable_size)
581
+
582
+ device_context.StartDoc(path.name)
583
+ document_started = True
584
+ for page in itertools.chain((first_page,), pages):
585
+ try:
586
+ device_context.StartPage()
587
+ ImageWin.Dib(page).draw(device_context.GetHandleOutput(), target)
588
+ device_context.EndPage()
589
+ finally:
590
+ page.close()
591
+ if page is first_page:
592
+ first_page_pending = False
593
+ device_context.EndDoc()
594
+ document_started = False
595
+ except (ValueError, RuntimeError):
596
+ raise
597
+ except Exception as error:
598
+ raise RuntimeError(f"Windows rejected the print job: {error}") from error
599
+ finally:
600
+ if document_started and device_context is not None:
601
+ try:
602
+ device_context.AbortDoc()
603
+ except Exception:
604
+ pass
605
+ if device_context is not None:
606
+ device_context.DeleteDC()
607
+ if first_page_pending:
608
+ first_page.close()
609
+ pages.close()
610
+
611
+
612
+ def main() -> int:
613
+ try:
614
+ printers = PrinterManager().list_printers()
615
+ except RuntimeError as error:
616
+ print(f"Printer discovery failed: {error}", file=sys.stderr)
617
+ return 1
618
+
619
+ if not printers:
620
+ print("No printers found.")
621
+ return 0
622
+ for printer in printers:
623
+ print(f"Printer Name: {printer.get_name()}, UUID: {printer.get_uuid()}")
624
+ return 0
625
+
626
+
627
+ if __name__ == "__main__":
628
+ raise SystemExit(main())
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.4
2
+ Name: a4-printer-interface
3
+ Version: 0.1.0
4
+ Summary: A small cross-platform Python interface for A4 printers
5
+ Author-email: GGN_2015 <neko@jlulug.org>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: Pillow
11
+ Requires-Dist: pypdfium2
12
+ Requires-Dist: reportlab
13
+ Requires-Dist: pywin32==312; sys_platform == "win32"
14
+ Dynamic: license-file
15
+
16
+ # a4-printer-interface
17
+
18
+ `a4-printer-interface` is a focused Python library for discovering local printer
19
+ queues and printing PDF documents or images on Windows, X11, and macOS.
20
+
21
+ Every input page is normalized for a portrait A4 sheet before it is submitted:
22
+
23
+ - Landscape pages are rotated to portrait.
24
+ - Pages of any size are scaled proportionally to fit A4.
25
+ - Pages whose aspect ratio differs from A4 are centered with white padding.
26
+ - Color and true grayscale rendering are supported.
27
+
28
+ The source PDF is never modified. PDFium renders each page at 300 DPI so that
29
+ layout and grayscale results do not depend on a desktop PDF viewer.
30
+
31
+ Images are EXIF-orientation aware and become a temporary, single-page portrait A4
32
+ PDF before printing. Landscape images are rotated, then the image is scaled and
33
+ center-cropped to cover the A4 canvas without an added white border. Multi-frame
34
+ images use their first frame.
35
+
36
+ ## Requirements
37
+
38
+ - Python 3.10 or newer.
39
+ - A printer configured in Windows, CUPS on X11, or the macOS printing system.
40
+ - The CUPS client commands `lpstat` and `lp` on X11. They are built into macOS.
41
+ - An A4-capable printer queue.
42
+
43
+ The lightweight runtime uses `pypdfium2`, Pillow, and ReportLab. Pillow-supported
44
+ image formats such as PNG, JPEG, TIFF, BMP, and WebP can be printed. Windows also
45
+ installs `pywin32` for direct GDI printing. The package does not install a GUI
46
+ toolkit or require an external PDF viewer.
47
+
48
+ ## Installation
49
+
50
+ From the repository root:
51
+
52
+ ```console
53
+ python -m pip install a4_printer_interface
54
+ ```
55
+
56
+ ## Discover printers
57
+
58
+ ```python
59
+ from a4_printer_interface import PrinterManager
60
+
61
+ manager = PrinterManager()
62
+ for printer in manager.list_printers():
63
+ print(printer.get_name(), printer.get_uuid())
64
+ ```
65
+
66
+ Names are matched case-insensitively. UUIDs are deterministic identifiers derived
67
+ from the operating-system queue and its backend identity.
68
+
69
+ ```python
70
+ office_queues = manager.get_printer_by_name("Office Printer")
71
+ printer = manager.get_printer_by_uuid("8fd0d51f-12c8-5b50-a2f1-4f64641ae77c")
72
+ ```
73
+
74
+ Create a new `PrinterManager` when you need to refresh the operating system's
75
+ printer list.
76
+
77
+ ## Check printer activity
78
+
79
+ Use `get_busy()` to check whether the selected queue is currently executing a
80
+ print job:
81
+
82
+ ```python
83
+ if printer.get_busy():
84
+ print("The printer is currently printing.")
85
+ ```
86
+
87
+ The method returns `False` for an idle printer or for jobs that are only queued,
88
+ paused, completed, or waiting for intervention. It raises `RuntimeError` when the
89
+ native print service cannot provide the queue status.
90
+
91
+ ## Print a document
92
+
93
+ Use the built-in `DefaultSettings` for color printing:
94
+
95
+ ```python
96
+ from a4_printer_interface import DefaultSettings, PrinterManager
97
+
98
+ printer = PrinterManager().list_printers()[0]
99
+ printer.print("report.pdf", DefaultSettings())
100
+ ```
101
+
102
+ Use the built-in `GrayscaleSettings` for grayscale printing:
103
+
104
+ ```python
105
+ from a4_printer_interface import GrayscaleSettings
106
+
107
+ printer.print("report.pdf", GrayscaleSettings())
108
+ ```
109
+
110
+ Images use the same API and settings:
111
+
112
+ ```python
113
+ printer.print("photo.jpg", DefaultSettings())
114
+ ```
115
+
116
+ In grayscale mode, PDFium renders the document directly to grayscale pixels before
117
+ it reaches the driver. The native print job is also marked as monochrome. In color
118
+ mode, the original page colors are preserved.
119
+
120
+ `print()` rejects files that are neither PDFs nor Pillow-supported images,
121
+ malformed or password-protected PDFs, missing files, unavailable queues, and jobs
122
+ rejected by the native print system. A successful return means the operating
123
+ system accepted the job; it does not mean that physical printing has finished.
124
+
125
+ ## Print the built-in test page
126
+
127
+ The package includes a low-ink, single-page color test PDF with small cyan,
128
+ magenta, yellow, and black patches, a black cross grid, and English and Chinese
129
+ sample text. Print it in color with the default settings:
130
+
131
+ ```python
132
+ printer.print_test_page()
133
+ ```
134
+
135
+ The optional settings argument can force a grayscale test:
136
+
137
+ ```python
138
+ printer.print_test_page(GrayscaleSettings())
139
+ ```
140
+
141
+ ## Platform backends
142
+
143
+ - Windows discovers queues with the print spooler and sends normalized A4 page
144
+ images directly to the selected printer through GDI. Printer defaults are not
145
+ changed.
146
+ - X11 and macOS discover CUPS queues with `lpstat`. They receive a temporary,
147
+ normalized A4 PDF through `lp`; the temporary file is deleted after submission.
148
+
149
+ ## Command line
150
+
151
+ List available queues after installation:
152
+
153
+ ```console
154
+ a4-printers
155
+ ```
156
+
157
+ The equivalent development command is:
158
+
159
+ ```console
160
+ python -m a4_printer_interface
161
+ ```
162
+
163
+ ## Development
164
+
165
+ Run the test suite:
166
+
167
+ ```console
168
+ python -m unittest discover -s tests -v
169
+ ```
170
+
171
+ Tests inspect normalized PDF page sizes and rendered pixels. Operating-system
172
+ printer services are mocked, so the tests never submit a real print job. CI runs
173
+ them on Windows, Ubuntu, and macOS with Python 3.10 and 3.13.
174
+
175
+ ## License
176
+
177
+ MIT
@@ -0,0 +1,10 @@
1
+ a4_printer_interface/__init__.py,sha256=dGMw4xUtDkxSrLSiXr6mDmBQUNwIK66JQ_IjTY7DY-s,345
2
+ a4_printer_interface/__main__.py,sha256=bdeporKR19X78lMXxk8nLGM43JKcZPv-CtQQryzgwMk,104
3
+ a4_printer_interface/main.py,sha256=GJ3PIYDdbq7wum29tzYYWLUqq7yB99yoDS3L_NGGyM0,21127
4
+ a4_printer_interface/assets/printer_test_page.pdf,sha256=5Qk15KMA1P2WYgai7WWm_kbDbji7WtXAAj6u1AwTt74,17999
5
+ a4_printer_interface-0.1.0.dist-info/licenses/LICENSE,sha256=gmkEFqkF3KJjRnhXGoLSfX4xXtfPHT1ghq3YgCF7B3w,1086
6
+ a4_printer_interface-0.1.0.dist-info/METADATA,sha256=wWp1c7riva6KVBQ4pPh_qe35Fz_tAVj5CkBMpxJ7CGQ,5471
7
+ a4_printer_interface-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ a4_printer_interface-0.1.0.dist-info/entry_points.txt,sha256=H_BxpdUEqLBNVBdKbCuQiK8glOKxDH1qiqtU8WFowJE,63
9
+ a4_printer_interface-0.1.0.dist-info/top_level.txt,sha256=dCnDSPGlDFDIQeelufjhHO18pAr9i12lEMqTtSeVOn0,21
10
+ a4_printer_interface-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ a4-printers = a4_printer_interface.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GGN_2015
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ a4_printer_interface