diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6a182b5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,429 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+*.env
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+
+[Dd]ebug/x64/
+[Dd]ebugPublic/x64/
+[Rr]elease/x64/
+[Rr]eleases/x64/
+bin/x64/
+obj/x64/
+
+[Dd]ebug/x86/
+[Dd]ebugPublic/x86/
+[Rr]elease/x86/
+[Rr]eleases/x86/
+bin/x86/
+obj/x86/
+
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+[Aa][Rr][Mm]64[Ee][Cc]/
+bld/
+[Oo]bj/
+[Oo]ut/
+[Ll]og/
+[Ll]ogs/
+
+# Build results on 'Bin' directories
+**/[Bb]in/*
+# Uncomment if you have tasks that rely on *.refresh files to move binaries
+# (https://github.com/github/gitignore/pull/3736)
+#!**/[Bb]in/*.refresh
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+*.trx
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Approval Tests result files
+*.received.*
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+.artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.idb
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+# but not Directory.Build.rsp, as it configures directory-level build defaults
+!Directory.Build.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.tlog
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio 6 workspace and project file (working project files containing files to include in project)
+*.dsw
+*.dsp
+
+# Visual Studio 6 technical files
+*.ncb
+*.aps
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+**/.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+**/.fake/
+
+# CodeRush personal settings
+**/.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+**/__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+#tools/**
+#!tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+MSBuild_Logs/
+
+# AWS SAM Build and Temporary Artifacts folder
+.aws-sam
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+**/.mfractor/
+
+# Local History for Visual Studio
+**/.localhistory/
+
+# Visual Studio History (VSHistory) files
+.vshistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+**/.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
+
+# VS Code files for those working on multiple tools
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+!.vscode/*.code-snippets
+
+# Local History for Visual Studio Code
+.history/
+
+# Built Visual Studio Code Extensions
+*.vsix
+
+# Windows Installer files from build outputs
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
\ No newline at end of file
diff --git a/App.xaml b/App.xaml
new file mode 100644
index 0000000..fb29ccb
--- /dev/null
+++ b/App.xaml
@@ -0,0 +1,86 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/App.xaml.cs b/App.xaml.cs
new file mode 100644
index 0000000..48697ef
--- /dev/null
+++ b/App.xaml.cs
@@ -0,0 +1,38 @@
+using System.Windows.Threading;
+using CloudPrint.Client.Models;
+using CloudPrint.Client.Services;
+
+namespace CloudPrint.Client;
+
+public partial class App : System.Windows.Application
+{
+ private readonly FileAppLogger _logger = new();
+
+ protected override void OnStartup(System.Windows.StartupEventArgs e)
+ {
+ base.OnStartup(e);
+ DispatcherUnhandledException += OnDispatcherUnhandledException;
+ AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
+ TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
+ }
+
+ private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
+ {
+ _logger.Write(AppLogEntry.FromException("UI 未处理异常", e.Exception));
+ e.Handled = true;
+ }
+
+ private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
+ {
+ if (e.ExceptionObject is Exception exception)
+ {
+ _logger.Write(AppLogEntry.FromException("应用未处理异常", exception));
+ }
+ }
+
+ private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
+ {
+ _logger.Write(AppLogEntry.FromException("后台任务未观察异常", e.Exception));
+ e.SetObserved();
+ }
+}
\ No newline at end of file
diff --git a/CloudPrint.Client.csproj b/CloudPrint.Client.csproj
new file mode 100644
index 0000000..78317cd
--- /dev/null
+++ b/CloudPrint.Client.csproj
@@ -0,0 +1,28 @@
+
+
+
+ WinExe
+ net8.0-windows
+ true
+ true
+ enable
+ enable
+ CloudPrint.Client
+ CloudPrint.Client
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Helpers/PdfProcessor.cs b/Helpers/PdfProcessor.cs
new file mode 100644
index 0000000..e51c43a
--- /dev/null
+++ b/Helpers/PdfProcessor.cs
@@ -0,0 +1,227 @@
+using CloudPrint.Client.Models;
+using PdfSharp.Drawing;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.IO;
+using System.IO;
+
+namespace CloudPrint.Client.Helpers;
+
+///
+/// 基于 PDFsharp 的 PDF 处理工具,负责打印前的页码范围裁剪、水印和合并。
+///
+public sealed class PdfProcessor
+{
+ public Task AddWatermarkAsync(string pdfPath, string text, CancellationToken cancellationToken = default)
+ {
+ ValidatePdfPath(pdfPath);
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return Task.FromResult(pdfPath);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ var outputPath = CreateSiblingOutputPath(pdfPath, "watermarked");
+ using var document = PdfReader.Open(pdfPath, PdfDocumentOpenMode.Modify);
+
+ foreach (var page in document.Pages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ using var graphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
+ var font = new XFont("Arial", 36, XFontStyleEx.Bold);
+ var size = graphics.MeasureString(text, font);
+ var centerX = page.Width.Point / 2;
+ var centerY = page.Height.Point / 2;
+
+ graphics.TranslateTransform(centerX, centerY);
+ graphics.RotateTransform(-35);
+ graphics.DrawString(
+ text,
+ font,
+ new XSolidBrush(XColor.FromArgb(80, 120, 120, 120)),
+ new XRect(-size.Width / 2, -size.Height / 2, size.Width, size.Height),
+ XStringFormats.Center);
+ graphics.RotateTransform(35);
+ graphics.TranslateTransform(-centerX, -centerY);
+ }
+
+ document.Save(outputPath);
+ return Task.FromResult(outputPath);
+ }
+
+ public Task ExtractPageRangeAsync(string pdfPath, string pageRange, string outputDirectory, CancellationToken cancellationToken = default)
+ {
+ ValidatePdfPath(pdfPath);
+ if (string.IsNullOrWhiteSpace(pageRange) || pageRange.Equals("all", StringComparison.OrdinalIgnoreCase))
+ {
+ return Task.FromResult(pdfPath);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ Directory.CreateDirectory(outputDirectory);
+ using var input = PdfReader.Open(pdfPath, PdfDocumentOpenMode.Import);
+ var pageIndexes = ParsePageRange(pageRange, input.PageCount);
+ if (pageIndexes.Count == input.PageCount && pageIndexes.SequenceEqual(Enumerable.Range(0, input.PageCount)))
+ {
+ return Task.FromResult(pdfPath);
+ }
+
+ using var output = new PdfDocument();
+ output.Info.Title = input.Info.Title;
+ output.Info.Author = input.Info.Author;
+ output.Info.Subject = input.Info.Subject;
+ output.Info.Keywords = input.Info.Keywords;
+
+ foreach (var index in pageIndexes)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ output.AddPage(input.Pages[index]);
+ }
+
+ var outputPath = CreateUniquePath(Path.Combine(outputDirectory, $"{Path.GetFileNameWithoutExtension(pdfPath)}.pages-{NormalizePageRangeForFileName(pageRange)}.pdf"));
+ output.Save(outputPath);
+ return Task.FromResult(outputPath);
+ }
+
+ public Task MergeAsync(IEnumerable documents, string outputPath, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(documents);
+ if (string.IsNullOrWhiteSpace(outputPath))
+ {
+ throw new ArgumentException("输出路径不能为空", nameof(outputPath));
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? Directory.GetCurrentDirectory());
+ using var output = new PdfDocument();
+
+ foreach (var document in documents)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (!IsPdf(document.FilePath))
+ {
+ continue;
+ }
+
+ using var input = PdfReader.Open(document.FilePath, PdfDocumentOpenMode.Import);
+ foreach (var page in input.Pages)
+ {
+ output.AddPage(page);
+ }
+ }
+
+ if (output.PageCount == 0)
+ {
+ throw new InvalidOperationException("没有可合并的 PDF 文件");
+ }
+
+ var uniqueOutputPath = CreateUniquePath(outputPath);
+ output.Save(uniqueOutputPath);
+ return Task.FromResult(uniqueOutputPath);
+ }
+
+ private static IReadOnlyList ParsePageRange(string pageRange, int pageCount)
+ {
+ if (pageCount <= 0)
+ {
+ throw new InvalidOperationException("PDF 没有可打印页面");
+ }
+
+ var pages = new SortedSet();
+ foreach (var rawPart in pageRange.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ var part = rawPart.Replace('-', '-').Replace('—', '-');
+ if (part.Contains('-', StringComparison.Ordinal))
+ {
+ var bounds = part.Split('-', 2, StringSplitOptions.TrimEntries);
+ var start = ParseOneBasedPageNumber(bounds[0], pageCount);
+ var end = ParseOneBasedPageNumber(bounds[1], pageCount);
+ if (start > end)
+ {
+ throw new ArgumentException($"页码范围无效:{rawPart}", nameof(pageRange));
+ }
+
+ for (var page = start; page <= end; page++)
+ {
+ pages.Add(page - 1);
+ }
+ }
+ else
+ {
+ pages.Add(ParseOneBasedPageNumber(part, pageCount) - 1);
+ }
+ }
+
+ if (pages.Count == 0)
+ {
+ throw new ArgumentException("页码范围不能为空", nameof(pageRange));
+ }
+
+ return pages.ToArray();
+ }
+
+ private static int ParseOneBasedPageNumber(string value, int pageCount)
+ {
+ if (!int.TryParse(value, out var page) || page < 1 || page > pageCount)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), $"页码 {value} 超出有效范围 1-{pageCount}");
+ }
+
+ return page;
+ }
+
+ private static void ValidatePdfPath(string pdfPath)
+ {
+ if (string.IsNullOrWhiteSpace(pdfPath))
+ {
+ throw new ArgumentException("PDF 路径不能为空", nameof(pdfPath));
+ }
+
+ if (!File.Exists(pdfPath))
+ {
+ throw new FileNotFoundException("PDF 文件不存在", pdfPath);
+ }
+
+ if (!IsPdf(pdfPath))
+ {
+ throw new ArgumentException("文件不是 PDF", nameof(pdfPath));
+ }
+ }
+
+ private static bool IsPdf(string path)
+ {
+ return Path.GetExtension(path).Equals(".pdf", StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static string CreateSiblingOutputPath(string sourcePath, string suffix)
+ {
+ var directory = Path.GetDirectoryName(sourcePath) ?? Directory.GetCurrentDirectory();
+ var outputPath = Path.Combine(directory, $"{Path.GetFileNameWithoutExtension(sourcePath)}.{suffix}.pdf");
+ return CreateUniquePath(outputPath);
+ }
+
+ private static string CreateUniquePath(string path)
+ {
+ if (!File.Exists(path))
+ {
+ return path;
+ }
+
+ var directory = Path.GetDirectoryName(path) ?? Directory.GetCurrentDirectory();
+ var fileName = Path.GetFileNameWithoutExtension(path);
+ var extension = Path.GetExtension(path);
+ for (var index = 1; index < 10_000; index++)
+ {
+ var candidate = Path.Combine(directory, $"{fileName}-{index}{extension}");
+ if (!File.Exists(candidate))
+ {
+ return candidate;
+ }
+ }
+
+ throw new IOException($"无法创建唯一文件路径:{path}");
+ }
+
+ private static string NormalizePageRangeForFileName(string pageRange)
+ {
+ return string.Concat(pageRange.Select(ch => char.IsLetterOrDigit(ch) ? ch : '-')).Trim('-');
+ }
+}
\ No newline at end of file
diff --git a/Helpers/WindowsPrintApi.cs b/Helpers/WindowsPrintApi.cs
new file mode 100644
index 0000000..a2b9344
--- /dev/null
+++ b/Helpers/WindowsPrintApi.cs
@@ -0,0 +1,117 @@
+using System.Runtime.InteropServices;
+
+namespace CloudPrint.Client.Helpers;
+
+///
+/// Windows Print Spooler API P/Invoke 声明,用于 RAW 打印、队列枚举和任务取消。
+///
+public static class WindowsPrintApi
+{
+ public const int JobControlCancel = 3;
+ public const int JobControlDelete = 5;
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ public sealed class DocInfo
+ {
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string DocumentName = string.Empty;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? OutputFile;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string DataType = "RAW";
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct SystemTime
+ {
+ public short Year;
+ public short Month;
+ public short DayOfWeek;
+ public short Day;
+ public short Hour;
+ public short Minute;
+ public short Second;
+ public short Milliseconds;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ public struct JobInfo1
+ {
+ public int JobId;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? PrinterName;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? MachineName;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? UserName;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? DocumentName;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? DataType;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string? StatusText;
+
+ public int Status;
+ public int Priority;
+ public int Position;
+ public int TotalPages;
+ public int PagesPrinted;
+ public SystemTime Submitted;
+ }
+
+ [DllImport("winspool.drv", EntryPoint = "OpenPrinterW", SetLastError = true, CharSet = CharSet.Unicode)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool OpenPrinter(string printerName, out IntPtr printerHandle, IntPtr printerDefaults);
+
+ [DllImport("winspool.drv", EntryPoint = "ClosePrinter", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool ClosePrinter(IntPtr printerHandle);
+
+ [DllImport("winspool.drv", EntryPoint = "StartDocPrinterW", SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern int StartDocPrinter(IntPtr printerHandle, int level, [In] DocInfo documentInfo);
+
+ [DllImport("winspool.drv", EntryPoint = "EndDocPrinter", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool EndDocPrinter(IntPtr printerHandle);
+
+ [DllImport("winspool.drv", EntryPoint = "StartPagePrinter", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool StartPagePrinter(IntPtr printerHandle);
+
+ [DllImport("winspool.drv", EntryPoint = "EndPagePrinter", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool EndPagePrinter(IntPtr printerHandle);
+
+ [DllImport("winspool.drv", EntryPoint = "WritePrinter", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool WritePrinter(IntPtr printerHandle, byte[] data, int count, out int written);
+
+ [DllImport("winspool.drv", EntryPoint = "EnumJobsW", SetLastError = true, CharSet = CharSet.Unicode)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool EnumJobs(
+ IntPtr printerHandle,
+ int firstJob,
+ int numberOfJobs,
+ int level,
+ IntPtr jobBuffer,
+ int bufferSize,
+ out int bytesNeeded,
+ out int jobsReturned);
+
+ [DllImport("winspool.drv", EntryPoint = "SetJobW", SetLastError = true, CharSet = CharSet.Unicode)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool SetJob(
+ IntPtr printerHandle,
+ int jobId,
+ int level,
+ IntPtr jobInfo,
+ int command);
+}
\ No newline at end of file
diff --git a/Infrastructure/AsyncRelayCommand.cs b/Infrastructure/AsyncRelayCommand.cs
new file mode 100644
index 0000000..e30d481
--- /dev/null
+++ b/Infrastructure/AsyncRelayCommand.cs
@@ -0,0 +1,55 @@
+using System.Windows.Input;
+
+namespace CloudPrint.Client.Infrastructure;
+
+public sealed class AsyncRelayCommand : ICommand
+{
+ private readonly Func _execute;
+ private readonly Func? _canExecute;
+ private bool _isExecuting;
+
+ public AsyncRelayCommand(Func execute, Func? canExecute = null)
+ {
+ _execute = execute ?? throw new ArgumentNullException(nameof(execute));
+ _canExecute = canExecute;
+ }
+
+ public event EventHandler? CanExecuteChanged;
+
+ public bool IsExecuting
+ {
+ get => _isExecuting;
+ private set
+ {
+ if (_isExecuting == value)
+ {
+ return;
+ }
+
+ _isExecuting = value;
+ RaiseCanExecuteChanged();
+ }
+ }
+
+ public bool CanExecute(object? parameter) => !IsExecuting && (_canExecute?.Invoke() ?? true);
+
+ public async void Execute(object? parameter)
+ {
+ if (!CanExecute(parameter))
+ {
+ return;
+ }
+
+ try
+ {
+ IsExecuting = true;
+ await _execute().ConfigureAwait(true);
+ }
+ finally
+ {
+ IsExecuting = false;
+ }
+ }
+
+ public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
+}
\ No newline at end of file
diff --git a/Infrastructure/IUiDispatcher.cs b/Infrastructure/IUiDispatcher.cs
new file mode 100644
index 0000000..a7e9933
--- /dev/null
+++ b/Infrastructure/IUiDispatcher.cs
@@ -0,0 +1,6 @@
+namespace CloudPrint.Client.Infrastructure;
+
+public interface IUiDispatcher
+{
+ void Invoke(Action action);
+}
\ No newline at end of file
diff --git a/Infrastructure/ObservableObject.cs b/Infrastructure/ObservableObject.cs
new file mode 100644
index 0000000..99cb8cb
--- /dev/null
+++ b/Infrastructure/ObservableObject.cs
@@ -0,0 +1,26 @@
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+
+namespace CloudPrint.Client.Infrastructure;
+
+public abstract class ObservableObject : INotifyPropertyChanged
+{
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ protected bool SetProperty(ref T field, T value, [CallerMemberName] string? propertyName = null)
+ {
+ if (EqualityComparer.Default.Equals(field, value))
+ {
+ return false;
+ }
+
+ field = value;
+ OnPropertyChanged(propertyName);
+ return true;
+ }
+
+ protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+}
\ No newline at end of file
diff --git a/Infrastructure/RelayCommand.cs b/Infrastructure/RelayCommand.cs
new file mode 100644
index 0000000..bd4daa7
--- /dev/null
+++ b/Infrastructure/RelayCommand.cs
@@ -0,0 +1,28 @@
+using System.Windows.Input;
+
+namespace CloudPrint.Client.Infrastructure;
+
+public sealed class RelayCommand : ICommand
+{
+ private readonly Action