diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6355831 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,213 @@ +# Continuous integration for PDFStream.NET. +# +# On every push and pull request this workflow builds the solution, runs the tests for both target +# frameworks (net8.0-windows and net10.0-windows), packs the NuGet package and publishes the test-print +# sample as one self-contained exe. The package and the sample are only kept as artifacts of the run: +# nothing is published to NuGet or anywhere else, and the workflow uses no secrets. +# +# Every command runs from the repository root, because global.json there switches "dotnet test" to +# Microsoft Testing Platform. That is why the test steps use --project and --framework (and never the +# old VSTest --filter option). +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +# A newer push to the same branch, or a new commit on the same pull request, makes a run that is still going +# pointless, so it is cancelled. Runs for different refs never cancel each other. +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # No usage data leaves the build: the .NET CLI and Microsoft Testing Platform both honour these. + DOTNET_CLI_TELEMETRY_OPTOUT: '1' + TESTINGPLATFORM_TELEMETRY_OPTOUT: '1' + DOTNET_NOLOGO: '1' + +jobs: + build-test-pack: + name: Build, test and pack (windows-latest) + runs-on: windows-latest + # A stuck print or test run (for example a printer dialog nobody can close) fails after 30 minutes instead of + # holding a runner for GitHub's default of six hours. + timeout-minutes: 30 + defaults: + run: + shell: pwsh + + steps: + - name: Check out the repository + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Install the .NET SDKs + uses: actions/setup-dotnet@v6 + with: + # The .NET 10 SDK builds both targets and runs the tests through Microsoft Testing Platform; + # the .NET 8 install brings the runtime the net8.0-windows tests run on. + dotnet-version: | + 8.0.x + 10.0.x + + - name: Show the .NET SDK in use + run: dotnet --version + + # Reports, never fails. Eight facade tests and the eight real-print tests need the + # "Microsoft Print to PDF" printer and skip themselves (with a reason) when it is missing, so this + # step and the skipped-test report below make a silent skip visible. + - name: Report the printer the real-print tests need + continue-on-error: true + run: | + try { + $printer = Get-Printer -Name 'Microsoft Print to PDF' -ErrorAction SilentlyContinue + if ($printer) { + "Microsoft Print to PDF is installed on this runner (driver: $($printer.DriverName)). The tests that print to it will run." + } else { + "::warning title=Printer missing::Microsoft Print to PDF is not installed on this runner. The facade and real-print tests that need it will be skipped; see the skipped-test report." + } + $spooler = Get-Service -Name Spooler -ErrorAction SilentlyContinue + "Print Spooler service: $(if ($spooler) { $spooler.Status } else { 'not found' })" + } catch { + "::warning title=Printer check failed::Could not check the printers: $($_.Exception.Message)" + } + exit 0 + + - name: Restore + run: dotnet restore + + - name: Build + run: dotnet build --configuration Release --no-restore + + - name: Test (net8.0-windows) + run: >- + dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj + --framework net8.0-windows --configuration Release --no-build + --results-directory artifacts/test-results + --report-xunit-trx --report-xunit-trx-filename net8.0-windows.trx + + - name: Test (net10.0-windows) + run: >- + dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj + --framework net10.0-windows --configuration Release --no-build + --results-directory artifacts/test-results + --report-xunit-trx --report-xunit-trx-filename net10.0-windows.trx + + # Reports, never fails: counts the skipped tests in each framework's results and lists them with + # the reason each test gave, in the log and on the run's summary page. + - name: Report skipped tests + if: always() + continue-on-error: true + run: | + try { + $lines = @('### Test results', '') + $files = @(Get-ChildItem artifacts/test-results -Filter *.trx -ErrorAction SilentlyContinue) + if ($files.Count -eq 0) { $lines += 'No test result files were found.' } + foreach ($file in $files) { + [xml]$trx = Get-Content $file.FullName -Raw + $results = @($trx.TestRun.Results.UnitTestResult) + $passed = @($results | Where-Object { $_.outcome -eq 'Passed' }).Count + $failed = @($results | Where-Object { $_.outcome -eq 'Failed' }).Count + $skipped = @($results | Where-Object { $_.outcome -eq 'NotExecuted' }) + $lines += "**$($file.BaseName)**: $($results.Count) tests, $passed passed, $failed failed, $($skipped.Count) skipped" + foreach ($test in $skipped) { + $reason = "$($test.Output.StdOut)".Trim() + $lines += "- skipped: $($test.testName)$(if ($reason) { " ($reason)" })" + } + if ($skipped.Count -gt 0) { "::warning title=Skipped tests::$($skipped.Count) tests were skipped on $($file.BaseName)." } + $lines += '' + } + $lines | ForEach-Object { $_ } + if ($env:GITHUB_STEP_SUMMARY) { $lines | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8 } + } catch { + "::warning title=Skipped-test report failed::$($_.Exception.Message)" + } + exit 0 + + - name: Upload the test results + if: always() + uses: actions/upload-artifact@v7 + with: + name: test-results + path: artifacts/test-results + if-no-files-found: warn + + - name: Pack the NuGet package + run: dotnet pack src/PDFStream.NET/PDFStream.NET.csproj --configuration Release --no-build --output artifacts/package + + # Fails the run if the package lost its licence, notices, readme, metadata or PDFium dependency, or + # picked up a file type that has no business in it (keys, certificates, settings, scripts). + - name: Check the package contents + run: | + Add-Type -AssemblyName System.IO.Compression.FileSystem + # The version being released: VersionPrefix plus VersionSuffix in Directory.Build.props. A version published + # on nuget.org is permanent, so the check pins it exactly. Change it together with that file when a new + # version is released. + $expectedVersion = '1.0.0-rc.1' + # The package id, the assembly and the namespace are all PDFStream.NET, so the file is + # PDFStream.NET..nupkg and its manifest PDFStream.NET.nuspec. Exactly one must exist. + $packages = @(Get-ChildItem artifacts/package -Filter 'PDFStream.NET.*.nupkg' | Where-Object { $_.Name -notlike '*.snupkg' }) + if ($packages.Count -ne 1) { throw "Expected one PDFStream.NET.$expectedVersion.nupkg, found $($packages.Count): $($packages.Name -join ', ')" } + if ($packages[0].Name -cne "PDFStream.NET.$expectedVersion.nupkg") { throw "The package file is '$($packages[0].Name)', not PDFStream.NET.$expectedVersion.nupkg" } + $package = $packages[0] + $zip = [IO.Compression.ZipFile]::OpenRead($package.FullName) + try { + $entries = @($zip.Entries | ForEach-Object { $_.FullName }) + $manifest = $zip.Entries | Where-Object { $_.FullName -ceq 'PDFStream.NET.nuspec' } + if (-not $manifest) { throw 'The package has no PDFStream.NET.nuspec.' } + $reader = [IO.StreamReader]::new($manifest.Open()) + [xml]$nuspec = $reader.ReadToEnd() + $reader.Dispose() + } finally { $zip.Dispose() } + $problems = @() + foreach ($required in 'LICENSE', 'THIRD-PARTY-NOTICES.md', 'README.md', 'lib/net8.0-windows7.0/PDFStream.NET.dll', 'lib/net10.0-windows7.0/PDFStream.NET.dll') { + if ($entries -cnotcontains $required) { $problems += "missing file: $required" } + } + $metadata = $nuspec.package.metadata + if ($metadata.id -cne 'PDFStream.NET') { $problems += "the package id is '$($metadata.id)', not PDFStream.NET" } + if ($metadata.title -cne 'PDFStream.NET') { $problems += "the package title is '$($metadata.title)', not PDFStream.NET" } + if ($metadata.version -cne $expectedVersion) { $problems += "the package version is '$($metadata.version)', not $expectedVersion" } + if ($metadata.license.'#text' -ne 'MIT') { $problems += 'the licence expression is not MIT' } + if ($metadata.readme -ne 'README.md') { $problems += 'the package readme is not README.md' } + if ($metadata.authors -ne 'P4 Software') { $problems += 'the authors are not P4 Software' } + if ($metadata.repository.url -cne 'https://github.com/P4Software/PDFStream.NET') { $problems += 'the repository URL is missing or wrong' } + foreach ($group in @($metadata.dependencies.group)) { + $pdfium = @($group.dependency | Where-Object { $_.id -ceq 'bblanchon.PDFium.Win32' }) + if ($pdfium.Count -ne 1) { $problems += "$($group.targetFramework) does not depend on bblanchon.PDFium.Win32 (pdfium.dll)" } + # The exact PDFium build that was tested (the nuspec writes it as "160.0.8165", which NuGet reads as "160.0.8165 or newer"). + elseif ($pdfium[0].version -cne '160.0.8165') { $problems += "$($group.targetFramework) depends on bblanchon.PDFium.Win32 $($pdfium[0].version), not 160.0.8165" } + } + $unexpected = @($entries | Where-Object { $_ -match '\.(snk|pfx|p12|pem|key|cer|ps1|cmd|bat|json|config)$' }) + if ($unexpected.Count -gt 0) { $problems += "unexpected files: $($unexpected -join ', ')" } + "Package: $($package.Name)"; $entries | Sort-Object | ForEach-Object { " $_" } + if ($problems.Count -gt 0) { $problems | ForEach-Object { "::error title=Package check::$_" }; exit 1 } + 'The PDFStream.NET package has the licence, the third-party notices, the readme, the metadata and the PDFium dependency.' + + - name: Upload the NuGet package + uses: actions/upload-artifact@v7 + with: + name: PDFStream.NET-nuget-package + path: artifacts/package + if-no-files-found: error + + # One exe that includes the .NET runtime and pdfium.dll, so a person can double-click it on a + # machine without .NET installed. Not trimmed: the settings reader relies on reflection. + - name: Publish the test-print sample (win-x64, self-contained, single file) + run: >- + dotnet publish samples/PDFStream.NET.TestPrint/PDFStream.NET.TestPrint.csproj + --framework net10.0-windows --configuration Release --runtime win-x64 --self-contained true + -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=embedded + -p:PublishDocumentationFiles=false + --output artifacts/testprint + + - name: Upload the test-print sample + uses: actions/upload-artifact@v7 + with: + name: PDFStream.NET.TestPrint-win-x64 + path: artifacts/testprint + if-no-files-found: error diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..affedf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# Build output +bin/ +obj/ +artifacts/ + +# Test results +TestResults/ + +# Packages produced by dotnet pack +*.nupkg +*.snupkg + +# IDE and user state +.vs/ +.idea/ +*.user +*.suo diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3176ef8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,154 @@ +# Changelog + +All notable changes to PDFStream.NET are recorded here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses +[Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## 1.0.0-rc.1 - 2026-11-21 + +The first release of PDFStream.NET, a release candidate (a prerelease on NuGet). The stable 1.0.0 follows once the +remaining manual release checklist rows are verified (Arm64, a scheduled task, IIS, other physical and duplex +printers); see "Verified" below for what was run and what was not. + +### Added + +- Solution scaffold: the `PDFStream.NET` library and its xUnit.net test project, targeting + `net8.0-windows` and `net10.0-windows`. +- `PdfPrinter.Print` for a file path, a stream or a byte array, with `PrintOptions` (printer name, document + name, password, page range, copies, duplex, colour, fit to page or actual size, paper source, output file) + and an optional `CancellationToken`. It never throws for bad input or printer problems: it returns a + `PrintResult` with a `PrintStatus`, a plain-language message that says what happened and what to do next, + and the number of pages sent. +- Page ranges such as `1-5, 8, 10-12`, printed in the order written. +- Printer lookup by the exact name Windows lists (network names included), and a check of the printer's queue + before printing: a paused queue, "Use printer offline", a printer that is not available or being deleted, + and a queue that cannot be opened (a stopped Print Spooler included) are refused with a message naming the + cause. A printer that only reports Offline is not refused. +- Filled-in form fields (text fields, checkboxes and the other fields of an ordinary PDF form) print on both + print paths. PDFium never draws form fields when it draws a page, so PDFStream.NET copies the pages with fields + that a print call prints, in one go, inside its own in-memory copy of the PDF, with everything each page + inherits from the PDF's page tree (its fonts, images and page boxes included), flattens the fields into the + copies as they print, and prints the copies in place of the pages. What the pages share is copied once, and + the copies are made only for a PDF of at most 64 MB (the copy budget). A copy is used only if it carries all + of the page's annotations and looks exactly like the page; otherwise (for example on a page with layers the + PDF switches off, a page with a damaged reference, or a PDF over the budget) the fields are drawn into the + page itself, and they still print. Everything else on the page prints as before; fields not marked for + printing stay off the paper, and pages without fields are untouched. Known limitation: a page with fields + that takes fonts or images from the PDF's page tree, and whose copy cannot be used, prints without those + fonts or images. Copying relies on `FPDF_ImportPagesByIndex`, which PDFium marks as experimental, tested only + with the bundled PDFium 160.0.8165. XFA-only forms are not supported (the bundled PDFium is built without + XFA). +- Printing straight onto the printer's page as drawing commands, with a picture fallback (at most 300 dpi) + for drivers that refuse that; each page is scaled and turned on its own. Copies are made by the driver when + it can, otherwise by sending the document again in the same job. +- Internal PDF engine behind an `IPdfEngine` / `IPdfDocument` seam, implemented with PDFium: + loads a PDF from memory; tells "no password given" apart from "wrong password"; opens PDFs that + only have an owner password without asking for one; reports page sizes in points; renders a page + straight onto a Windows device context (with PDFium's printing flag) or onto a white bitmap at any + resolution. +- One process-wide lock around every PDFium call, because PDFium is not thread-safe. Calls from + several threads are safe; the lock is held per engine call, so concurrent jobs interleave at page level (the first form page of a document is a longer call; see Known limitations). +- PDFium 160.0.8165 native binaries for win-x64, win-x86 and win-arm64 (package + `bblanchon.PDFium.Win32`), with their licences in `THIRD-PARTY-NOTICES.md`. +- Real-print acceptance tests through *Microsoft Print to PDF* that check the produced pages for ink, and a + manual release checklist (`docs/release-checklist.md`). +- `samples/PDFStream.NET.TestPrint`: a double-click test-print program (net10.0-windows). It reads a + commented `settings.json` next to the exe (created on the first run), lists the installed printers, + and does a dry run by default; `ReallyPrint` set to `true` really prints. It always waits for a key + press so the result can be read, uses only the public API, and accepts paths pasted with quote marks. +- NuGet package metadata: the package id and title `PDFStream.NET`, the README as the package page, the MIT + licence expression, the repository and project address, tags, and `LICENSE` and `THIRD-PARTY-NOTICES.md` + inside the package. +- Documentation: `docs/usage.md`, `docs/services-and-iis.md`, `docs/troubleshooting.md` and `CONTRIBUTING.md`. +- CI (`.github/workflows/ci.yml`): on every push and pull request, build and test both frameworks on + `windows-latest`, report whether *Microsoft Print to PDF* exists and how many tests were skipped, pack and + check the NuGet package, and publish the test-print sample as one self-contained exe, with `LICENSE` and + `THIRD-PARTY-NOTICES.md` next to it (the exe carries the .NET runtime and `pdfium.dll`). Artifacts only; it + publishes nothing and uses no secrets. + +### Changed + +- The product is named `PDFStream.NET` everywhere: the NuGet package (`dotnet add package PDFStream.NET`), the + assembly (`PDFStream.NET.dll`) and the C# namespace, so code says `using PDFStream.NET;`. The projects, the + solution and the test-print sample carry the same name. The type names (`PdfPrinter`, `PrintOptions`, ...) are + unchanged. This was decided before the first release, while no program depends on the library yet. +- The name is written PDFStream.NET, with a capital NET (like SheetStream.NET), in the package id and title, the + assembly, the namespace, the folders and project files, the repository address + (https://github.com/P4Software/PDFStream.NET) and all the documentation. NuGet keeps the capitalisation of the + first publish permanently, so it is fixed before the first release. Earlier drafts wrote it `PDFStream.net`. + +- The C# language version is pinned to 12.0 instead of "latest", so the language no longer changes with the + installed SDK. C# 12 is the newest version the .NET 8 SDK supports. + +### Known limitations + +- Form fields: in a PDF with three or more form pages that share one indirect `/Contents` array (and one + indirect `/Resources` dictionary), later pages can also print the fields of earlier pages, with status `Ok`. + The check of each page copy catches the first affected page, but the fallback that draws the fields into the + page itself edits the shared array again. Workaround: flatten such a PDF before printing, or print its pages as + separate documents. A characterization test pins this behaviour; fixing it means changing that test and the + documentation. Planned for 1.0. +- Form fields: a crafted PDF with inline inherited values can make form printing use a lot of memory (about + 600 MB measured for a 1.2 MB PDF with 100 form pages); print untrusted PDFs in a separate worker process. +- The first page with form fields of a document runs one longer engine call that copies every form page the call + prints (about 77 ms on x64 and 95 ms on x86 for 500 form pages, as measured in a review); it holds the + process-wide lock and cannot be cancelled. +- If reloading a flattened page fails, which is practically unreachable, the page is drawn with blank form + fields and status `Ok`. + +### Verified + +Test hosts actually run for this change (one Windows 11 x64 machine, .NET SDK 11.0.100; the test counts are +from the last run, on 2026-11-21, Debug build, after the name was set to PDFStream.NET): + +- win-x64: `net8.0-windows` (452 tests) and `net10.0-windows` (477 tests), all passed, none skipped. +- win-x86: `net8.0-windows` (452 tests) and `net10.0-windows` (477 tests) + (`dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --arch x86`), all passed, none + skipped; the form, engine, real-print and memory tests logged `Process architecture: X86`. On an earlier + 32-bit `net10.0-windows` run that day, one real-print test timed out after 30 seconds waiting for + *Microsoft Print to PDF* to finish writing its file, and the re-run passed; that wait is now 120 seconds, and + a timeout reports the state of the print queue. +- win-arm64: **not run**. No arm64 machine was available, and an x64 machine cannot execute arm64 + code. The arm64 `pdfium.dll` is present in the package and exports the same functions, but + loading it is unverified. +- On 2026-11-20, under the package's earlier id (before the name PDFStream.net was chosen): the NuGet package + from a separate consumer app outside the repository, restored from a local folder + into an empty package cache, with the .NET 10 SDK (10.0.404) on `net8.0-windows` and `net10.0-windows` and + the .NET 8 SDK (8.0.428) on `net8.0-windows`: for win-x64, win-x86 and win-arm64, both `dotnet build -r` + and `dotnet publish -r` put the `pdfium.dll` of that architecture next to the exe (checked by SHA-256 + against the PDFium package and by the file's machine type); a build with no runtime identifier puts all + three under `runtimes`. The x64, x86 and no-runtime-identifier builds were run and printed a two-page PDF + to *Microsoft Print to PDF* (two pages in the output file). The arm64 builds were checked as files only. +- On 2026-11-21, under the spelling `PDFStream.net` (lowercase, before the final spelling PDFStream.NET was chosen): + the package was packed again and + used from separate win-x64 and win-x86 apps outside the repository (empty package cache, local folder feed, + `using PDFStream.net;`); both printed a two-page PDF to *Microsoft Print to PDF* (two pages in the output file) and + `pdfium.dll` of the right architecture was next to the exe. The package holds `lib/net8.0-windows7.0/PDFStream.net.dll` + and `lib/net10.0-windows7.0/PDFStream.net.dll`; the self-contained test-print sample was published as + `PDFStream.net.TestPrint.exe` and its dry run says `PDFStream.net test print`. +- On 2026-11-21, still under the lowercase spelling, after the form-printing changes of that day: `dotnet pack -c Release` into a folder outside the + repository gave `PDFStream.net.1.0.0-preview.nupkg`, and the package check from `ci.yml` passed against it. A + separate win-x64 app on `net10.0-windows` restored it from that folder into an empty package cache, reported + the assembly and the namespace as `PDFStream.net`, and printed a one-page PDF with a filled form field to + *Microsoft Print to PDF* (status Ok, one page, output file written; its content was not inspected). +- On 2026-11-20: the self-contained single-file test-print sample (win-x64) printed a two-page PDF to + *Microsoft Print to PDF*. +- On 2026-11-21, still under the lowercase spelling, with the version set to 1.0.0-rc.1: `dotnet pack -c Release` into a folder outside the repository + gave `PDFStream.net.1.0.0-rc.1.nupkg` (lowercase spelling; nuspec version `1.0.0-rc.1`; `AssemblyVersion` and `FileVersion` 1.0.0.0; the + informational version is `1.0.0-rc.1` plus the commit hash), and the package check from `ci.yml` passed against it. + A separate win-x64 app on `net10.0-windows` restored it (``) + from that folder into an empty package cache and printed a two-page PDF to *Microsoft Print to PDF* (status Ok, + two pages, output file written with two pages). +- On 2026-11-21, after the name was set to `PDFStream.NET` (capital NET): `dotnet build -warnaserror` gave 0 warnings + on both frameworks; `dotnet pack -c Release` into a folder outside the repository gave + `PDFStream.NET.1.0.0-rc.1.nupkg` (nuspec id and title `PDFStream.NET`, repository + `https://github.com/P4Software/PDFStream.NET`, `lib/net8.0-windows7.0/PDFStream.NET.dll` and + `lib/net10.0-windows7.0/PDFStream.NET.dll`), and the package check from `ci.yml` passed against it. The check + failed, as it must, against a pack with the lowercase id, one with a lowercase assembly name and one with the + lowercase repository address. A separate win-x64 app on `net10.0-windows` restored it into an empty package cache, + wrote `using PDFStream.NET;`, printed a one-page PDF to *Microsoft Print to PDF* (status Ok, output file written), + and `pdfium.dll` of the right architecture was next to the exe. The test-print sample was published the way CI does + it: `PDFStream.NET.TestPrint.exe` with `LICENSE` and `THIRD-PARTY-NOTICES.md` beside it, and its dry run says + `PDFStream.NET test print`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..29e9c73 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,122 @@ +# Contributing to PDFStream.NET + +Thank you for helping. Bug reports, printer and driver reports, documentation fixes and pull requests are all +welcome. Please open an [issue](https://github.com/P4Software/PDFStream.NET/issues) before a large change, so we +can agree on the approach first. + +## What you need + +- Windows 10 or 11, x64. +- The .NET 10 SDK (it builds both targets, `net8.0-windows` and `net10.0-windows`). Newer SDKs work too. +- The .NET 8 runtime, to run the `net8.0-windows` tests. +- For the 32-bit test runs: the x86 .NET 8 and .NET 10 runtimes. +- *Microsoft Print to PDF* (it ships with Windows 10 and 11) for the real-print tests. Without it those tests, + and the library tests that need a real printer name, skip themselves and say why. + +## Always run commands from the repository root + +`global.json` in the repository root switches `dotnet test` to Microsoft Testing Platform. The .NET SDK only +finds that file from the current folder upwards, so run every command below from the root of your clone. + +From any other folder, `dotnet test` falls back to the older VSTest mode and fails. With the Testing Platform +options it does not understand `--project`: + +```text +MSBUILD : error MSB1001: Unknown switch. +Switch: --project +``` + +and with a VSTest-style project argument it stops with: + +```text +error : Testing with VSTest target is no longer supported by Microsoft.Testing.Platform on .NET 10 SDK and later. +``` + +For the same reason, filter tests with the Testing Platform options (`--filter-method`, `--filter-class`, +`--filter-trait`), never with the VSTest `--filter` option. + +## Build and test + +```text +dotnet build +dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --framework net8.0-windows +dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --framework net10.0-windows +``` + +Run both frameworks before you open a pull request. The sample's tests only exist for `net10.0-windows`, +because the sample targets only that framework. + +One test, one class, or one category: + +```text +dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --framework net10.0-windows --filter-method "PDFStream.NET.Tests.Acceptance.RealPrintTests.Prints_three_page_pdf_to_file_with_three_pages_and_non_blank_output" +dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --framework net10.0-windows --filter-class "PDFStream.NET.Tests.PdfPrinterTests" +dotnet test --project tests/PDFStream.NET.Tests --filter-trait "Category=RealPrinter" --framework net8.0-windows +``` + +32-bit (x86) runs, which load the x86 `pdfium.dll`: + +```text +dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --arch x86 --framework net8.0-windows +dotnet test --project tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj --arch x86 --framework net10.0-windows +``` + +Arm64 cannot be tested on an x64 machine; it is a manual check on a real Arm64 PC. + +The real-print tests print to *Microsoft Print to PDF* into a temporary folder, open the produced PDF again and +count its pages and the ink on each page. A real print must never be judged by its status alone. + +Telemetry: to keep the .NET CLI and the Testing Platform from sending usage data, set +`DOTNET_CLI_TELEMETRY_OPTOUT=1` and `TESTINGPLATFORM_TELEMETRY_OPTOUT=1` in your environment (CI does). + +## Package and sample + +```text +dotnet pack src/PDFStream.NET/PDFStream.NET.csproj --configuration Release --output artifacts/package +dotnet publish samples/PDFStream.NET.TestPrint/PDFStream.NET.TestPrint.csproj --framework net10.0-windows --configuration Release --runtime win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=embedded -p:PublishDocumentationFiles=false --output artifacts/testprint +``` + +The package is named `PDFStream.NET`, so `dotnet pack` writes `artifacts/package/PDFStream.NET..nupkg` +(`PDFStream.NET.1.0.0-rc.1.nupkg` for the first release). The version is set in one place, `VersionPrefix` and +`VersionSuffix` in `Directory.Build.props`, and the package check in `.github/workflows/ci.yml` expects the same +version: change both together when a new version is released. +The assembly inside it is `PDFStream.NET.dll` and the namespace is `PDFStream.NET`. + +The package does not contain `pdfium.dll` itself: it depends on the `bblanchon.PDFium.Win32` package, whose +`runtimes/win-x64`, `win-x86` and `win-arm64` folders give a consuming app the right copy. If you change +anything about packaging, check it from a separate consumer app outside the repository: reference the package +with ``, add +`artifacts/package` as a package source in that app's `nuget.config`, point `NUGET_PACKAGES` at an empty +folder (so an older copy of the package in your cache cannot stand in for the new one), build and publish it +with `-r win-x64`, `-r win-x86`, `-r win-arm64` and with no runtime identifier, for `net8.0-windows` and +`net10.0-windows`, and check that the `pdfium.dll` next to the exe is the one for that architecture. CI checks +the package's own contents (licence, notices, readme, metadata, the PDFium dependency) on every run. + +The publish command makes one exe that includes .NET and `pdfium.dll`, so it runs by double-click on a +machine without .NET. + +## Before a release + +Work through the [manual release checklist](docs/release-checklist.md). Nothing in it counts as verified until +someone has run the check and written the machine, the date and the result in the row. Never mark a row from +memory. + +## Rules for code + +- The public API never throws for bad input or printer problems: it returns a `PrintResult` with a status and + a plain-language message that says what happened and what to do next. +- Every public type and member has XML documentation (a missing one fails the build), and non-obvious code + has a comment saying why. +- "Printed" means pages were rendered and sent. Tests check output pixels, not only the status. +- PDFium is not thread-safe: every call into it goes through the one process-wide lock in `PdfiumLibrary`. +- No telemetry, network calls, licence keys, watermarks or expiry dates, ever. +- Every dependency must be permissively licensed (MIT, BSD, Apache-2.0) and redistributable. Read its licence + file before you add it, and add it to [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). PDFsharp in the test + project is pinned to 6.2.4 on purpose: later versions are AGPL. + +## Commits and pull requests + +- Commits are authored by you, under your own name and e-mail address. +- Never commit secrets: no keys, passwords, tokens, certificates or private settings files. +- Do not copy code from commercial PDF libraries or from private applications. +- By contributing you agree that your contribution is released under the project's [MIT licence](LICENSE). diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..dbf485b --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,56 @@ + + + + + + net8.0-windows;net10.0-windows + + 12.0 + enable + enable + + + + + true + $(WarningsAsErrors);CS1591 + + + + P4 Software + P4 Software + PDFStream.NET + Copyright (c) 2026 P4 Software + MIT + + 1.0.0 + rc.1 + + diff --git a/PDFStream.NET.sln b/PDFStream.NET.sln new file mode 100644 index 0000000..386bb0b --- /dev/null +++ b/PDFStream.NET.sln @@ -0,0 +1,73 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PDFStream.NET", "src\PDFStream.NET\PDFStream.NET.csproj", "{18073531-B3F8-4DFB-8EF3-E51126ED6DD3}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PDFStream.NET.Tests", "tests\PDFStream.NET.Tests\PDFStream.NET.Tests.csproj", "{B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{5D20AA90-6969-D8BD-9DCD-8634F4692FDA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PDFStream.NET.TestPrint", "samples\PDFStream.NET.TestPrint\PDFStream.NET.TestPrint.csproj", "{08C09ED8-E7BC-4BD6-B581-78B7505D7388}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Debug|x64.ActiveCfg = Debug|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Debug|x64.Build.0 = Debug|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Debug|x86.ActiveCfg = Debug|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Debug|x86.Build.0 = Debug|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Release|Any CPU.Build.0 = Release|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Release|x64.ActiveCfg = Release|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Release|x64.Build.0 = Release|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Release|x86.ActiveCfg = Release|Any CPU + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3}.Release|x86.Build.0 = Release|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Debug|x64.ActiveCfg = Debug|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Debug|x64.Build.0 = Debug|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Debug|x86.ActiveCfg = Debug|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Debug|x86.Build.0 = Debug|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Release|Any CPU.Build.0 = Release|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Release|x64.ActiveCfg = Release|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Release|x64.Build.0 = Release|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Release|x86.ActiveCfg = Release|Any CPU + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F}.Release|x86.Build.0 = Release|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Debug|Any CPU.Build.0 = Debug|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Debug|x64.ActiveCfg = Debug|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Debug|x64.Build.0 = Debug|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Debug|x86.ActiveCfg = Debug|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Debug|x86.Build.0 = Debug|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Release|Any CPU.ActiveCfg = Release|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Release|Any CPU.Build.0 = Release|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Release|x64.ActiveCfg = Release|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Release|x64.Build.0 = Release|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Release|x86.ActiveCfg = Release|Any CPU + {08C09ED8-E7BC-4BD6-B581-78B7505D7388}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {18073531-B3F8-4DFB-8EF3-E51126ED6DD3} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {B9256D53-22FC-4AEE-BBE7-1A2C5D52C80F} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {08C09ED8-E7BC-4BD6-B581-78B7505D7388} = {5D20AA90-6969-D8BD-9DCD-8634F4692FDA} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index 7ef3e91..c9ab859 100644 --- a/README.md +++ b/README.md @@ -1,96 +1,195 @@
-# PDFStream +# PDFStream.NET **Free, open-source PDF printing for .NET.** Send a PDF to any Windows printer in one line of code. No Adobe Reader, no licence keys, no watermarks. -![Status: early development](https://img.shields.io/badge/status-early%20development-orange) +![Status: 1.0.0-rc.1 release candidate](https://img.shields.io/badge/status-1.0.0--rc.1%20release%20candidate-yellow) ![Platform: Windows](https://img.shields.io/badge/platform-Windows-0078D4) -![.NET 10](https://img.shields.io/badge/.NET-10-512BD4) -![Open source](https://img.shields.io/badge/open%20source-free%20forever-brightgreen) +![.NET 8 and 10](https://img.shields.io/badge/.NET-8%20%7C%2010-512BD4) +![Licence: MIT](https://img.shields.io/badge/licence-MIT-brightgreen)
--- -> **Heads up: PDFStream is just getting started.** -> The code is not published yet. This page describes what we are building and why, -> so you can follow along, give feedback and help shape it. +> **Status: version 1.0.0-rc.1, the first release (a release candidate).** The library is complete and its automated tests pass, including +> real prints to *Microsoft Print to PDF* in 64-bit and 32-bit processes. The manual release checklist +> (physical printers, a Windows service, a scheduled task, Arm64 hardware) is **not complete yet**, and the +> package (`PDFStream.NET`) is **not on NuGet yet**. The stable 1.0.0 follows once the remaining checklist rows +> (Arm64, a scheduled task, IIS, other physical and duplex printers) are verified. PDF to image conversion is +> planned after 1.0. +> See [what has been verified](#what-has-been-verified). -## Why PDFStream? +## Why PDFStream.NET? -Printing a PDF from a .NET application should not need a paid licence, a licence key that -expires, or a copy of Adobe Reader installed on every server. Yet today most developers either -pay for a commercial library or fight with the Windows print system themselves. +Printing a PDF from a .NET application should not need a paid licence, a licence key that expires, or a copy +of Adobe Reader installed on every server. Yet today most developers either pay for a commercial library or +fight with the Windows print system themselves. -PDFStream is a small, focused library that does one job well: **take a PDF and print it, silently, -on the printer you choose.** It is built by [P4 Software](https://github.com/P4Software) because we -needed it for our own warehouse software, and we are sharing it so nobody else has to pay for it. +PDFStream.NET is a small, focused library that does one job well: **take a PDF and print it, silently, on the +printer you choose.** It is built by [P4 Software](https://github.com/P4Software) because we needed it for our +own warehouse software, and we are sharing it so nobody else has to pay for it. -## What it will do (version 1) +## What it does -- **Silent printing**: no dialogs, no user interaction. Works from services, scheduled tasks and servers. +- **Silent printing**: no dialogs, no user interaction, for programs that print with nobody at the screen. - **Any printer Windows can see**: physical printers and virtual ones such as *Microsoft Print to PDF*. - **Any input**: a file path, a stream or a byte array. -- **Print options**: page ranges, number of copies, duplex, colour or black and white, scaling, paper source. -- **Password-protected PDFs**. -- **Plain-language results**: every failure comes back as a clear message that says what went wrong - and what to do next, not a cryptic code. -- **No Adobe, no third-party installs**: the PDF rendering engine ships inside the package. -- **No licence keys. Ever.** +- **Print options**: page ranges, copies, duplex, colour or black and white, fit to page or actual size, + paper source, and printing to a file. +- **Password-protected PDFs.** +- **Plain-language results**: every failure comes back as a status and a message that says what went wrong + and what to do next. It never throws managed exceptions for bad input or printer problems, such as a bad file + or a paused printer. A crash inside the native PDF engine is the one thing no .NET library can turn into a + result; see [Security and limits](https://github.com/P4Software/PDFStream.NET/blob/main/docs/usage.md#security-and-limits). +- **No Adobe, nothing else to install**: the PDF engine (PDFium) comes with the package for x64, x86 and Arm64. +- **No licence keys, watermarks, expiry dates, telemetry or network calls. Ever.** + +## Install + +PDFStream.NET is not published on NuGet yet. Version 1.0.0-rc.1 is the first release and a prerelease, so once it +is published a plain `dotnet add package PDFStream.NET` finds nothing until the stable 1.0.0 exists. Add the +prerelease explicitly: + +```text +dotnet add package PDFStream.NET --prerelease +``` + +or name the version: `dotnet add package PDFStream.NET --version 1.0.0-rc.1`. On nuget.org the package page lists +prereleases only when "Include prerelease" is ticked. + +The package, the assembly and the namespace are all called `PDFStream.NET`: in your code you write +`using PDFStream.NET;`. + +Until then, build the package from this repository (see [CONTRIBUTING.md](https://github.com/P4Software/PDFStream.NET/blob/main/CONTRIBUTING.md)) and add the +folder it lands in as a package source. -Coming after version 1: PDF to image conversion (PNG, JPG, TIFF). +Requirements: -## What it will look like +- Windows 10 or Windows Server 2016, or newer. +- A project that targets a Windows framework: `net8.0-windows`, `net10.0-windows` or newer. (Plain `net8.0` + cannot reference it, because printing goes through the Windows print system.) -This is a design sketch of the planned API, not final code: +The package brings the PDF engine's `pdfium.dll` for 64-bit, 32-bit and Arm64 Windows, and your build puts the +right one next to your program. There is nothing else to install. + +## Use it ```csharp +using PDFStream.NET; + // Print a PDF that is already in memory, for example one just downloaded from an API. byte[] pdf = await File.ReadAllBytesAsync("packing-slip.pdf"); PrintResult result = PdfPrinter.Print(pdf, new PrintOptions { - PrinterName = "Warehouse Printer 1", + PrinterName = "Warehouse Printer 1", // exactly as Windows lists it, or \\server\printer Copies = 2, }); if (!result.Succeeded) { - // The message is written for people, so it can go straight into a log or a screen. + // The message is written for people: log it, or show it to the person running the program. An + // UnknownError message can end with technical details, so keep it out of public web pages. Console.WriteLine(result.Message); } ``` -## Requirements +The same call accepts a file path or a stream, and an optional `CancellationToken`: -- Windows 10 / Windows Server 2016 or newer -- .NET 10 (a Windows target such as `net10.0-windows`) +```csharp +PrintResult fromFile = PdfPrinter.Print(@"C:\Slips\slip-1042.pdf", new PrintOptions +{ + PrinterName = "Warehouse Printer 1", + Pages = "1-3, 5", + Duplex = DuplexMode.LongEdge, + Color = false, +}); + +using FileStream stream = File.OpenRead("invoice.pdf"); +PrintResult fromStream = PdfPrinter.Print(stream, new PrintOptions +{ + PrinterName = "Microsoft Print to PDF", + OutputFile = @"C:\Out\invoice-copy.pdf", // print to a file, no Save As dialog +}, cancellationToken); +``` -Linux and macOS are not planned for version 1 because printing goes through the Windows print system. +`result.Status` tells your code what happened (`Ok`, `FileNotFound`, `PasswordRequired`, `PrinterNotFound`, +`PrinterUnavailable`, ...), `result.Message` tells a person, and `result.PagesPrinted` says how many pages +were sent. + +## Documentation + +- [Usage guide](https://github.com/P4Software/PDFStream.NET/blob/main/docs/usage.md): every option, every status and its message, copies, passwords, printing + to a file, cancelling, threads. +- [Services, scheduled tasks and IIS](https://github.com/P4Software/PDFStream.NET/blob/main/docs/services-and-iis.md): the account must be able to see the + printer, and other things a program without a screen needs. +- [Troubleshooting](https://github.com/P4Software/PDFStream.NET/blob/main/docs/troubleshooting.md), organised by the message you got. +- [Contributing](https://github.com/P4Software/PDFStream.NET/blob/main/CONTRIBUTING.md): building, testing and the release checklist. +- [Security](https://github.com/P4Software/PDFStream.NET/blob/main/SECURITY.md): how to report a vulnerability privately; read + [Security and limits](https://github.com/P4Software/PDFStream.NET/blob/main/docs/usage.md#security-and-limits) before printing PDFs you do not trust. + +## Try it without writing code + +`samples/PDFStream.NET.TestPrint` is a small program you run by double-clicking `PDFStream.NET.TestPrint.exe`. On the +first run it creates a commented `settings.json` next to itself and lists your printers. Fill in the printer +name and a PDF, and run it again: by default it is a **dry run** that only checks your settings and shows what +it would send. Set `ReallyPrint` to `true` to print. Paths copied with Explorer's "Copy as path" work even +though they carry quote marks. It is also a short example of using the public API. + +Every CI build keeps a ready-to-run copy (the `PDFStream.NET.TestPrint-win-x64` artifact): a single exe for 64-bit +(x64) Windows only, which includes .NET and `pdfium.dll`, so .NET does not have to be installed. It is not signed, +so Windows SmartScreen may warn before it runs, and on its first run it extracts `pdfium.dll` to a folder under +your temporary folder. `LICENSE` and `THIRD-PARTY-NOTICES.md` come next to the exe: it carries the .NET runtime +(MIT; its own third-party notices apply too) and PDFium, and any program that redistributes `pdfium.dll` must +carry the PDFium section of those notices. Built from source without those publish options, the sample needs +the .NET 10 runtime. + +## What has been verified + +On one Windows 11 x64 machine: + +- The full test suite for `net8.0-windows` and `net10.0-windows`, in a 64-bit and in a 32-bit (x86) process, + including real prints to *Microsoft Print to PDF* whose output is checked page by page for ink. Last run on + 2026-11-21, after the name was set to PDFStream.NET: all tests passed, none skipped (452 on `net8.0-windows`, + 477 on `net10.0-windows`). +- The package, from a separate app outside this repository. Under the package's earlier names, on 2026-11-20 and + 2026-11-21: built and published for win-x64, win-x86 and win-arm64 on both frameworks, the right `pdfium.dll` + lands next to the app, and the x64 and x86 builds printed a two-page PDF to *Microsoft Print to PDF* (the + CHANGELOG lists each run and the spelling of the name at the time). Under its final name PDFStream.NET, on + 2026-11-21: the package was packed as `PDFStream.NET.1.0.0-rc.1.nupkg` and used from a separate win-x64 app on + `net10.0-windows` with `using PDFStream.NET;`, which printed a PDF to *Microsoft Print to PDF*, and the right + `pdfium.dll` landed next to the exe. + +Not verified yet (they are on the [release checklist](https://github.com/P4Software/PDFStream.NET/blob/main/docs/release-checklist.md)): running on an Arm64 +PC, physical printers (duplex, network printers), and printing from a Windows service, a scheduled task +or IIS. ## Roadmap | Step | What | Status | |------|------|--------| -| 1 | Project set-up, licence, build pipeline | In progress (MIT licence added) | -| 2 | Silent printing of a PDF to a chosen printer | Planned | -| 3 | Print options (ranges, copies, duplex, colour) | Planned | -| 4 | Password-protected PDFs and clear error messages | Planned | -| 5 | First NuGet release | Planned | -| 6 | PDF to image conversion | Planned | +| 1 | Project set-up, licence, build pipeline | Done | +| 2 | Silent printing of a PDF to a chosen printer | Done | +| 3 | Print options (ranges, copies, duplex, colour, scaling, paper source, print to file) | Done | +| 4 | Password-protected PDFs and clear error messages | Done | +| 5 | Manual release checklist, then the first NuGet release (1.0.0-rc.1) and the stable 1.0.0 | In progress | +| 6 | PDF to image conversion (PNG, JPG, TIFF), planned after 1.0 | Planned | ## Get involved -PDFStream is open source and built in the open. Ideas, bug reports and pull requests will be -welcome as soon as the first code lands. For now, the best way to help is to open an -[issue](https://github.com/P4Software/PDFStream/issues) and tell us what you would use it for, -especially the printers, servers and PDF files that give you trouble today. +PDFStream.NET is open source and built in the open. Bug reports, printer and driver reports and pull requests +are welcome: open an [issue](https://github.com/P4Software/PDFStream.NET/issues), especially about the printers, +servers and PDF files that give you trouble today. See [CONTRIBUTING.md](https://github.com/P4Software/PDFStream.NET/blob/main/CONTRIBUTING.md). ## Licence -PDFStream is free and open source under the [MIT License](LICENSE). Use it in personal, commercial and closed-source projects, with no fees and no licence keys. +PDFStream.NET is free and open source under the [MIT License](https://github.com/P4Software/PDFStream.NET/blob/main/LICENSE), copyright 2026 P4 Software. Use it in +personal, commercial and closed-source projects, with no fees and no licence keys. The PDF engine and the +libraries inside it keep their own permissive licences; see +[THIRD-PARTY-NOTICES.md](https://github.com/P4Software/PDFStream.NET/blob/main/THIRD-PARTY-NOTICES.md). --- diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..feab84e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,65 @@ +# Security policy + +## Reporting a vulnerability + +Please do not report security problems in public issues, discussions or pull requests. + +Report them privately through GitHub's private vulnerability reporting on this repository: open the +**Security** tab of [P4Software/PDFStream.NET](https://github.com/P4Software/PDFStream.NET) and choose +**Report a vulnerability** (or go straight to +[the reporting form](https://github.com/P4Software/PDFStream.NET/security/advisories/new)). Only the maintainers and +you can see the report. + +Please include: + +- the PDFStream.NET version (or commit), the .NET version, the Windows version and the processor architecture; +- what happens (a crash of the whole process, a hang, a file read or written that should not be, and so on); +- if you can, a PDF or the steps that reproduce it. A PDF that crashes a print service is often a real + document: remove anything confidential before you attach it, or describe how to build an equivalent file. + +We will answer in the report, keep you informed while a fix is prepared, and credit you in the published +advisory unless you prefer not to be named. + +## Supported versions + +| Version | Security fixes | +| --- | --- | +| 1.0.0-rc.x and later releases (the latest release on NuGet) | Yes | +| Older releases | No: update to the latest release | +| Builds from source | No: use the latest release, or the latest commit on `main` | + +Version 1.0.0-rc.1 is the first release of PDFStream.NET (the package `PDFStream.NET`). It has not been published on +NuGet yet; until it is, fixes land on `main` only. + +## PDFium, the PDF engine + +PDFStream.NET does not build or change PDFium: it calls the prebuilt `pdfium.dll` from the +[`bblanchon.PDFium.Win32`](https://www.nuget.org/packages/bblanchon.PDFium.Win32) NuGet package. Security fixes in +PDFium are taken by updating that dependency to a newer build and releasing a new PDFStream.NET version. An +application can also reference a newer `bblanchon.PDFium.Win32` directly, which NuGet then uses instead; PDFStream.NET +has only been tested with the version it depends on. + +Printing form fields uses one PDFium function that PDFium marks as experimental: `FPDF_ImportPagesByIndex`, which +copies pages within PDFStream.NET's in-memory copy of the PDF. It has been tested only with PDFium 160.0.8165, the +version PDFStream.NET depends on. With a `pdfium.dll` in which that function is missing or fails, form fields still +print, drawn into each page itself, but a page that takes its fonts or images from the PDF's page tree then prints +without them; see [Form fields](docs/usage.md#form-fields). + +## Known limits + +PDFium runs inside the program that calls PDFStream.NET, without a sandbox, so a malformed or hostile PDF that crashes +it ends that whole process. This and the other limits (one hung printer driver stalls every print in the +process; cancellation is checked between pages only) are explained, with what to do about them, in +[Security and limits](docs/usage.md#security-and-limits). A PDF that crashes or hangs PDFStream.NET is still worth +reporting as described above. + +Two more limits are known and accepted for the first release: + +- **A crafted PDF can make form printing use a lot of memory.** A value that pages inherit from the page tree, + written inline, is copied once for every page with fields, and the copy budget does not bound it. In a + measurement, a 1.2 MB PDF with 100 form pages grew memory by about 600 MB. Print PDFs you do not trust in a + separate worker process, so that a file like this costs one job and not your service. +- **Pages that share one content array can show each other's form fields.** In a PDF with three or more form + pages that share one indirect `/Contents` array, later pages can also print the fields of earlier pages + (status `Ok`). If a printout must never carry another page's values, flatten such PDFs first. See + [Form fields](docs/usage.md#form-fields). diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..69d7267 --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,2884 @@ +# Third-party notices + +PDFStream.NET is released under the MIT licence (see [LICENSE](LICENSE)), copyright 2026 P4 Software. +It ships with, or depends on, the third-party software listed below. Each component stays under its +own licence; the full licence texts are reproduced at the end of this file. + +## PDF engine: PDFium + +| | | +|---|---| +| What | [PDFium](https://pdfium.googlesource.com/pdfium/), the PDF renderer inside Chromium, as prebuilt `pdfium.dll` files for **win-x64, win-x86 and win-arm64** | +| Package | [`bblanchon.PDFium.Win32`](https://www.nuget.org/packages/bblanchon.PDFium.Win32) **160.0.8165** (PDFium from Chromium build 8165, built by [bblanchon/pdfium-binaries](https://github.com/bblanchon/pdfium-binaries) without V8 and without XFA) | +| PDFium licence | BSD-3-Clause, with parts under Apache-2.0 (both texts are in PDFium's licence file) | +| Packaging licence | MIT (the pdfium-binaries build scripts); the NuGet package declares Apache-2.0 | +| How PDFStream.NET uses it | Through PDFStream.NET's own P/Invoke declarations (`src/PDFStream.NET/Engine/PdfiumNative.cs`), written from PDFium's public header `fpdfview.h`. No third-party .NET binding is used. | + +The NuGet package itself contains no licence files. The texts below come from the release archives of +the same build (release `chromium/8165` of bblanchon/pdfium-binaries), whose `LICENSE` says: "This +package also includes third-party software. See the licenses/ directory for their respective licenses." + +What was checked, on 2026-11-20, for all three archives (`pdfium-win-x64.tgz`, `pdfium-win-x86.tgz` and +`pdfium-win-arm64.tgz`): each archive matches the SHA-256 digest published on the release; the +`bin/pdfium.dll` in each archive is byte for byte the `pdfium.dll` that the NuGet package ships for that +architecture; the `LICENSE` file and the 18 files in `licenses/` are identical in all three archives; +`VERSION` is the same (160.0.8165.0); and the build settings file `args.gn` differs only in +`target_cpu`. So the licence texts below apply to all three binaries. + +### Why this package and not a .NET binding + +| Candidate | Version checked | Licence | Decision | +|---|---|---|---| +| `bblanchon.PDFium.Win32` + PDFStream.NET's own P/Invoke | 160.0.8165 | Apache-2.0 (package), MIT (scripts), BSD-3-Clause/Apache-2.0 (PDFium) | **Chosen.** Ships win-x64, win-x86 and win-arm64 binaries; all three export `FPDF_RenderPage`, the render-to-device-context function printing needs. Only Windows binaries, no extra dependencies. | +| `PDFiumCore` | 157.0.8100 | Apache-2.0 | Rejected. Its generated binding has no `FPDF_RenderPage` (device context) entry point, only bitmap rendering. It also pulls in the Linux and macOS PDFium packages and has no net10.0 build. | +| `Nong.PDFiumCore` (fork of PDFiumCore) | 152.0.7947.1 | Apache-2.0 declared in the package; the repository licence file could not be read (the gitcode page returned HTML) | Rejected. Same generated binding, so also no `FPDF_RenderPage`; single-maintainer fork on an older PDFium build. | + +### Libraries compiled into pdfium.dll + +| Component | Licence, as stated in its licence file | +|---|---| +| Abseil | Apache-2.0 | +| Anti-Grain Geometry 2.3 | AGG licence: copy, use, modify, sell and distribute, provided the copyright notice appears in all copies | +| Dragonbox | Apache-2.0 with LLVM Exceptions, or Boost Software License 1.0 | +| fast_float | MIT | +| FreeType | FreeType Project License (FTL) | +| HarfBuzz | "Old MIT" | +| Highway | Apache-2.0 | +| ICU | Unicode License v3 | +| Little CMS | MIT | +| libjpeg-turbo | IJG License and BSD-3-Clause (its SIMD code is zlib-licensed, subsumed by the IJG License) | +| libpng | PNG Reference Library License version 2 | +| LLVM libc | Apache-2.0 with LLVM Exceptions | +| OpenJPEG | BSD-2-Clause | +| simdutf | MIT | +| zlib | zlib licence | + +Credits these licences ask for in the documentation: + +- Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved. +- This software is based in part on the work of the Independent JPEG Group. + +ICU's licence file also quotes GPL text for its autoconf build macros (`aclocal.m4`, under the +Autoconf exception). Those are build scripts; they are not compiled into `pdfium.dll`. + +## .NET package dependencies + +| Package | Version | Licence | Why | +|---|---|---|---| +| System.Drawing.Common | 8.0.34 (net8.0-windows), 10.0.15 (net10.0-windows) | MIT | GDI+ bitmaps and Windows printing (`PrintDocument`) | +| Microsoft.Win32.SystemEvents | 8.0.0 / 10.0.15, through System.Drawing.Common | MIT | Dependency of System.Drawing.Common | + +These are ordinary NuGet dependencies, restored from nuget.org; they are listed here for completeness. + +## Redistributing pdfium.dll + +Every application built with PDFStream.NET ships `pdfium.dll` next to its program (the `bblanchon.PDFium.Win32` +dependency puts it there), and so redistributes PDFium and the libraries compiled into it. Their licences +(BSD-3-Clause, Apache-2.0 and the others listed above) require that whoever receives the binary also receives +their notices. **Any application that redistributes pdfium.dll must carry the PDFium section of these notices**: +the "PDF engine: PDFium" section above and the licence texts below from "pdfium-binaries packaging" to "zlib". +Shipping this whole file with your program is the simplest way to do that. + +## The test-print sample exe + +The `PDFStream.NET.TestPrint-win-x64` artifact that CI publishes is one self-contained exe. Besides PDFStream.NET (MIT, +see [LICENSE](LICENSE)) and `pdfium.dll` (the PDFium section above applies to it), it carries: + +| Component | Licence | Notes | +|---|---|---| +| The .NET runtime (package `Microsoft.NETCore.App.Runtime.win-x64`) | MIT | Copyright (c) .NET Foundation and Contributors; the licence text is below. The runtime's own third-party notices apply to this copy too: they are the `THIRD-PARTY-NOTICES.TXT` file in that package, also published at [github.com/dotnet/runtime](https://github.com/dotnet/runtime/blob/main/THIRD-PARTY-NOTICES.TXT). | +| System.Drawing.Common and Microsoft.Win32.SystemEvents | MIT | As listed above. | + +The sample's build and publish output put `LICENSE` and this file next to the exe. + +## Development only (not distributed) + +The test project uses xUnit.net v3 (Apache-2.0), Microsoft.NET.Test.Sdk (MIT), Microsoft Testing +Platform (MIT) and PDFsharp **6.2.4** (MIT) with its MIT-licensed dependencies. PDFsharp is pinned to +exactly 6.2.4 because PDFsharp 6.5.0 and later, including the 7.0 previews, are AGPL-3.0-only. None of +these is part of the PDFStream.NET package. + +--- + +## Licence texts + +### pdfium-binaries packaging (MIT) + +Source: `LICENSE` in the `chromium/8165` release archive. + +```text +Copyright 2014-2025 Benoit Blanchon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +This package also includes third-party software. See the licenses/ directory for their respective licenses. +``` + +### PDFium (BSD-3-Clause and Apache-2.0) + +Source: `licenses/pdfium.txt` in the `chromium/8165` release archive. + +```text +Copyright 2014 The PDFium Authors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### Abseil (Apache-2.0) + +Source: `licenses/abseil.txt` in the `chromium/8165` release archive. + +```text + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### Anti-Grain Geometry 2.3 + +Source: `licenses/agg23.txt` in the `chromium/8165` release archive. + +```text +//---------------------------------------------------------------------------- +// Anti-Grain Geometry - Version 2.3 +// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) +// +// Permission to copy, use, modify, sell and distribute this software +// is granted provided this copyright notice appears in all copies. +// This software is provided "as is" without express or implied +// warranty, and with no claim as to its suitability for any purpose. +// +//---------------------------------------------------------------------------- +// Contact: mcseem@antigrain.com +// mcseemagg@yahoo.com +// http://www.antigrain.com +//---------------------------------------------------------------------------- +``` + +### Dragonbox (Apache-2.0 with LLVM Exceptions) + +Source: `licenses/dragonbox-Apache2-LLVM.txt` in the `chromium/8165` release archive. + +```text + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. +``` + +### Dragonbox (Boost Software License 1.0) + +Source: `licenses/dragonbox-Boost.txt` in the `chromium/8165` release archive. + +```text +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +``` + +### fast_float (MIT) + +Source: `licenses/fast_float.txt` in the `chromium/8165` release archive. + +```text +MIT License + +Copyright (c) 2021 The fast_float authors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +``` + +### FreeType (FreeType Project License) + +Source: `licenses/freetype.txt` in the `chromium/8165` release archive. + +```text + The FreeType Project LICENSE + ---------------------------- + + 2006-Jan-27 + + Copyright 1996-2002, 2006 by + David Turner, Robert Wilhelm, and Werner Lemberg + + + +Introduction +============ + + The FreeType Project is distributed in several archive packages; + some of them may contain, in addition to the FreeType font engine, + various tools and contributions which rely on, or relate to, the + FreeType Project. + + This license applies to all files found in such packages, and + which do not fall under their own explicit license. The license + affects thus the FreeType font engine, the test programs, + documentation and makefiles, at the very least. + + This license was inspired by the BSD, Artistic, and IJG + (Independent JPEG Group) licenses, which all encourage inclusion + and use of free software in commercial and freeware products + alike. As a consequence, its main points are that: + + o We don't promise that this software works. However, we will be + interested in any kind of bug reports. (`as is' distribution) + + o You can use this software for whatever you want, in parts or + full form, without having to pay us. (`royalty-free' usage) + + o You may not pretend that you wrote this software. If you use + it, or only parts of it, in a program, you must acknowledge + somewhere in your documentation that you have used the + FreeType code. (`credits') + + We specifically permit and encourage the inclusion of this + software, with or without modifications, in commercial products. + We disclaim all warranties covering The FreeType Project and + assume no liability related to The FreeType Project. + + + Finally, many people asked us for a preferred form for a + credit/disclaimer to use in compliance with this license. We thus + encourage you to use the following text: + + """ + Portions of this software are copyright © The FreeType + Project (www.freetype.org). All rights reserved. + """ + + Please replace with the value from the FreeType version you + actually use. + + +Legal Terms +=========== + +0. Definitions +-------------- + + Throughout this license, the terms `package', `FreeType Project', + and `FreeType archive' refer to the set of files originally + distributed by the authors (David Turner, Robert Wilhelm, and + Werner Lemberg) as the `FreeType Project', be they named as alpha, + beta or final release. + + `You' refers to the licensee, or person using the project, where + `using' is a generic term including compiling the project's source + code as well as linking it to form a `program' or `executable'. + This program is referred to as `a program using the FreeType + engine'. + + This license applies to all files distributed in the original + FreeType Project, including all source code, binaries and + documentation, unless otherwise stated in the file in its + original, unmodified form as distributed in the original archive. + If you are unsure whether or not a particular file is covered by + this license, you must contact us to verify this. + + The FreeType Project is copyright (C) 1996-2000 by David Turner, + Robert Wilhelm, and Werner Lemberg. All rights reserved except as + specified below. + +1. No Warranty +-------------- + + THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO + USE, OF THE FREETYPE PROJECT. + +2. Redistribution +----------------- + + This license grants a worldwide, royalty-free, perpetual and + irrevocable right and license to use, execute, perform, compile, + display, copy, create derivative works of, distribute and + sublicense the FreeType Project (in both source and object code + forms) and derivative works thereof for any purpose; and to + authorize others to exercise some or all of the rights granted + herein, subject to the following conditions: + + o Redistribution of source code must retain this license file + (`FTL.TXT') unaltered; any additions, deletions or changes to + the original files must be clearly indicated in accompanying + documentation. The copyright notices of the unaltered, + original files must be preserved in all copies of source + files. + + o Redistribution in binary form must provide a disclaimer that + states that the software is based in part of the work of the + FreeType Team, in the distribution documentation. We also + encourage you to put an URL to the FreeType web page in your + documentation, though this isn't mandatory. + + These conditions apply to any software derived from or based on + the FreeType Project, not just the unmodified files. If you use + our work, you must acknowledge us. However, no fee need be paid + to us. + +3. Advertising +-------------- + + Neither the FreeType authors and contributors nor you shall use + the name of the other for commercial, advertising, or promotional + purposes without specific prior written permission. + + We suggest, but do not require, that you use one or more of the + following phrases to refer to this software in your documentation + or advertising materials: `FreeType Project', `FreeType Engine', + `FreeType library', or `FreeType Distribution'. + + As you have not signed this license, you are not required to + accept it. However, as the FreeType Project is copyrighted + material, only this license, or another one contracted with the + authors, grants you the right to use, distribute, and modify it. + Therefore, by using, distributing, or modifying the FreeType + Project, you indicate that you understand and accept all the terms + of this license. + +4. Contacts +----------- + + There are two mailing lists related to FreeType: + + o freetype@nongnu.org + + Discusses general use and applications of FreeType, as well as + future and wanted additions to the library and distribution. + If you are looking for support, start in this list if you + haven't found anything to help you in the documentation. + + o freetype-devel@nongnu.org + + Discusses bugs, as well as engine internals, design issues, + specific licenses, porting, etc. + + Our home page can be found at + + http://www.freetype.org + + +--- end of FTL.TXT --- +``` + +### HarfBuzz ("Old MIT") + +Source: `licenses/harfbuzz.txt` in the `chromium/8165` release archive. + +```text +HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. +For parts of HarfBuzz that are licensed under different licenses see individual +files names COPYING in subdirectories where applicable. + +Copyright © 2010-2022 Google, Inc. +Copyright © 2015-2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012,2015 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2011 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod +Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. +Copyright © 1998-2005 David Turner and Werner Lemberg +Copyright © 2016 Igalia S.L. +Copyright © 2022 Matthias Clasen +Copyright © 2018,2021 Khaled Hosny +Copyright © 2018,2019,2020 Adobe, Inc +Copyright © 2013-2015 Alexei Podtelezhnikov + +For full copyright notices consult the individual files in the package. + + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that the +above copyright notice and the following two paragraphs appear in +all copies of this software. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN +IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. +``` + +### Highway (Apache-2.0) + +Source: `licenses/highway.txt` in the `chromium/8165` release archive. + +```text + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + +### ICU (Unicode License v3) + +Source: `licenses/icu.txt` in the `chromium/8165` release archive. + +```text +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2016-2025 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + +---------------------------------------------------------------------- + +Third-Party Software Licenses + +This section contains third-party software notices and/or additional +terms for licensed third-party software components included within ICU +libraries. + +---------------------------------------------------------------------- + +ICU License - ICU 1.8.1 to ICU 57.1 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1995-2016 International Business Machines Corporation and others +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, provided that the above +copyright notice(s) and this permission notice appear in all copies of +the Software and that both the above copyright notice(s) and this +permission notice appear in supporting documentation. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY +SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER +RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, use +or other dealings in this Software without prior written authorization +of the copyright holder. + +All trademarks and registered trademarks mentioned herein are the +property of their respective owners. + +---------------------------------------------------------------------- + +Chinese/Japanese Word Break Dictionary Data (cjdict.txt) + + # The Google Chrome software developed by Google is licensed under + # the BSD license. Other software included in this distribution is + # provided under other licenses, as set forth below. + # + # The BSD License + # http://opensource.org/licenses/bsd-license.php + # Copyright (C) 2006-2008, Google Inc. + # + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are met: + # + # Redistributions of source code must retain the above copyright notice, + # this list of conditions and the following disclaimer. + # Redistributions in binary form must reproduce the above + # copyright notice, this list of conditions and the following + # disclaimer in the documentation and/or other materials provided with + # the distribution. + # Neither the name of Google Inc. nor the names of its + # contributors may be used to endorse or promote products derived from + # this software without specific prior written permission. + # + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + # + # + # The word list in cjdict.txt are generated by combining three word lists + # listed below with further processing for compound word breaking. The + # frequency is generated with an iterative training against Google web + # corpora. + # + # * Libtabe (Chinese) + # - https://sourceforge.net/project/?group_id=1519 + # - Its license terms and conditions are shown below. + # + # * IPADIC (Japanese) + # - http://chasen.aist-nara.ac.jp/chasen/distribution.html + # - Its license terms and conditions are shown below. + # + # ---------COPYING.libtabe ---- BEGIN-------------------- + # + # /* + # * Copyright (c) 1999 TaBE Project. + # * Copyright (c) 1999 Pai-Hsiang Hsiao. + # * All rights reserved. + # * + # * Redistribution and use in source and binary forms, with or without + # * modification, are permitted provided that the following conditions + # * are met: + # * + # * . Redistributions of source code must retain the above copyright + # * notice, this list of conditions and the following disclaimer. + # * . Redistributions in binary form must reproduce the above copyright + # * notice, this list of conditions and the following disclaimer in + # * the documentation and/or other materials provided with the + # * distribution. + # * . Neither the name of the TaBE Project nor the names of its + # * contributors may be used to endorse or promote products derived + # * from this software without specific prior written permission. + # * + # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + # * OF THE POSSIBILITY OF SUCH DAMAGE. + # */ + # + # /* + # * Copyright (c) 1999 Computer Systems and Communication Lab, + # * Institute of Information Science, Academia + # * Sinica. All rights reserved. + # * + # * Redistribution and use in source and binary forms, with or without + # * modification, are permitted provided that the following conditions + # * are met: + # * + # * . Redistributions of source code must retain the above copyright + # * notice, this list of conditions and the following disclaimer. + # * . Redistributions in binary form must reproduce the above copyright + # * notice, this list of conditions and the following disclaimer in + # * the documentation and/or other materials provided with the + # * distribution. + # * . Neither the name of the Computer Systems and Communication Lab + # * nor the names of its contributors may be used to endorse or + # * promote products derived from this software without specific + # * prior written permission. + # * + # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + # * OF THE POSSIBILITY OF SUCH DAMAGE. + # */ + # + # Copyright 1996 Chih-Hao Tsai @ Beckman Institute, + # University of Illinois + # c-tsai4@uiuc.edu http://casper.beckman.uiuc.edu/~c-tsai4 + # + # ---------------COPYING.libtabe-----END-------------------------------- + # + # + # ---------------COPYING.ipadic-----BEGIN------------------------------- + # + # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science + # and Technology. All Rights Reserved. + # + # Use, reproduction, and distribution of this software is permitted. + # Any copy of this software, whether in its original form or modified, + # must include both the above copyright notice and the following + # paragraphs. + # + # Nara Institute of Science and Technology (NAIST), + # the copyright holders, disclaims all warranties with regard to this + # software, including all implied warranties of merchantability and + # fitness, in no event shall NAIST be liable for + # any special, indirect or consequential damages or any damages + # whatsoever resulting from loss of use, data or profits, whether in an + # action of contract, negligence or other tortuous action, arising out + # of or in connection with the use or performance of this software. + # + # A large portion of the dictionary entries + # originate from ICOT Free Software. The following conditions for ICOT + # Free Software applies to the current dictionary as well. + # + # Each User may also freely distribute the Program, whether in its + # original form or modified, to any third party or parties, PROVIDED + # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear + # on, or be attached to, the Program, which is distributed substantially + # in the same form as set out herein and that such intended + # distribution, if actually made, will neither violate or otherwise + # contravene any of the laws and regulations of the countries having + # jurisdiction over the User or the intended distribution itself. + # + # NO WARRANTY + # + # The program was produced on an experimental basis in the course of the + # research and development conducted during the project and is provided + # to users as so produced on an experimental basis. Accordingly, the + # program is provided without any warranty whatsoever, whether express, + # implied, statutory or otherwise. The term "warranty" used herein + # includes, but is not limited to, any warranty of the quality, + # performance, merchantability and fitness for a particular purpose of + # the program and the nonexistence of any infringement or violation of + # any right of any third party. + # + # Each user of the program will agree and understand, and be deemed to + # have agreed and understood, that there is no warranty whatsoever for + # the program and, accordingly, the entire risk arising from or + # otherwise connected with the program is assumed by the user. + # + # Therefore, neither ICOT, the copyright holder, or any other + # organization that participated in or was otherwise related to the + # development of the program and their respective officials, directors, + # officers and other employees shall be held liable for any and all + # damages, including, without limitation, general, special, incidental + # and consequential damages, arising out of or otherwise in connection + # with the use or inability to use the program or any product, material + # or result produced or otherwise obtained by using the program, + # regardless of whether they have been advised of, or otherwise had + # knowledge of, the possibility of such damages at any time during the + # project or thereafter. Each user will be deemed to have agreed to the + # foregoing by his or her commencement of use of the program. The term + # "use" as used herein includes, but is not limited to, the use, + # modification, copying and distribution of the program and the + # production of secondary products from the program. + # + # In the case where the program, whether in its original form or + # modified, was distributed or delivered to or received by a user from + # any person, organization or entity other than ICOT, unless it makes or + # grants independently of ICOT any specific warranty to the user in + # writing, such person, organization or entity, will also be exempted + # from and not be held liable to the user for any such damages as noted + # above as far as the program is concerned. + # + # ---------------COPYING.ipadic-----END---------------------------------- + +---------------------------------------------------------------------- + +Lao Word Break Dictionary Data (laodict.txt) + + # Copyright (C) 2016 and later: Unicode, Inc. and others. + # License & terms of use: http://www.unicode.org/copyright.html + # Copyright (c) 2015 International Business Machines Corporation + # and others. All Rights Reserved. + # + # Project: https://github.com/rober42539/lao-dictionary + # Dictionary: https://github.com/rober42539/lao-dictionary/laodict.txt + # License: https://github.com/rober42539/lao-dictionary/LICENSE.txt + # (copied below) + # + # This file is derived from the above dictionary version of Nov 22, 2020 + # ---------------------------------------------------------------------- + # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell. + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are met: + # + # Redistributions of source code must retain the above copyright notice, this + # list of conditions and the following disclaimer. Redistributions in binary + # form must reproduce the above copyright notice, this list of conditions and + # the following disclaimer in the documentation and/or other materials + # provided with the distribution. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + # OF THE POSSIBILITY OF SUCH DAMAGE. + # -------------------------------------------------------------------------- + +---------------------------------------------------------------------- + +Burmese Word Break Dictionary Data (burmesedict.txt) + + # Copyright (c) 2014 International Business Machines Corporation + # and others. All Rights Reserved. + # + # This list is part of a project hosted at: + # github.com/kanyawtech/myanmar-karen-word-lists + # + # -------------------------------------------------------------------------- + # Copyright (c) 2013, LeRoy Benjamin Sharon + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions + # are met: Redistributions of source code must retain the above + # copyright notice, this list of conditions and the following + # disclaimer. Redistributions in binary form must reproduce the + # above copyright notice, this list of conditions and the following + # disclaimer in the documentation and/or other materials provided + # with the distribution. + # + # Neither the name Myanmar Karen Word Lists, nor the names of its + # contributors may be used to endorse or promote products derived + # from this software without specific prior written permission. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS + # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + # SUCH DAMAGE. + # -------------------------------------------------------------------------- + +---------------------------------------------------------------------- + +Time Zone Database + + ICU uses the public domain data and code derived from Time Zone +Database for its time zone support. The ownership of the TZ database +is explained in BCP 175: Procedure for Maintaining the Time Zone +Database section 7. + + # 7. Database Ownership + # + # The TZ database itself is not an IETF Contribution or an IETF + # document. Rather it is a pre-existing and regularly updated work + # that is in the public domain, and is intended to remain in the + # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do + # not apply to the TZ Database or contributions that individuals make + # to it. Should any claims be made and substantiated against the TZ + # Database, the organization that is providing the IANA + # Considerations defined in this RFC, under the memorandum of + # understanding with the IETF, currently ICANN, may act in accordance + # with all competent court orders. No ownership claims will be made + # by ICANN or the IETF Trust on the database or the code. Any person + # making a contribution to the database or code waives all rights to + # future claims in that contribution or in the TZ Database. + +---------------------------------------------------------------------- + +Google double-conversion + +Copyright 2006-2011, the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---------------------------------------------------------------------- + +JSON parsing library (nlohmann/json) + +File: vendor/json/upstream/single_include/nlohmann/json.hpp (only for ICU4C) + +MIT License + +Copyright (c) 2013-2022 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +---------------------------------------------------------------------- + +File: aclocal.m4 (only for ICU4C) +Section: pkg.m4 - Macros to locate and utilise pkg-config. + + +Copyright © 2004 Scott James Remnant . +Copyright © 2012-2015 Dan Nicholson + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307, USA. + +As a special exception to the GNU General Public License, if you +distribute this file as part of a program that contains a +configuration script generated by Autoconf, you may include it under +the same distribution terms that you use for the rest of that +program. + + +(The condition for the exception is fulfilled because +ICU4C includes a configuration script generated by Autoconf, +namely the `configure` script.) + +---------------------------------------------------------------------- + +File: config.guess (only for ICU4C) + + +This file is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . + +As a special exception to the GNU General Public License, if you +distribute this file as part of a program that contains a +configuration script generated by Autoconf, you may include it under +the same distribution terms that you use for the rest of that +program. This Exception is an additional permission under section 7 +of the GNU General Public License, version 3 ("GPLv3"). + + +(The condition for the exception is fulfilled because +ICU4C includes a configuration script generated by Autoconf, +namely the `configure` script.) + +---------------------------------------------------------------------- + +File: install-sh (only for ICU4C) + + +Copyright 1991 by the Massachusetts Institute of Technology + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation, and that the name of M.I.T. not be used in advertising or +publicity pertaining to distribution of the software without specific, +written prior permission. M.I.T. makes no representations about the +suitability of this software for any purpose. It is provided "as is" +without express or implied warranty. + +---------------------------------------------------------------------- + +File: sorttable.js (only for ICU4J) + +The MIT Licence, for code from kryogenix.org + +Code downloaded from the Browser Experiments section of kryogenix.org is +licenced under the so-called MIT licence. The licence is below. + +Copyright (c) 1997-date Stuart Langridge + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### Little CMS (MIT) + +Source: `licenses/lcms.txt` in the `chromium/8165` release archive. + +```text +//--------------------------------------------------------------------------------- +// +// Little Color Management System +// Copyright (c) 1998-2026 Marti Maria Saguer +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the Software +// is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +//--------------------------------------------------------------------------------- +// +// Version 2.19 +// +``` + +### libjpeg-turbo (overview: IJG and BSD-3-Clause) + +Source: `licenses/libjpeg_turbo.md` in the `chromium/8165` release archive. + +```text +libjpeg-turbo Licenses +====================== + +libjpeg-turbo is covered by two compatible BSD-style open source licenses: + +- The IJG (Independent JPEG Group) License, which is listed in + [README.ijg](README.ijg) + + This license applies to the libjpeg API library and associated programs, + including any code inherited from libjpeg and any modifications to that + code. Note that the libjpeg-turbo SIMD source code bears the + [zlib License](https://opensource.org/licenses/Zlib), but in the context of + the overall libjpeg API library, the terms of the zlib License are subsumed + by the terms of the IJG License. + +- The Modified (3-clause) BSD License, which is listed below + + This license applies to the TurboJPEG API library and associated programs, as + well as the build system. Note that the TurboJPEG API library wraps the + libjpeg API library, so in the context of the overall TurboJPEG API library, + both the terms of the IJG License and the terms of the Modified (3-clause) + BSD License apply. + + +Complying with the libjpeg-turbo Licenses +========================================= + +This section provides a roll-up of the libjpeg-turbo licensing terms, to the +best of our understanding. This is not a license in and of itself. It is +intended solely for clarification. + +1. If you are distributing a modified version of the libjpeg-turbo source, + then: + + 1. You cannot alter or remove any existing copyright or license notices + from the source. + + **Origin** + - Clause 1 of the IJG License + - Clause 1 of the Modified BSD License + - Clauses 1 and 3 of the zlib License + + 2. You must add your own copyright notice to the header of each source + file you modified, so others can tell that you modified that file. (If + there is not an existing copyright header in that file, then you can + simply add a notice stating that you modified the file.) + + **Origin** + - Clause 1 of the IJG License + - Clause 2 of the zlib License + + 3. You must include the IJG README file, and you must not alter any of the + copyright or license text in that file. + + **Origin** + - Clause 1 of the IJG License + +2. If you are distributing only libjpeg-turbo binaries without the source, or + if you are distributing an application that statically links with + libjpeg-turbo, then: + + 1. Your product documentation must include a message stating: + + This software is based in part on the work of the Independent JPEG + Group. + + **Origin** + - Clause 2 of the IJG license + + 2. If your binary distribution includes or uses the TurboJPEG API, then + your product documentation must include the text of the Modified BSD + License (see below.) + + **Origin** + - Clause 2 of the Modified BSD License + +3. You cannot use the name of the IJG or The libjpeg-turbo Project or the + contributors thereof in advertising, publicity, etc. + + **Origin** + - IJG License + - Clause 3 of the Modified BSD License + +4. The IJG and The libjpeg-turbo Project do not warrant libjpeg-turbo to be + free of defects, nor do we accept any liability for undesirable + consequences resulting from your use of the software. + + **Origin** + - IJG License + - Modified BSD License + - zlib License + + +The Modified (3-clause) BSD License +=================================== + +Copyright (C)2009-2024 D. R. Commander. All Rights Reserved.
+Copyright (C)2015 Viktor Szathmáry. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +- Neither the name of the libjpeg-turbo Project nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + +Why Two Licenses? +================= + +The zlib License could have been used instead of the Modified (3-clause) BSD +License, and since the IJG License effectively subsumes the distribution +conditions of the zlib License, this would have effectively placed +libjpeg-turbo binary distributions under the IJG License. However, the IJG +License specifically refers to the Independent JPEG Group and does not extend +attribution and endorsement protections to other entities. Thus, it was +desirable to choose a license that granted us the same protections for new code +that were granted to the IJG for code derived from their software. +``` + +### libjpeg-turbo (IJG License) + +Source: `licenses/libjpeg_turbo.ijg` in the `chromium/8165` release archive. + +```text +libjpeg-turbo note: This file has been modified by The libjpeg-turbo Project +to include only information relevant to libjpeg-turbo, to wordsmith certain +sections, and to remove impolitic language that existed in the libjpeg v8 +README. It is included only for reference. Please see README.md for +information specific to libjpeg-turbo. + + +The Independent JPEG Group's JPEG software +========================================== + +This distribution contains a release of the Independent JPEG Group's free JPEG +software. You are welcome to redistribute this software and to use it for any +purpose, subject to the conditions under LEGAL ISSUES, below. + +This software is the work of Tom Lane, Guido Vollbeding, Philip Gladstone, +Bill Allombert, Jim Boucher, Lee Crocker, Bob Friesenhahn, Ben Jackson, +Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, Ge' Weijers, +and other members of the Independent JPEG Group. + +IJG is not affiliated with the ISO/IEC JTC1/SC29/WG1 standards committee +(also known as JPEG, together with ITU-T SG16). + + +DOCUMENTATION ROADMAP +===================== + +This file contains the following sections: + +OVERVIEW General description of JPEG and the IJG software. +LEGAL ISSUES Copyright, lack of warranty, terms of distribution. +REFERENCES Where to learn more about JPEG. +ARCHIVE LOCATIONS Where to find newer versions of this software. +FILE FORMAT WARS Software *not* to get. +TO DO Plans for future IJG releases. + +Other documentation files in the distribution are: + +User documentation: + doc/usage.txt Usage instructions for cjpeg, djpeg, jpegtran, + rdjpgcom, and wrjpgcom. + doc/*.1 Unix-style man pages for programs (same info as + usage.txt). + doc/wizard.txt Advanced usage instructions for JPEG wizards only. + doc/change.log Version-to-version change highlights. +Programmer and internal documentation: + doc/libjpeg.txt How to use the JPEG library in your own programs. + src/example.c Sample code for calling the JPEG library. + doc/structure.txt Overview of the JPEG library's internal structure. + doc/coderules.txt Coding style rules --- please read if you contribute + code. + +Please read at least usage.txt. Some information can also be found in the JPEG +FAQ (Frequently Asked Questions) article. See ARCHIVE LOCATIONS below to find +out where to obtain the FAQ article. + +If you want to understand how the JPEG code works, we suggest reading one or +more of the REFERENCES, then looking at the documentation files (in roughly +the order listed) before diving into the code. + + +OVERVIEW +======== + +This package contains C software to implement JPEG image encoding, decoding, +and transcoding. JPEG (pronounced "jay-peg") is a standardized compression +method for full-color and grayscale images. JPEG's strong suit is compressing +photographic images or other types of images that have smooth color and +brightness transitions between neighboring pixels. Images with sharp lines or +other abrupt features may not compress well with JPEG, and a higher JPEG +quality may have to be used to avoid visible compression artifacts with such +images. + +JPEG is normally lossy, meaning that the output pixels are not necessarily +identical to the input pixels. However, on photographic content and other +"smooth" images, very good compression ratios can be obtained with no visible +compression artifacts, and extremely high compression ratios are possible if +you are willing to sacrifice image quality (by reducing the "quality" setting +in the compressor.) + +This software implements JPEG baseline, extended-sequential, progressive, and +lossless compression processes. Provision is made for supporting all variants +of these processes, although some uncommon parameter settings aren't +implemented yet. We have made no provision for supporting the hierarchical +processes defined in the standard. + +We provide a set of library routines for reading and writing JPEG image files, +plus two sample applications "cjpeg" and "djpeg", which use the library to +perform conversion between JPEG and some other popular image file formats. +The library is intended to be reused in other applications. + +In order to support file conversion and viewing software, we have included +considerable functionality beyond the bare JPEG coding/decoding capability; +for example, the color quantization modules are not strictly part of JPEG +decoding, but they are essential for output to colormapped file formats. These +extra functions can be compiled out of the library if not required for a +particular application. + +We have also included "jpegtran", a utility for lossless transcoding between +different JPEG processes, and "rdjpgcom" and "wrjpgcom", two simple +applications for inserting and extracting textual comments in JFIF files. + +The emphasis in designing this software has been on achieving portability and +flexibility, while also making it fast enough to be useful. In particular, +the software is not intended to be read as a tutorial on JPEG. (See the +REFERENCES section for introductory material.) Rather, it is intended to +be reliable, portable, industrial-strength code. We do not claim to have +achieved that goal in every aspect of the software, but we strive for it. + +We welcome the use of this software as a component of commercial products. +No royalty is required, but we do ask for an acknowledgement in product +documentation, as described under LEGAL ISSUES. + + +LEGAL ISSUES +============ + +In plain English: + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +REFERENCES +========== + +We recommend reading one or more of these references before trying to +understand the innards of the JPEG software. + +The best short technical introduction to the JPEG compression algorithm is + Wallace, Gregory K. "The JPEG Still Picture Compression Standard", + Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. +(Adjacent articles in that issue discuss MPEG motion picture compression, +applications of JPEG, and related topics.) If you don't have the CACM issue +handy, a PDF file containing a revised version of Wallace's article is +available at http://www.ijg.org/files/Wallace.JPEG.pdf. The file (actually +a preprint for an article that appeared in IEEE Trans. Consumer Electronics) +omits the sample images that appeared in CACM, but it includes corrections +and some added material. Note: the Wallace article is copyright ACM and IEEE, +and it may not be used for commercial purposes. + +A somewhat less technical, more leisurely introduction to JPEG can be found in +"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by +M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides +good explanations and example C code for a multitude of compression methods +including JPEG. It is an excellent source if you are comfortable reading C +code but don't know much about data compression in general. The book's JPEG +sample code is far from industrial-strength, but when you are ready to look +at a full implementation, you've got one here... + +The best currently available description of JPEG is the textbook "JPEG Still +Image Data Compression Standard" by William B. Pennebaker and Joan L. +Mitchell, published by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. +Price US$59.95, 638 pp. The book includes the complete text of the ISO JPEG +standards (DIS 10918-1 and draft DIS 10918-2). + +The original JPEG standard is divided into two parts, Part 1 being the actual +specification, while Part 2 covers compliance testing methods. Part 1 is +titled "Digital Compression and Coding of Continuous-tone Still Images, +Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS +10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of +Continuous-tone Still Images, Part 2: Compliance testing" and has document +numbers ISO/IEC IS 10918-2, ITU-T T.83. + +The JPEG standard does not specify all details of an interchangeable file +format. For the omitted details, we follow the "JFIF" conventions, revision +1.02. JFIF version 1 has been adopted as ISO/IEC 10918-5 (05/2013) and +Recommendation ITU-T T.871 (05/2011): Information technology - Digital +compression and coding of continuous-tone still images: JPEG File Interchange +Format (JFIF). It is available as a free download in PDF file format from +https://www.iso.org/standard/54989.html and http://www.itu.int/rec/T-REC-T.871. +A PDF file of the older JFIF 1.02 specification is available at +http://www.w3.org/Graphics/JPEG/jfif3.pdf. + +The TIFF 6.0 file format specification can be obtained from +http://mirrors.ctan.org/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation +scheme found in the TIFF 6.0 spec of 3-June-92 has a number of serious +problems. IJG does not recommend use of the TIFF 6.0 design (TIFF Compression +tag 6). Instead, we recommend the JPEG design proposed by TIFF Technical Note +#2 (Compression tag 7). Copies of this Note can be obtained from +http://www.ijg.org/files/. It is expected that the next revision +of the TIFF spec will replace the 6.0 JPEG design with the Note's design. +Although IJG's own code does not support TIFF/JPEG, the free libtiff library +uses our library to implement TIFF/JPEG per the Note. + + +ARCHIVE LOCATIONS +================= + +The "official" archive site for this software is www.ijg.org. +The most recent released version can always be found there in +directory "files". + +The JPEG FAQ (Frequently Asked Questions) article is a source of some +general information about JPEG. It is available at +http://www.faqs.org/faqs/jpeg-faq. + + +FILE FORMAT COMPATIBILITY +========================= + +This software implements ITU T.81 | ISO/IEC 10918 with some extensions from +ITU T.871 | ISO/IEC 10918-5 (JPEG File Interchange Format-- see REFERENCES). +Informally, the term "JPEG image" or "JPEG file" most often refers to JFIF or +a subset thereof, but there are other formats containing the name "JPEG" that +are incompatible with the original JPEG standard or with JFIF (for instance, +JPEG 2000 and JPEG XR). This software therefore does not support these +formats. Indeed, one of the original reasons for developing this free software +was to help force convergence on a common, interoperable format standard for +JPEG files. + +JFIF is a minimal or "low end" representation. TIFF/JPEG (TIFF revision 6.0 as +modified by TIFF Technical Note #2) can be used for "high end" applications +that need to record a lot of additional data about an image. + + +TO DO +===== + +Please send bug reports, offers of help, etc. to jpeg-info@jpegclub.org. +``` + +### OpenJPEG (BSD-2-Clause) + +Source: `licenses/libopenjpeg.txt` in the `chromium/8165` release archive. + +```text +/* + * The copyright in this software is being made available under the 2-clauses + * BSD License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such rights + * are granted under this license. + * + * Copyright (c) 2005, Herve Drolon, FreeImage Team + * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR + * Copyright (c) 2012, CS Systemes d'Information, France + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +``` + +### libpng (PNG Reference Library License version 2) + +Source: `licenses/libpng.txt` in the `chromium/8165` release archive. + +```text +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE +========================================= + +PNG Reference Library License version 2 +--------------------------------------- + + * Copyright (c) 1995-2026 The PNG Reference Library Authors. + * Copyright (c) 2018-2026 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +The software is supplied "as is", without warranty of any kind, +express or implied, including, without limitation, the warranties +of merchantability, fitness for a particular purpose, title, and +non-infringement. In no event shall the Copyright owners, or +anyone distributing the software, be liable for any damages or +other liability, whether in contract, tort or otherwise, arising +from, out of, or in connection with the software, or the use or +other dealings in the software, even if advised of the possibility +of such damage. + +Permission is hereby granted to use, copy, modify, and distribute +this software, or portions hereof, for any purpose, without fee, +subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the product + documentation would be appreciated, but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + + +PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) +----------------------------------------------------------------------- + +libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are +Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are +derived from libpng-1.0.6, and are distributed according to the same +disclaimer and license as libpng-1.0.6 with the following individuals +added to the list of Contributing Authors: + + Simon-Pierre Cadieux + Eric S. Raymond + Mans Rullgard + Cosmin Truta + Gilles Vollant + James Yu + Mandar Sahastrabuddhe + Google Inc. + Vadim Barkov + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of + the library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is + with the user. + +Some files in the "contrib" directory and some configure-generated +files that are distributed with libpng have other copyright owners, and +are released under other open source licenses. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from +libpng-0.96, and are distributed according to the same disclaimer and +license as libpng-0.96, with the following individuals added to the +list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, +and are distributed according to the same disclaimer and license as +libpng-0.88, with the following individuals added to the list of +Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +Some files in the "scripts" directory have other copyright owners, +but are released under this license. + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing +Authors and Group 42, Inc. disclaim all warranties, expressed or +implied, including, without limitation, the warranties of +merchantability and of fitness for any purpose. The Contributing +Authors and Group 42, Inc. assume no liability for direct, indirect, +incidental, special, exemplary, or consequential damages, which may +result from the use of the PNG Reference Library, even if advised of +the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, +without fee, and encourage the use of this source code as a component +to supporting the PNG file format in commercial products. If you use +this source code in a product, acknowledgment is not required but would +be appreciated. +``` + +### LLVM libc (Apache-2.0 with LLVM Exceptions) + +Source: `licenses/llvm-libc.txt` in the `chromium/8165` release archive. + +```text +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2007-2019 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. +``` + +### simdutf (MIT) + +Source: `licenses/simdutf.txt` in the `chromium/8165` release archive. + +```text +Copyright 2021 The simdutf authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +### zlib (zlib licence) + +Source: `licenses/zlib.txt` in the `chromium/8165` release archive. + +```text +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.3.2.1, February xxth, 2026 + + Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 at https://datatracker.ietf.org/doc/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ +``` + +### .NET runtime, System.Drawing.Common and Microsoft.Win32.SystemEvents (MIT) + +Source: `LICENSE.TXT` in the System.Drawing.Common package; the `LICENSE.TXT` in the +`Microsoft.NETCore.App.Runtime.win-x64` package (the .NET runtime in the self-contained test-print sample) is the +same licence text (the two files differ only in line endings). + +```text +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/docs/design/pdfstream-v1-design.md b/docs/design/pdfstream-v1-design.md new file mode 100644 index 0000000..5242b0a --- /dev/null +++ b/docs/design/pdfstream-v1-design.md @@ -0,0 +1,272 @@ +# PDFStream.NET v1: design + +Date: 2026-11-20. Status: the design the first release (the release candidate 1.0.0-rc.1, then the stable 1.0.0) is +built to; "v1" in this document and in its file name means that first release. Owner: P4 Software. + +## Intent and why + +PDFStream.NET is a free, open-source .NET library that prints a PDF, silently, to a Windows printer. +Commercial libraries do this today, but they cost money, often depend on licence keys, or need Adobe +Reader installed. We needed it for our own warehouse software, and decided to build it and give it +away. The first real user is our warehouse software's print service, a Windows service that prints +packing slips and bills of lading to printers at customer sites; every other .NET developer who prints +PDFs from a service or server is the audience. + +## Goals + +1. **Print a PDF silently** to any printer Windows can see (physical or virtual), from a file path, + a stream or a byte array. No dialogs, no Adobe, no licence key, no watermark. +2. **Work where servers work**: inside Windows services, scheduled tasks and IIS app pools + (subject to the printer being visible to that account, which the docs must explain). +3. **Print options**: page ranges, copies, duplex, colour or black and white, scaling to fit, + paper source. +4. **Password-protected PDFs.** +5. **Failures come back as a result, never an unexpected exception**, with a status and a plain + language message that says what happened and what to do next. +6. **Serve the first user**: the warehouse print service switches to PDFStream.NET by changing its single + print call. This is the acceptance test (see below). +7. Ships as the NuGet package `PDFStream.NET` with the PDF engine inside it. + +## Non-goals (not in v1) + +- PDF viewer or editor components. +- Linux, macOS or any non-Windows printing (printing goes through the Windows print system). +- Printing through Adobe Reader. +- Printing several documents as one print job. +- Output-tray selection. +- A hosted service, a paid edition, licence keys or telemetry. + +## Anti-goals (a failure even if it technically works) + +- Any watermark, nag, trial period, expiry or licence key. +- Needing Adobe Reader or any other install on the machine. +- A copyleft or non-redistributable dependency (it would bind every user). +- Network calls or data collection of any kind. +- Reporting success when the printout is blank or wrong. "Printed" must mean pages were really + rendered and sent. + +## Constraints + +- **Licence: MIT.** All dependencies must be permissive (MIT, BSD, Apache-2.0) + and redistributable. Apache-2.0 dependencies (PDFium) require a third-party notices file shipped + with the package. +- **Engine: PDFium.** MuPDF is rejected because its AGPL licence would force copyleft on everyone. +- Windows only. Targets: `net8.0-windows` and `net10.0-windows` (net10 is what the first user + runs; net8 is the long-term-support release many developers are still on). +- Native binaries for win-x64, win-x86 and win-arm64 (x86 matters because older deployments still + run 32-bit programs). +- Public repository: every commit authored by P4 Software, no secrets, no code copied from any vendor + or from private applications. +- Everything a person is meant to run (the test-print sample, see below) works by double-click, + reads a commented `settings.json` next to it, explains every message in plain language and never + closes before the result can be read. + +## Approaches considered + +**A. PDFium engine, printing through the Windows print system (chosen).** +Render each PDF page with PDFium straight onto the printer's page (vector quality, small spool +files), through `System.Drawing.Printing.PrintDocument`. PDFium is the renderer inside Chrome: +fast, accurate, permissively licensed. Trade-off: we ship and test native binaries ourselves. + +**B. Windows' built-in WinRT PDF renderer.** Nothing native to ship, but it needs Windows 10 or +newer and is unreliable in services and scheduled tasks, which is the main use case. Rejected. + +**C. MuPDF or another commercial/AGPL engine.** Excellent quality, but licence terms make it +unusable for a free MIT library. Rejected. + +Inside A there are two sub-decisions: + +- **How to call PDFium.** Options: an existing .NET binding (PDFiumCore is Apache-2.0 and + netstandard2.1, with a fork that adds net10), or our own thin wrapper over prebuilt PDFium + binaries. An internal interface sits in front of the engine (in the code: `IPdfEngine` and + `IPdfDocument`), so the binding can be swapped without touching the public API. The binding is + chosen after verifying each candidate's licence file and net10 behaviour (the comparison and the + outcome are in THIRD-PARTY-NOTICES.md). +- **How to put pixels on paper.** Render directly onto the printer's device context with PDFium's + printing flag; if a driver refuses, fall back to rendering a bitmap at the printer's resolution. + Both paths must be tested against real printers. + +## Public API (design sketch; the code has the final names) + +```csharp +namespace PDFStream.NET; + +public static class PdfPrinter +{ + public static PrintResult Print(string path, PrintOptions options); + public static PrintResult Print(Stream pdf, PrintOptions options); + public static PrintResult Print(byte[] pdf, PrintOptions options); +} + +public sealed class PrintOptions +{ + public string PrinterName { get; init; } // required + public string DocumentName { get; init; } // shown in the print queue + public string Password { get; init; } // for protected PDFs + public string Pages { get; init; } // e.g. "1-5, 8, 10-12"; empty = all + public int Copies { get; init; } = 1; + public DuplexMode Duplex { get; init; } // printer default / none / long edge / short edge + public bool? Color { get; init; } // null = printer default; true / false force it + public ScaleMode Scale { get; init; } // fit / actual size + public string PaperSource { get; init; } +} + +public sealed class PrintResult +{ + public bool Succeeded { get; } + public PrintStatus Status { get; } // enum, one value per failure reason + public string Message { get; } // plain language: what happened, what to do next + public int PagesPrinted { get; } +} +``` + +`PrintStatus` covers at least: OK, file not found, not a valid PDF, password required, wrong +password, printer not found, printer could not be opened or its settings are invalid, invalid page +range, page does not exist, cancelled, unknown error. The first real user already turns each printing +outcome into a message for its operators; those are the same reasons, so with `PrintStatus` its +mapping is a table lookup. + +## v1 scope and release order + +- **1.0**: everything in Goals above, the test-print sample, docs, CI. The first NuGet release is the release + candidate 1.0.0-rc.1; the stable 1.0.0 follows once the remaining manual release checklist rows are verified. +- **After 1.0**: PDF to image (PNG, JPG, multi-page TIFF) reusing the same engine. Kept out of 1.0 so the + first release is small and proven on printers; the public README says it is planned after 1.0. + +No compatibility layer for other PDF libraries' APIs in v1: the first user has a single print call, +which is simpler to change directly. + +## Repository layout + +``` +src/PDFStream.NET/ the library +tests/PDFStream.NET.Tests/ unit and integration tests +samples/PDFStream.NET.TestPrint double-click sample: lists printers, prints a chosen PDF +docs/ usage guide, printing from services and IIS, troubleshooting +docs/design/ this design +.github/workflows/ CI: build and test on windows-latest, pack NuGet +LICENSE README.md CHANGELOG.md THIRD-PARTY-NOTICES.md CONTRIBUTING.md +``` + +## Acceptance tests + +1. **Real print, verified.** Print a multi-page PDF to *Microsoft Print to PDF* and confirm the + output has the right page count and is not blank (count non-white pixels; do not trust the + status alone). +2. Page ranges, copies, duplex and colour options reach the printer settings. +3. Password-protected PDF: right password prints; wrong or missing password returns the right status. +4. Bad input (missing file, garbage bytes, unknown printer) returns a status and message, never throws. +5. Runs from a Windows service and from a scheduled task under a normal service account. +6. x64, x86 and arm64 packages load and print. +7. **First-user switch**: the warehouse print service's single print call is changed to PDFStream.NET + and, on one real PC, packing slips and bills of lading print correctly and look the same as + before. Done only when the printouts have been checked on paper by eye. +8. The package contains no keys, no telemetry, and the licence file and third-party notices. + +## What the first user needs + +- **Call shape today.** One call per document: the PDF as a byte array, a printer name, an empty + password and a document name. It sets no paper size, orientation, margins, tray, duplex or copies, + so the printer's own defaults apply. PDFStream.NET's defaults must therefore be: printer defaults for + everything (colour included: `Color` stays `null`, which leaves the printer's own colour setting, + unless the caller sets it), and the page scaled to fit the printable area and rotated to match the paper + (the safest match for packing slips and bills of lading; acceptance test 7 is judged by eye against + the old output). +- **Hosting.** A Windows service at customer sites, printing to the document printers there, so + acceptance test 5 (service account) is the real deployment, not an edge case. Label printing is + out of scope. +- **Printer names.** Accept exactly the names Windows returns for installed printers, including + network names such as `\\server\printer`. +- **Status messages.** The service turns each printing outcome into a message for its operators; + with `PrintStatus` that becomes a one-to-one table lookup. + +## Design decisions + +- **Concurrency.** PDFium is not thread-safe, so the library takes a process-wide lock around every + engine call. Calls from several threads are safe. The lock is held for one engine call (opening the + PDF, measuring or drawing one page, closing it), not for a whole job, so concurrent jobs run side by + side and interleave at page level; each stays its own print job. The one exception is the first form page + of a document: its engine call finds and copies every planned form page, so it is longer (about 77 ms on x64 + and 95 ms on x86 for 500 form pages, measured in review), holds the lock throughout and cannot be + interrupted. Documented. +- **Cancellation.** Every overload takes an optional `CancellationToken`. `Cancelled` means the + token fired or the job was cancelled before it was sent. `PagesPrinted`: after a cancellation that + ended the job normally it is the exact number of pages sent, and those pages print; after any failure it + is 0, because an aborted job may have been withdrawn from the queue and the pages drawn before the + failure normally never come out. The token is checked between pages, so it cannot interrupt the first form + page's longer engine call either. +- **Printer state before printing.** A job is refused with + `PrinterUnavailable` and a message naming the cause only when the queue is paused, set to "Use Printer + Offline", not available, being deleted, or cannot be opened (a stopped Print Spooler included). An + "Offline" status alone is not refused: network printers often report it through SNMP while they print + normally. A printer that really is switched off therefore queues the job until it comes back. +- **Printing to a file without a dialog.** *Microsoft Print to PDF* shows a Save As dialog unless + told where to write. `PrintOptions` gets an optional `OutputFile` (print to file). This is also a + useful feature and what the tests use to run unattended. +- **Hardware and CI.** x64 build, tests and a real print to PDF run in CI on `windows-latest` if + the runner has the driver; if it does not, those tests move to a manual checklist. x86, arm64, + Windows-service and scheduled-task checks are a manual checklist run on real machines before each + release, and the release notes say which were run. We do not claim what was not verified. +- **Owner permission flags** (a PDF that says "printing not allowed"): ignored in v1, which matches + what the commercial libraries do and what server automation expects; documented clearly. +- **Form fields.** PDFium's page-drawing calls never draw form fields, so pages with fields are flattened + before they are drawn, inside PDFStream.NET's private in-memory copy of the PDF. Flattening a page in place is + wrong when the page inherits its /Resources: `FPDFPage_Flatten` creates an empty /Resources on the page, which + hides the inherited fonts, images and XObjects. So the pages with fields among the pages a print job draws are + copied to the end of the document first, in one `FPDF_ImportPagesByIndex` call with the document as source and + destination (the import writes each page's inherited Resources, MediaBox, CropBox and Rotate onto its copy), + and the fields are flattened into the copies, which are drawn in place of the pages. One call, not one per + page: every call clones everything a page can reach, so one call per page multiplied a shared resource + dictionary by the number of form pages (40 pages sharing 8 MB of images grew memory by about 290 MB, and a + 500-page job in a 32-bit process did not finish), while one call clones what the pages share once (14 to + 17 MB for the same 40 pages). The copy is made at most once per document, and only for a PDF of at most 64 MB + (the copy budget: PDFium does not report what the copy costs, so the file size stands in for it). A copy is + used only if it carries as many annotations as its page (the import drops a whole /Annots array when one + entry is a damaged reference, and the pixel check cannot see fields) and draws exactly the same pixels as the + page in a low-resolution comparison. The comparison catches what depends on object identity: the copies' OCG + objects are new, so a layer the catalog switches off would show. It does not fully catch copies that share + one content array (see the known limitation below). Every copy that is missing or cannot be used falls + back to flattening into the page itself: the fields print, and a page that inherits its /Resources loses them + as it did before the copy existed (the documented limitation). Only when that fails too is the page drawn as + it is. `FPDF_FFLDraw` was not used because it draws only into a bitmap, so the device-context path would no + longer be vector. `FPDF_ImportPagesByIndex` is marked experimental in `fpdf_ppo.h` and verified only with the + bundled 160.0.8165. Costs and gaps: the pages to print are read once more to find the fields, and each form + page is drawn twice at low resolution for the comparison; a value a page inherits inline rather than as a + separate object is cloned onto every copy, which the budget does not bound (in a test, a deliberately + inflated inline dictionary grew memory by about 600 MB for 100 form pages); XFA-only forms are not supported + (the bundled PDFium has no XFA). **Known limitation (shared /Contents array).** When three or more form + pages share one indirect /Contents array and one indirect /Resources dictionary, later pages can also show the + fields of earlier pages, with status Ok (page 3 shows page 2's field; page 4 shows those of pages 2 and 3). The + single import call makes the copies share the cloned content array, and `FPDFPage_Flatten` edits that array in + place, naming its drawing after the first free `/FFTn` of the shared `/XObject` dictionary. The comparison + catches the first contaminated copy (page 2), but the in-place fallback then flattens the original, shared + array, so page 3's original and copy differ as well and page 3 also goes in place and keeps page 2's drawing. + It was accepted as documented: a real fix needs private objects per copy (one import call per page), which + brings back the memory growth of the one-call design, and PDFium has no API to unshare the array. A + characterization test (`Known_limitation_...` in `FormFieldRenderingTests`) pins the behaviour; a fix must + update the test and the user docs. Candidate fixes for 1.0: detect shared /Contents by comparing copy renders + after each flatten, or an import-per-page mode when the budget allows. If reloading the flattened page or copy + fails after a flatten, the unflattened page is drawn with blank form fields and status Ok; this is accepted + because the same page index loaded moments earlier. +- **Publishing.** CI builds and packs the NuGet package; publishing a release is a manual step by a + maintainer with the project's NuGet account. Copyright holder is P4 Software. + +## Chosen during implementation + +- Choice of PDFium binding, after checking each candidate's licence and net10 support. +- Exact public type and member names; internal structure; test framework. +- Details of the print path (device-context rendering vs bitmap fallback) and which drivers need + the fallback. +- The wording of messages (plain language, English now; Spanish later is welcome). +- CI and NuGet publishing mechanics. + +## Open questions + +1. **Funding and sustainability** of the project (open since 2026-11-20; does not block 1.0). +2. **NuGet package ID**: decided on 2026-11-21: the package is `PDFStream.NET` (capital NET, like the owner's + SheetStream.NET; the owner's final decision), the only name shown on nuget.org; the assembly (`PDFStream.NET.dll`) + and the C# namespace (`PDFStream.NET`) carry the same name, before any user depends on the library. NuGet looks + package IDs up without regard to case but keeps the capitalisation of the first publish for good, which is why + the spelling is fixed before the first release. Checked on 2026-11-21: nuget.org has no package with this ID (its + package content API, which takes the ID in lowercase, answered 404 Not Found for `pdfstream.net`), so it is free + until someone publishes one. (Plain `PDFStream` was also free on 2026-11-20, but it is no longer the chosen ID.) diff --git a/docs/release-checklist.md b/docs/release-checklist.md new file mode 100644 index 0000000..fa1c4cf --- /dev/null +++ b/docs/release-checklist.md @@ -0,0 +1,95 @@ +# PDFStream.NET release checklist + +Run these checks before each release. Rows marked "Not run" have not been done: nothing here counts as +verified until someone has run it, written the machine, the date, the result and their initials in the row, +and (for a failure) opened an issue. Never change a result to Pass from memory. + +How to read the result column: **Pass**, **Fail** (write what happened), **Not run**. + +## 1. Automated checks (run by the test suite) + +The real-print acceptance tests print through *Microsoft Print to PDF* into a temporary file, re-open the +produced PDF with the library's own engine and check the page count and that no page is blank. Run them with: + +``` +dotnet test --project tests/PDFStream.NET.Tests --filter-trait "Category=RealPrinter" +dotnet test --project tests/PDFStream.NET.Tests --filter-trait "Category=RealPrinter" -f net10.0-windows --arch x86 +``` + +A machine without the printer skips them and says why. They do not replace the manual checks in section 2: +Print to PDF has no paper, no tray, no duplex unit and no queue that can go offline. + +| Check | Machine | Date | Result | Initials | +| --- | --- | --- | --- | --- | +| Real-print tests, x64 host, net10.0-windows | Windows 11 x64 developer workstation | 2026-11-21 | Pass (8 of 8), including the vector-path and form-field checks, in the full net10.0-windows suite (475 of 475, Release, none skipped) on the code with that day's form-printing changes | | +| Real-print tests, x86 (32-bit) host, net10.0-windows | Windows 11 x64 developer workstation | 2026-11-21 | Pass (8 of 8), including the vector-path and form-field checks, in the full suite with `--arch x86 --framework net10.0-windows` (475 of 475, Release, none skipped) on the code with that day's form-printing changes; an earlier run that day failed one test (`Copies_two_produces_doubled_pages`: Print to PDF had not finished writing the file after 30 seconds; the wait is now 120 seconds) | | +| Real-print tests, x64 host, net8.0-windows | Windows 11 x64 developer workstation | 2026-11-21 | Pass (8 of 8), in the full net8.0-windows suite (450 of 450, Release, none skipped) on the code with that day's form-printing changes | | +| Real-print tests, x86 (32-bit) host, net8.0-windows | Windows 11 x64 developer workstation | 2026-11-21 | Pass (8 of 8), in the full suite with `--arch x86 --framework net8.0-windows` (450 of 450, Release, none skipped) on the code with that day's form-printing changes | | + +What the automated tests cover: three pages in, three pages out and none blank; five pages of mixed sizes and +orientations; a page range; two software copies (Print to PDF reports a maximum of 1 copy); a password-protected +PDF with the right password; a wrong password returning PasswordInvalid and writing no file; a filled-in form +(a text field and a ticked checkbox) whose fields come out inked; and that Print to PDF received the pages as +drawing commands on the device context (vector path), not as bitmaps. + +Known behaviour found while writing them: when the print call returns, *Microsoft Print to PDF* may not have +finished writing the output file yet (a read straight afterwards failed with "file in use" in the 32-bit +host). The tests wait for the file to be complete. A program that opens the output file right after printing +must do the same. + +## 2. Manual checks + +Each check needs real hardware or a real Windows setup that the test suite cannot reproduce. + +### 2.1 Processor architectures + +Print a multi-page PDF with the sample or your own program built for each architecture and look at the paper +(or the produced file): all pages, right orientation, nothing cut off. + +| Check | Machine | Date | Result | Initials | +| --- | --- | --- | --- | --- | +| Print on x86 (32-bit) Windows or a 32-bit process on a physical printer | | | Not run | | +| Print on arm64 Windows (a real arm64 PC, not an emulator of x64) | | | Not run | | + +### 2.2 Where the program runs + +| Check | Machine | Date | Result | Initials | +| --- | --- | --- | --- | --- | +| Run from a Windows service under a normal service account (not LocalSystem, not an administrator), printing to a printer that account can use | | | Not run | | +| Run from a Task Scheduler task ("Run whether user is logged on or not") | | | Not run | | +| Run from an IIS application pool: an ASP.NET Core app printing to a printer visible to the app pool identity | | | Not run | | + +### 2.3 Printers and paper + +| Check | Machine | Date | Result | Initials | +| --- | --- | --- | --- | --- | +| A physical printer: a multi-page PDF comes out complete, correctly scaled and in the right orientation | | | Not run | | +| A physical duplex printer: `DuplexMode.LongEdge` and `DuplexMode.ShortEdge` give the right binding edge on a 4-page PDF | | | Not run | | +| A 5-page PDF with mixed sizes and orientations (A4 portrait and Letter landscape alternating): every page fits the sheet, landscape pages are turned, nothing is cut off | | | Not run | | +| A network printer that Windows lists as Offline (the status comes from SNMP) but that is on and reachable still prints | | | Not run | | +| Duplex with software copies (`Copies` above what the driver supports) and a PDF with an odd page count: the copies are collated | | | Not run | | + +Known limitation for the duplex row: with software copies and an odd page count, the next copy starts on +the back of the last sheet of the previous copy. Record in the row that this was seen, and do not mark the +check as Fail for it. + +### 2.4 Printer problems return a result, never an exception + +Each of these must return `PrintStatus.PrinterUnavailable` with the matching plain-language message and must +not throw or hang. + +| Check | Machine | Date | Result | Initials | +| --- | --- | --- | --- | --- | +| A paused print queue: the message says the printer is paused and to resume it | | | Not run | | +| The Print Spooler service stopped: the message says the Print Spooler is not running and to start it | | | Not run | | + +## 3. Vector path on other drivers + +The automated test confirms that *Microsoft Print to PDF* gets vector drawing commands and not the bitmap +fallback. The page painter has no public or internal switch that reports which path was used, and none was +added. For a physical printer this can only be judged from the size of the spool file and the print quality +of small text and barcodes. + +| Check | Machine | Date | Result | Initials | +| --- | --- | --- | --- | --- | +| Physical printer: small text and barcodes are sharp, and the spool file is small (vector path, not a large picture per page) | | | Not run | | diff --git a/docs/services-and-iis.md b/docs/services-and-iis.md new file mode 100644 index 0000000..4883bbe --- /dev/null +++ b/docs/services-and-iis.md @@ -0,0 +1,102 @@ +# Printing from Windows services, scheduled tasks and IIS + +PDFStream.NET is built for programs that print with nobody at the screen: a Windows service, a scheduled task, +a web application in IIS. It never shows a dialog and never waits for a person. This page explains what such +a program needs from Windows. + +**Status: not yet verified.** Running from a Windows service, from a scheduled task and from IIS are on the +[release checklist](release-checklist.md) and have not been run yet. Microsoft's documentation also states +that the `System.Drawing.Printing` classes, which PDFStream.NET prints through, are not supported in a Windows +service or an ASP.NET application. PDFStream.NET turns every failure into a result with a message instead of an +exception, but until those checklist rows are run, test printing under your real account and printer before +you rely on it. + +**Untrusted PDFs.** PDFium runs inside your service without a sandbox, so a malformed or hostile PDF that +crashes it ends the whole service process, which .NET cannot catch; print PDFs you do not trust in a separate +worker process (see [Security and limits](usage.md#security-and-limits)). + +## The account must see the printer + +A program prints as the account it runs under, and it can only use the printers that account can see. That +is the most common reason a service gets `PrinterNotFound` for a printer that is plainly installed. + +- **Printers installed on the machine** (a local USB printer, or a network printer added with a Standard + TCP/IP port, by an administrator) are visible to every account, services included. This is the most + reliable set-up for a service. +- **Per-user printer connections** are not visible to a service. A connection to a shared printer + (`\\server\printer`) added from a user's own session, through "Add a printer" or by double-clicking the + share, belongs to that user only. A service, a scheduled task running as another account, and an IIS app pool + do not see it, even on the same machine. +- **Machine-wide connections** to a shared printer can be added by an administrator, for example with + `rundll32 printui.dll,PrintUIEntry /ga /n"\\server\printer"`, after which the Print Spooler service must be + restarted; or through Group Policy (Deployed Printers, "per computer"). Every account then sees the printer. +- **Permission to print.** The account also needs the Print permission on the printer (Printer properties, + Security tab) and, for a shared printer, on the print server's share. +- **Which identity reaches the network.** `LocalSystem` and `NetworkService` reach a print server as the + computer account (`DOMAIN\COMPUTERNAME$`), so that account needs permission on the server's printer. + `LocalService` reaches the network anonymously and normally cannot use a shared printer at all. A normal + domain user account used as the service account reaches the network as itself. + +Give the printer name exactly as Windows lists it for that account; network names look like +`\\server\printer`. To see what the account sees, run the test-print sample as that account (for example +with "Run as different user"), or log `PrinterSettings.InstalledPrinters` from the service itself. + +## Windows services + +- Run the service under an account that can see and use the printer (see above). A dedicated, normal (not + administrator) account is the safest choice and the one the release checklist tests. +- Set `PrinterName` on every call: a service has no default printer of its own. +- Never print to a print-to-file printer (such as *Microsoft Print to PDF*) without `OutputFile`. Without it, + the printer asks where to save the file, and a service has no screen to ask on, so the job cannot finish + normally: it may be cancelled or it may wait. (This case has not been tried in a service.) +- Use full paths for `OutputFile` and for PDF files. A service's current folder is usually + `C:\Windows\System32`, and mapped drive letters belong to user sessions, not to services. +- Keep the message. `PrintResult.Message` says what to fix in words the person reading the log understands: + write it to the log or the event log as it is. + +## Scheduled tasks + +A task set to "Run whether user is logged on or not" behaves like a service: it runs as its account without a +screen, so everything above applies. A task set to "Run only when user is logged on" runs in that user's +session and sees that user's printers, including per-user connections. + +## IIS + +A web application prints as its application pool's identity. + +- The default identity, `ApplicationPoolIdentity`, is a virtual account named `IIS AppPool\`. It + sees the printers installed on the machine (and machine-wide connections), not anyone's per-user + connections. To give it permission on a printer, add `IIS AppPool\` on the printer's Security tab. + On the network it acts as the computer account, as described above. +- Alternatively, run the pool as a dedicated domain account that has permission on the printer. +- Printing takes seconds, not milliseconds. Do not print inside the request if you can avoid it: put the job in + a queue and print from a background worker, so a slow or stuck printer never holds up a web request. + +## 32-bit and 64-bit + +The program must load the `pdfium.dll` built for the processor mode it runs in. The `PDFStream.NET` package brings all three +(x64, x86 and Arm64) and your build places the right one: + +- **A build or publish for one runtime identifier** (for example `-r win-x64` or `-r win-x86`) puts that + architecture's `pdfium.dll` next to your program. Make sure it matches how the program really runs: an IIS + pool with "Enable 32-Bit Applications" set to True runs a 32-bit process and needs the x86 copy. +- **A build without a runtime identifier** puts all three under `runtimes\win-x64`, `runtimes\win-x86` and + `runtimes\win-arm64`, and .NET loads the right one when the program starts. Copy the whole output folder, + including `runtimes` and the `.deps.json` file, when you deploy. + +If the copy is missing, every print returns `UnknownError` with details that mention `pdfium`. + +## Several jobs at once + +A service or web application often prints from several threads. That is safe. PDFium, the engine that reads +and draws PDFs, is not thread-safe, so PDFStream.NET makes every call into it under one lock for the whole +process. The lock is held for one engine call at a time (opening a PDF, drawing one page, closing it), not for +a whole job, so jobs that run at the same time interleave at page level: each is still its own print job with +its pages in order, but each takes longer than it would alone. If timing matters, print from one queue. + +## "Printing not allowed" PDFs + +Owner permissions inside a PDF, such as "printing not allowed", are ignored: such a PDF prints like any other. +That is what server automation expects (a service printing a supplier's packing slip cannot ask anyone to lift +a restriction). Only an open password stops PDFStream.NET from +reading a PDF, and you supply that in `PrintOptions.Password`. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..b631137 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,272 @@ +# Troubleshooting + +Find the message you got below; each section says what it means and what to check. The messages are the +exact texts PDFStream.NET returns in `PrintResult.Message` (text in angle brackets is filled in for the actual +job). Problems that come with no error at all are at the end, starting with +[It says printed but nothing came out](#it-says-printed-but-nothing-came-out). + +## Problems with the PDF + +### "The PDF file could not be found or read." + +> The PDF file could not be found or read. Check that the file path is correct and that this account is allowed to open the file. + +Status `FileNotFound`. The path is blank, wrong, points at a folder, or the account running the program may +not read the file, or another program holds it locked. In a Windows service, remember that a relative path is +taken from the service's current folder (usually `C:\Windows\System32`), and that mapped drive letters +such as `Z:` belong to a user session: use a full local path or a UNC path (`\\server\share\file.pdf`) +that the service account can read. + +### "The file is not a valid PDF, or it is damaged and cannot be opened." + +> The file is not a valid PDF, or it is damaged and cannot be opened. Check that the file is a complete PDF and try opening it in a PDF viewer. + +Status `InvalidPdf`. The bytes are not a PDF (an HTML error page saved as .pdf is a common case), the file +is cut short, the stream or byte array was empty, or the PDF has no pages. If you pass a stream, check that it +is positioned at the start of the PDF: it is read from its current position. + +### "The PDF is protected with a password and none was given." + +> The PDF is protected with a password and none was given. Enter the password in the print options and try again. + +Status `PasswordRequired`. Set `PrintOptions.Password` to the PDF's open password. + +### "The password given for the PDF is not correct." + +> The password given for the PDF is not correct. Check the password and try again. + +Status `PasswordInvalid`. The PDF needs an open password and the one given is wrong. (A PDF protected only by +an owner password prints whatever password you pass, so this message always means the open password.) + +## Problems with the page range + +### "The page range is not valid." + +> The page range is not valid. Use page numbers starting at 1, separated by commas, and write ranges from the lower to the higher number, for example 1-5, 8, 10-12. + +Status `InvalidPageRange`. The text of `Pages` is not a page range: letters, 0, a minus sign, an empty piece +between commas, or a range written backwards such as `5-2`. + +### "The page range includes a page that is not in the PDF." + +> The page range includes a page that is not in the PDF. Check the number of pages in the document and choose pages within it. + +Status `PageNotFound`. The range is well written but names a page after the last one. + +## Problems with the options + +### "The print options are not valid, ..." + +> The print options are not valid, for example the printer name is empty or the number of copies is less than 1. Check the print options and try again. + +Status `InvalidOptions`. One of: the options object is `null`, `PrinterName` is empty, `Copies` is below 1 +or above 32767, or `Duplex` / `Scale` holds a number that is not one of their named values. + +### "The paper source "<name>" is not available ..." + +> The paper source "<name>" is not available on this printer. The available paper sources are: <list>. Use one of these names exactly, or leave the paper source empty to use the printer's default tray. + +> The paper source "<name>" is not available because this printer does not report any selectable paper sources. Leave the paper source empty to use the printer's default tray. + +Status `InvalidOptions`. Copy one of the listed names into `PaperSource` (letter case does not matter), or +leave it out. Tray names come from the printer driver, so they can differ between two models, or between two +drivers for the same model. + +### "The output file "<path>" cannot be used." + +> The output file "<path>" cannot be used. Check that the path is a file name (not a folder) and that the folder it is in already exists. + +Status `InvalidOptions`. `OutputFile` is blank, names a folder, contains characters Windows does not allow +in a file name, or its folder does not exist. PDFStream.NET never creates folders: create it first. + +## Problems with the printer + +### "No printer with that name is installed on this computer." + +> No printer with that name is installed on this computer. Check the printer name exactly as Windows lists it, and that the printer is visible to the account running this program. + +Status `PrinterNotFound`. Check the spelling against Settings, Printers & scanners (or run the test-print +sample, which lists the installed printers). If the name is right and the program runs as a Windows service, +a scheduled task or an IIS app pool, the printer is probably a per-user connection that only your own account +can see. See [services-and-iis.md](services-and-iis.md#the-account-must-see-the-printer). + +### "The printer could not be opened, or it does not accept the requested settings." + +> The printer could not be opened, or it does not accept the requested settings. Check that the printer is switched on and connected and that the Windows Print Spooler service is running, then try again or choose different print settings. + +Status `PrinterUnavailable`. The general printer message. It covers: + +- `Duplex` set to `LongEdge` or `ShortEdge` on a printer whose driver cannot print on both sides (PDFStream.NET + refuses rather than printing one-sided). Use `DuplexMode.PrinterDefault` or `None`, or another printer. +- Windows lists the printer but cannot open it, or rejects its settings. +- The print system failed while the job was running (for example the driver failed to start or end the job). +- The printer reports no printable area at all. +- The list of printers could not be read for a reason other than a stopped Print Spooler (a stopped spooler + that Windows reports as such gets its own message, below). + +### "The printer "<printer name>" is paused in Windows, ..." + +> The printer "<printer name>" is paused in Windows, so the document was not sent. Open the printer's queue (Settings, Printers & scanners), choose Resume, then print again. + +Status `PrinterUnavailable`. A paused queue would accept the job and hold it, so PDFStream.NET refuses instead of +reporting a print that never comes out. Resume the queue. + +### "The printer "<printer name>" is set to "Use printer offline" in Windows, ..." + +> The printer "<printer name>" is set to "Use printer offline" in Windows, so the document was not sent. Open the printer's queue, clear "Use printer offline" in the Printer menu, then print again. + +Status `PrinterUnavailable`. Someone chose "Use printer offline" for this queue. Clear it. + +### "The printer "<printer name>" is not available at the moment, ..." + +> The printer "<printer name>" is not available at the moment, so the document was not sent. Check that the printer is switched on and connected, then print again. + +Status `PrinterUnavailable`. Windows itself marks the printer as not available. + +### "The printer "<printer name>" is being removed from Windows ..." + +> The printer "<printer name>" is being removed from Windows and no longer accepts documents, so the document was not sent. Choose another printer, or add this printer again, then print again. + +Status `PrinterUnavailable`. The printer is being deleted (often it waits for its last job to finish). + +### "Windows could not open the printer "<printer name>", ..." + +> Windows could not open the printer "<printer name>", so the document was not sent. Check that the Windows Print Spooler service is running and that the account running this program is allowed to use this printer, then print again. + +Status `PrinterUnavailable`. The printer is in the list but its queue cannot be opened, usually because the +account has no permission to print to it (check the printer's Security tab, and on a print server the share's +permissions), or the print server cannot be reached. + +### "The Windows Print Spooler service is not running, ..." + +> The Windows Print Spooler service is not running, so no printer can be used and the document was not sent. Start the Print Spooler service (in Services, or ask the person who looks after this computer), then print again. + +Status `PrinterUnavailable`. Start the Print Spooler service (`services.msc`, "Print Spooler", Start; set it +to start automatically). + +What PDFStream.NET detects: Windows answers "RPC server unavailable" (error 1722) while the spooler service is +stopped, and PDFStream.NET gives this message when it gets that answer while reading the list of printers, while +opening the printer's queue, or when the printer you named is not in the list and the local spooler, asked +directly, gives that answer. What it does not do: it does not ask the Windows service manager about the +service, so a spooler that fails in some other way (still starting, crashing, refusing this account) gets the +general printer message above, which also says to check the spooler. + +Not verified yet: this mapping is tested only with simulated answers. A machine with the spooler really stopped +is on the [release checklist](release-checklist.md) and has not been tried. + +## The job stopped + +### "Printing was cancelled before it finished, ..." + +> Printing was cancelled before it finished, so some pages may not have been printed. Start the job again if the document is still needed. + +Status `Cancelled`. Your cancellation token fired, or the print system cancelled the job by itself. Check +`PagesPrinted`: when your token stopped the job between pages it is the exact number of pages that print; +when it is 0, nothing was sent. A print-to-file printer used without `OutputFile` asks where to save, and +closing that dialog without saving cancels the job. Where there is no screen to show the dialog on (a service, +for example), the job cannot finish normally: it may be cancelled or it may wait. Always set `OutputFile` for +such printers. + +### "Page <n> of the PDF could not be drawn, ..." + +> Page <n> of the PDF could not be drawn, so printing was stopped and the unfinished job may have been withdrawn from the print queue. Check the print queue for a job left over from this document and delete it, then open the PDF in a PDF viewer to check that the page is not damaged and print the document again. Details: <technical reason> + +Status `UnknownError`, `PagesPrinted` 0. The PDF engine failed on that page. Check the queue for a leftover +job, open the PDF in a viewer, and keep the "Details" text for a bug report. + +### "Page <n> could not be printed: the printer did not accept it as drawing commands, ..." + +> Page <n> could not be printed: the printer did not accept it as drawing commands, and the page is too large to send as a picture with the memory available. Printing was stopped and the unfinished job may have been withdrawn from the print queue, so check the print queue for a job left over from this document and delete it. Choose a smaller paper size, or split the document into smaller parts, then try again. + +Status `UnknownError`, `PagesPrinted` 0. The driver refused the page as drawing commands, so PDFStream.NET tried +to send it as a picture, and there was not enough memory for one. This happens most in 32-bit programs with +very large pages; a 64-bit build of your program usually solves it. + +### "Printing failed for an unexpected reason. ... Details: <technical reason>" + +> Printing failed for an unexpected reason. Try again, and if it keeps happening contact the person who looks after this program. Details: <technical reason> + +Status `UnknownError`. Something none of the other statuses describes. The "Details" part is the technical +reason. The most likely one in a new installation is that `pdfium.dll` is missing for the processor the +program runs on. The details then read "Unable to load DLL 'pdfium' or one of its dependencies: The specified +module could not be found. (0x8007007E)"; see +[services-and-iis.md](services-and-iis.md#32-bit-and-64-bit) for how the right copy gets next to your program. + +## Problems that come with no error + +### It says printed but nothing came out + +`Ok` means every page was rendered and handed to Windows. Paper coming out is up to the printer, and the job +can wait in the Windows queue: + +- **The printer shows "Offline" in Windows but it really is on.** Network printers often report Offline + through SNMP while they print perfectly well, so PDFStream.NET does not refuse a printer just because Windows + says Offline. Only these queue states are refused (with their own messages above): paused, "Use printer + offline", not available, being deleted, and a queue that cannot be opened (including a stopped Print + Spooler). +- **The printer really is switched off or unplugged.** The job is accepted and waits in the queue; it prints + when the printer comes back. Open the queue to see it. +- **Out of paper, jammed, out of toner, door open.** These are not refused either: the job waits in the queue + and prints once someone fixes the printer. +- **Wrong printer.** Check `PrinterName`; network names look like `\\server\printer`. + +### The output file is empty, locked or missing right after printing + +*Microsoft Print to PDF* keeps writing the file for a moment after `Print` returns. Open the file only once it +can be opened on its own; [usage.md](usage.md#printing-to-a-file) has a short helper that waits for it. + +### More pages were counted than the PDF has + +With software copies (a driver that supports fewer copies than you asked for, such as Print to PDF), +`PagesPrinted` counts every page sent, so 3 pages x 2 copies is 6. When the driver makes the copies itself, +each page is sent once and it is 3. See [usage.md](usage.md#copies). + +### Duplex copies start on the back of the previous copy + +Known limitation: with software copies, duplex on and an odd page count, the next copy starts on the back of +the last sheet of the previous copy. Print one copy per call when that matters. + +### Form fields are missing on the paper + +PDFStream.NET prints filled-in form fields (see [usage.md](usage.md#form-fields)). If some are missing: + +- **The field is marked as not printable.** PDF forms can hide a field from paper (often instructions or + buttons). Such fields stay off the paper on purpose, as they do when the PDF is printed from a viewer. +- **The page says "Please wait..." or the fields are empty and the form looks different in Adobe Reader.** + The PDF is an XFA form. XFA forms are not supported: the bundled PDF engine is built without XFA, so it prints + only the page content. Save or print the form to a plain PDF first (for example with "Microsoft Print to PDF" + from a viewer that shows it correctly) and print that file. +- **A value shows in one format on screen and another on paper.** Form scripts do not run, so a value that a + script formats (dates, currency) prints as it is stored in the PDF. +- **Every field of one page is blank, but the rest of that page prints.** The PDF engine refused to draw that + page's fields at all, both into a copy of the page and into the page itself, so PDFStream.NET printed the page + without them instead of failing the print. If you can share the PDF, open an issue with it. +- **The fields print, but images or text are missing from that page.** This is the known limitation of form + printing (see [usage.md](usage.md#form-fields)). A page with fields is normally printed from a copy that has + its fields drawn in. When that copy cannot be used, the fields are drawn into the page itself instead, and if + the page takes its fonts or images from the PDF's page tree (instead of carrying them itself), those are then + hidden. The copy cannot be used, for example, when the PDF switches layers off on that page, when the page + refers to something the file does not contain (a damaged PDF), when the PDF is larger than 64 MB (the copy + budget), or when your application uses a `pdfium.dll` other than the one PDFStream.NET was tested with (see + [usage.md](usage.md#form-fields)). Print or save the filled form to a plain PDF first (for example with + "Microsoft Print to PDF" from a viewer, or with the "flatten" option of the tool that filled it) and print + that file. + +### A form page shows field values from another page + +Known limitation. In a PDF with three or more form pages that share one indirect `/Contents` array (and one +indirect `/Resources` dictionary), a later page can also print the fields of earlier pages, and the status is +still `Ok`: the third page also shows the second page's field values, the fourth page also shows those of the +second and third. The check PDFStream.NET makes before it uses a page copy catches the first affected page, but +the fallback that then draws the fields into the page itself edits the same shared array. See +[usage.md](usage.md#form-fields). Workarounds: + +- Flatten the PDF with a PDF tool before printing (print the filled form to a plain PDF with "Microsoft Print + to PDF" from a viewer, or use the "flatten" option of the tool that filled it) and print that file. +- Or print the pages as separate documents: split the PDF into one file per form page and print each file with + its own call. + +### A PDF marked "printing not allowed" printed anyway + +That is by design: owner permissions such as "printing not allowed" are ignored, as server automation +expects. Only an open password stops PDFStream.NET from reading a PDF. diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..599ae17 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,313 @@ +# Using PDFStream.NET + +This guide covers everything the library does: the three print calls, every print option, every result +status with the exact message it carries, and the behaviour that is worth knowing before you rely on it in +production. For problems, start from the message you got in [troubleshooting.md](troubleshooting.md). For +Windows services, scheduled tasks and IIS, read [services-and-iis.md](services-and-iis.md). + +## Requirements + +- Windows 10 or Windows Server 2016, or newer. +- A project that targets a Windows framework: `net8.0-windows`, `net10.0-windows` or newer. A project that + targets plain `net8.0` cannot reference the `PDFStream.NET` package, because printing goes through the Windows + print system. +- Nothing else on the machine: no Adobe Reader, no PDF viewer, no licence key. The PDF engine (PDFium) comes + with the package for 64-bit (x64), 32-bit (x86) and Arm64 Windows, and your build picks the right one. +- The NuGet package is `PDFStream.NET` (`dotnet add package PDFStream.NET`); in code you write + `using PDFStream.NET;`. + +## The three calls + +```csharp +using PDFStream.NET; + +PrintResult fromFile = PdfPrinter.Print(@"C:\Slips\slip-1042.pdf", options); +PrintResult fromStream = PdfPrinter.Print(stream, options); // read from its current position to the end +PrintResult fromBytes = PdfPrinter.Print(pdfBytes, options); +``` + +Each call takes an optional `CancellationToken` as its last argument. None of them throws a managed exception +for bad input or printer problems: every such outcome, including an unexpected internal failure, comes back as a +`PrintResult`. The one failure no .NET library can turn into a result is a crash inside the native PDF engine; +see [Security and limits](#security-and-limits). + +- **File path**: a missing, unreadable or blank path returns `FileNotFound`. +- **Stream**: it is read from its current position to its end, it does not need to support seeking, and it + is left open (it belongs to you). A `null`, empty or broken stream returns `InvalidPdf`. +- **Byte array**: the complete PDF file. `null` or empty returns `InvalidPdf`. The array is not changed or kept. + +A full example: + +```csharp +PrintResult result = PdfPrinter.Print(pdfBytes, new PrintOptions +{ + PrinterName = @"\\print-server\Warehouse Printer 1", + DocumentName = "Packing slip 1042", + Pages = "1-2", + Copies = 2, + Duplex = DuplexMode.LongEdge, + Color = false, +}); + +if (!result.Succeeded) +{ + // The message is written for people: log it. An UnknownError message can end with technical details, + // so do not show it as it is in a public web page. + logger.LogWarning("Packing slip 1042 did not print ({Status}): {Message}", result.Status, result.Message); +} +``` + +## Print options + +Build a `PrintOptions` with an object initializer; every property is init-only. Anything you leave out keeps +the printer's own setting, except where a default is given below. + +| Option | Default | What it does | +|---|---|---| +| `PrinterName` | empty (required) | The printer, exactly as Windows lists it, including network names such as `\\server\printer`. An exact match wins; otherwise letter case and spaces around the name are ignored. Empty returns `InvalidOptions`. | +| `DocumentName` | `null` | The name of the job in the print queue. `null` or blank uses "PDF document". | +| `Password` | `null` | The password of a protected PDF. `null` or empty means none. A PDF that only has an owner password (restrictions, but no password to open it) prints without one, even when you pass an unrelated password. | +| `Pages` | `null` (every page) | The pages to print, counted from 1, for example `"1-5, 8, 10-12"`. Pages print in the order written, and a page written twice prints twice. Spaces around numbers are fine. `null`, empty or blank means every page. | +| `Copies` | 1 | How many copies, from 1 to 32767. See [Copies](#copies). | +| `Duplex` | `PrinterDefault` | `PrinterDefault` changes nothing; `None` prints one-sided; `LongEdge` flips like a book; `ShortEdge` flips like a notepad. Asking a printer that cannot print on both sides for `LongEdge` or `ShortEdge` returns `PrinterUnavailable` instead of quietly printing one-sided. | +| `Color` | `null` (printer's own setting) | `null` keeps whatever the printer is set to; `true` asks for colour and `false` for black and white. A printer that cannot print in colour prints black and white either way. | +| `Scale` | `FitToPage` | `FitToPage` shrinks or enlarges each page to fit the printable area, centred, and turns it to match the paper when that fits better. `ActualSize` prints at 100%, centred, turning the page when that keeps more of it on the paper; anything outside the printable area is cut off. Every page is sized on its own, so a PDF with mixed sizes and orientations works. | +| `PaperSource` | `null` (default tray) | The tray name as the printer reports it (letter case ignored). A name the printer does not have returns `InvalidOptions` with the list of tray names it does have. | +| `OutputFile` | `null` | Writes the job to this file instead of the printer's port. This is how *Microsoft Print to PDF* runs without a Save As dialog. See [Printing to a file](#printing-to-a-file). | + +## The result + +| Member | Meaning | +|---|---| +| `Succeeded` | `true` only when every requested page was rendered and sent to the printer (`Status` is `Ok`). | +| `Status` | A `PrintStatus` value to branch on in code. | +| `Message` | The same outcome in plain language: what happened and, for a failure, what to do next. Most messages can be shown to the person running the program as they are, but an `UnknownError` message may end with technical details (the text of an internal exception), so log it rather than show it in a public web page. | +| `PagesPrinted` | How many pages were sent to the printer. See below. | + +### What PagesPrinted counts + +- **After success**: every page sent. When the library makes the copies itself (software copies, see + [Copies](#copies)), that is pages x copies; when the printer driver makes the copies, each page is sent + once, so it is the number of pages only. +- **After a cancellation that ended the job normally**: the exact number of pages sent before printing + stopped. The job is then finished normally, so those pages do print. +- **After a failure**: 0. A job that fails is aborted and may have been withdrawn from the print queue by + Windows (check the queue for a job left over), and pages drawn before the failure normally never come out. A cancellation that arrives before the first page has + been drawn is also reported with 0, and so is a job the print system cancelled by itself. + +"Printed" means the pages were really rendered and handed to Windows. It does not mean paper has come out: +a printer that is out of paper or switched off keeps the job in its queue (see +[troubleshooting.md](troubleshooting.md#it-says-printed-but-nothing-came-out)). + +## Every status and its message + +Each status has a standard message. Where a more specific message can replace it, that message is listed +too; text in angle brackets is filled in for the actual job. + +| Status | Standard message | +|---|---| +| `Ok` | The document was printed. All requested pages were sent to the printer. | +| `FileNotFound` | The PDF file could not be found or read. Check that the file path is correct and that this account is allowed to open the file. | +| `InvalidPdf` | The file is not a valid PDF, or it is damaged and cannot be opened. Check that the file is a complete PDF and try opening it in a PDF viewer. | +| `PasswordRequired` | The PDF is protected with a password and none was given. Enter the password in the print options and try again. | +| `PasswordInvalid` | The password given for the PDF is not correct. Check the password and try again. | +| `PrinterNotFound` | No printer with that name is installed on this computer. Check the printer name exactly as Windows lists it, and that the printer is visible to the account running this program. | +| `PrinterUnavailable` | The printer could not be opened, or it does not accept the requested settings. Check that the printer is switched on and connected and that the Windows Print Spooler service is running, then try again or choose different print settings. | +| `InvalidPageRange` | The page range is not valid. Use page numbers starting at 1, separated by commas, and write ranges from the lower to the higher number, for example 1-5, 8, 10-12. | +| `PageNotFound` | The page range includes a page that is not in the PDF. Check the number of pages in the document and choose pages within it. | +| `InvalidOptions` | The print options are not valid, for example the printer name is empty or the number of copies is less than 1. Check the print options and try again. | +| `Cancelled` | Printing was cancelled before it finished, so some pages may not have been printed. Start the job again if the document is still needed. | +| `UnknownError` | Printing failed for an unexpected reason. Try again, and if it keeps happening contact the person who looks after this program. | + +The more specific messages: + +| Status | When | Message | +|---|---|---| +| `PrinterUnavailable` | The queue is paused | The printer "<printer name>" is paused in Windows, so the document was not sent. Open the printer's queue (Settings, Printers & scanners), choose Resume, then print again. | +| `PrinterUnavailable` | "Use printer offline" is set | The printer "<printer name>" is set to "Use printer offline" in Windows, so the document was not sent. Open the printer's queue, clear "Use printer offline" in the Printer menu, then print again. | +| `PrinterUnavailable` | Windows reports it not available | The printer "<printer name>" is not available at the moment, so the document was not sent. Check that the printer is switched on and connected, then print again. | +| `PrinterUnavailable` | The printer is being deleted | The printer "<printer name>" is being removed from Windows and no longer accepts documents, so the document was not sent. Choose another printer, or add this printer again, then print again. | +| `PrinterUnavailable` | The queue cannot be opened | Windows could not open the printer "<printer name>", so the document was not sent. Check that the Windows Print Spooler service is running and that the account running this program is allowed to use this printer, then print again. | +| `PrinterUnavailable` | The Print Spooler is stopped | The Windows Print Spooler service is not running, so no printer can be used and the document was not sent. Start the Print Spooler service (in Services, or ask the person who looks after this computer), then print again. | +| `InvalidOptions` | Unknown paper source | The paper source "<name>" is not available on this printer. The available paper sources are: <list>. Use one of these names exactly, or leave the paper source empty to use the printer's default tray. | +| `InvalidOptions` | Unknown paper source, printer lists none | The paper source "<name>" is not available because this printer does not report any selectable paper sources. Leave the paper source empty to use the printer's default tray. | +| `InvalidOptions` | Unusable output file | The output file "<path>" cannot be used. Check that the path is a file name (not a folder) and that the folder it is in already exists. | +| `UnknownError` | An unexpected exception | Printing failed for an unexpected reason. Try again, and if it keeps happening contact the person who looks after this program. Details: <technical reason> | +| `UnknownError` | A page could not be drawn | Page <n> of the PDF could not be drawn, so printing was stopped and the unfinished job may have been withdrawn from the print queue. Check the print queue for a job left over from this document and delete it, then open the PDF in a PDF viewer to check that the page is not damaged and print the document again. Details: <technical reason> | +| `UnknownError` | A page is too large for the picture fallback | Page <n> could not be printed: the printer did not accept it as drawing commands, and the page is too large to send as a picture with the memory available. Printing was stopped and the unfinished job may have been withdrawn from the print queue, so check the print queue for a job left over from this document and delete it. Choose a smaller paper size, or split the document into smaller parts, then try again. | + +The checks run in this order, and the first problem ends the call: the options, the cancellation token, +opening the PDF, the page range against the real page count, the printer and its settings (including the +queue state), and then the job itself. + +## Copies + +When the printer driver says it can make the requested number of copies, the library asks the driver for +them and sends each page once. When it cannot (a driver that supports only 1 copy, such as *Microsoft Print +to PDF*), the library sends the whole document again for each copy, in the same print job, so the copies +come out collated and a print-to-file job still produces one file. It never does both, so you never get +copies of copies. + +Known limitation: with software copies, duplex on, and an odd number of pages, the next copy starts on the +back of the last sheet of the previous copy. Print one copy per call if that matters for your documents. + +## Passwords and "printing not allowed" + +A PDF can carry an *open* password (needed to read it) and an *owner* password with permissions such as +"printing not allowed". PDFStream.NET needs the open password when there is one. Owner permissions are ignored: +a PDF that says "printing not allowed" prints anyway, which is what server automation expects. Do not use +PDFStream.NET to enforce a document's permissions. + +## Printing to a file + +Set `OutputFile` to have the job written to a file instead of sent to the printer's port, for example with +*Microsoft Print to PDF*. The folder must already exist; use a full path (a relative path is taken from the +current folder of the process, which in a Windows service is `C:\Windows\System32`). An existing file is +replaced. An empty text returns `InvalidOptions`; leave the option out (`null`) when you do not want a file. + +**Microsoft Print to PDF keeps writing after Print returns.** The print call returns when the pages have been +sent; the driver finishes the file a moment later. Open the file only once it can be opened on its own: + +```csharp +/// Waits until the print system has finished writing the file, or the time runs out. +static bool WaitUntilWritten(string path, TimeSpan timeout) +{ + DateTime giveUp = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < giveUp) + { + try + { + // Opening with no sharing only succeeds once the print system has closed the file. + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None); + if (stream.Length > 0) + { + return true; + } + } + catch (IOException) + { + // Not created yet, or still being written: try again shortly. + } + + Thread.Sleep(500); + } + + return false; +} +``` + +## Cancelling + +Pass a `CancellationToken`. It is checked before the PDF is opened, after it is opened, and between pages, +never in the middle of a page. The first page with form fields of a document is the exception that runs +longer: it first finds and copies every form page the call prints (see [Form fields](#form-fields)), which is +one engine call that cannot be interrupted (about 77 ms on x64 and 95 ms on x86 for 500 form pages, as measured in +a review). A job stopped between pages ends normally, so the pages already sent print and +`PagesPrinted` counts them exactly; the status is `Cancelled`. + +## Security and limits + +Read this before you print PDFs that come from outside your organisation (uploads, e-mail, customer portals). + +- **PDFium runs inside your process, without a sandbox.** It is the PDF engine of Chrome, but Chrome runs it in + a sandboxed process of its own; PDFStream.NET calls it directly in yours. A malformed or deliberately hostile PDF + that triggers a memory fault inside PDFium ends the whole process at once: .NET cannot catch it, no + `PrintResult` is returned, and a Windows service simply stops (its recovery settings can restart it). +- **Print untrusted PDFs in a separate worker process.** Run the print call in a small child process (one per + job, or a long-lived worker that you start again when it dies) and treat a worker that disappears as a failed + job. A bad file then costs one job instead of your service. +- **One hung printer driver stalls every print in the process.** PDFium is not thread-safe, so PDFStream.NET holds + one lock for the whole process around every PDFium call, including drawing a page onto the printer, which + runs inside the printer driver. A driver that hangs while a page is drawn keeps that lock, and every other + print in the same process waits behind it. A worker process per printer (or per job) contains this as well. +- **A PDF can be built to make form printing use a lot of memory.** A value that pages inherit from the PDF's + page tree, written inline instead of as a separate object, is copied once for every page with fields. In a + test, a 1.2 MB file whose 100 pages with fields inherit an inline list of 100,000 numbers made memory grow by + about 600 MB while its pages were drawn. Ordinary PDFs inherit only a few + references this way. A worker process (above) contains such files as well. +- **Cancellation is checked between pages only.** The token is checked before the PDF is opened, after it is + opened and between pages. It cannot interrupt a page that is being drawn, a driver that hangs, the opening + of a very large PDF, or the first page with form fields of a document, whose one engine call copies every + form page of the job (see [Several threads at once](#several-threads-at-once)). +- **Security fixes in PDFium** reach PDFStream.NET through updates of the `bblanchon.PDFium.Win32` package it + depends on. To report a vulnerability, see [SECURITY.md](../SECURITY.md). + +## Several threads at once + +The calls are safe from several threads at once. PDFium, the engine that reads and draws the PDF, is not +thread-safe, so every call into it is made under one lock for the whole process. The lock is held for one +engine call at a time (opening the PDF, measuring or drawing one page, closing it), not for a whole job, so +concurrent jobs run side by side and interleave at page level. The first page with form fields of a document +is the exception: it runs one longer engine call that finds and copies every form page the job prints (about +77 ms on x64 and 95 ms on x86 for 500 form pages, as measured in a review), holds the lock for all of it, and cannot be +interrupted by cancellation or by another job. Each call is still its own print job with its +own pages in order; each simply takes longer than it would alone. If you print from many threads (a busy web +server, for example), a queue that prints one document at a time gives steadier timing. + +## How pages reach the printer + +Each page is drawn by PDFium straight onto the printer's page as drawing commands, which keeps text and +barcodes sharp and the spool file small. If a driver refuses that, the page is drawn as a picture at the +printer's resolution (at most 300 dpi) instead. Before any job starts, the printer's queue is checked: a +queue that is paused, set to "Use printer offline", not available, being deleted, or cannot be opened is +refused with a message naming the cause. A printer that only *reports* Offline is not refused; see +[troubleshooting.md](troubleshooting.md#it-says-printed-but-nothing-came-out). + +## Form fields + +Filled-in form fields print: text fields, checkboxes, radio buttons, lists and the other fields of an +ordinary PDF form (an AcroForm), with the values they hold. PDFium, the PDF engine, never draws form fields +when it draws a page. So when the first page with fields is about to be printed, PDFStream.NET copies all the pages +with fields that the print call prints, in one go, within its own copy of the PDF in memory, draws the fields +into each copy exactly as they print, and prints the copies instead of the pages. A copy keeps everything its +page shows, including fonts, images and page sizes it takes from elsewhere in the PDF. Before a copy is used, +PDFStream.NET checks that it carries all of the page's fields and looks exactly like the page. If it does not +(this happens on a page with layers that the PDF switches off, because the copy's layers are not the ones the +PDF's layer settings name), the fields are drawn into the page itself instead, which keeps those layers off the +paper. Your file or byte array is never changed, and pages without fields are drawn untouched. + +- **Fields print as they print from a PDF viewer.** A field that is not marked for printing (a "screen only" + field, such as an instruction or a button) stays off the paper. +- **Values come from what the PDF stores.** Each field prints its stored appearance. A field that has a value + but no stored appearance, and every field of a form that says its appearances must be rebuilt (the form's + `NeedAppearances` setting, which some form-filling tools set instead of writing the appearance), gets an + appearance built by PDFium from its value first. No form scripts run, so a value that a script would format + (a date or currency format, for example) prints as it is stored. +- **XFA forms are not supported.** The PDFium build PDFStream.NET ships is built without XFA. A form made only of + XFA (a "dynamic" form from Adobe LiveCycle or AEM Designer) has no ordinary fields to print, so only the page + content prints, which for such forms is often a single "Please wait..." page. A form that carries both kinds + prints its ordinary fields. Save or print such a form to a plain PDF first. +- If the copy of a page cannot be used for any reason (see the known limitation below), the fields are drawn + into the page itself instead. Only if that fails too does the page print without its fields, as earlier + versions printed it. +- **A PDF with fields costs a little more.** The pages to be printed are read once more to find the fields, + each page with fields is drawn twice at low resolution for the check above and read once more, and until the + print call returns the copies hold one more copy of what those pages use (their fonts and images, for + example). What several pages share as separate objects (images, fonts) is copied once, so for those this is + at most about the size of the PDF file; the exception is described under + [Security and limits](#security-and-limits). A PDF without fields costs nothing extra. +- **The copy budget is 64 MB.** The copies are made only for a PDF of at most 64 MB. For a larger PDF, the + fields of every page are drawn into the page itself. That is right for most pages; only a page that takes + fonts or images from the PDF's page tree prints without them (see the known limitation below). Nothing is + reported as an error: the print succeeds as usual. +- **Form printing relies on a PDFium function marked experimental.** The copies are made with + `FPDF_ImportPagesByIndex`, which PDFium marks as experimental. It has been tested only with the PDFium build + PDFStream.NET depends on (160.0.8165, from the `bblanchon.PDFium.Win32` package). If your application uses another + `pdfium.dll` in which that function is missing or fails, the fields are drawn into each page itself instead: + they still print, but a page that takes fonts or images from the PDF's page tree prints without them. +- **Known limitation: pages that share one content array.** In a PDF with three or more form pages that share + one indirect `/Contents` array (and one indirect `/Resources` dictionary), later pages can also show the fields + of earlier pages, and the print still reports `Ok`. For example, the third page also prints the second page's + field and the fourth page also prints the fields of the second and third. The check described above catches + the first page affected, but the fallback then draws the fields into the page itself, which edits the shared + array again. Some generators write identical pages this way; most PDFs are not built like this. Giving + every page its own private copy would bring back the memory growth described above, so this is accepted for now. + If your PDFs look like this, flatten them with a PDF tool before printing (see + [troubleshooting.md](troubleshooting.md#a-form-page-shows-field-values-from-another-page)) or print the + pages as separate documents. +- **Known limitation.** A page that has form fields *and* takes its fonts or images from the PDF's page tree + instead of carrying them itself, *and* whose copy cannot be used, can print without those fonts or images + (the fields are then drawn into the page itself, which hides what it takes from the page tree). The copy + cannot be used, for example, on a page with layers the PDF switches off, on a page that refers to something + the file does not contain (a damaged PDF), or in a PDF over the copy budget. Such files are rare; see + [troubleshooting.md](troubleshooting.md#form-fields-are-missing-on-the-paper) for a workaround. diff --git a/global.json b/global.json new file mode 100644 index 0000000..3140116 --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/samples/PDFStream.NET.TestPrint/IConsoleIo.cs b/samples/PDFStream.NET.TestPrint/IConsoleIo.cs new file mode 100644 index 0000000..91aea8b --- /dev/null +++ b/samples/PDFStream.NET.TestPrint/IConsoleIo.cs @@ -0,0 +1,55 @@ +namespace PDFStream.NET.TestPrint; + +/// +/// The only way the test-print program talks to the person: lines of plain text out and one +/// key press in. Keeping the console behind this small interface lets the tests run the whole +/// program without a real console, so no test can ever block waiting for a key. +/// +public interface IConsoleIo +{ + /// Shows one line of text. An empty text shows an empty line. + /// The text to show. + void WriteLine(string text = ""); + + /// Shows a short prompt and waits until the person presses a key. + void WaitForKey(); +} + +/// The real console: output and a real key press. +public sealed class SystemConsoleIo : IConsoleIo +{ + /// Creates the console wrapper and switches the output to UTF-8 where Windows allows it. + public SystemConsoleIo() + { + try + { + // Printer names can contain accents or other non-ASCII letters; the default console code + // page would show them as question marks, and then the name could not be copied. + Console.OutputEncoding = System.Text.Encoding.UTF8; + } + catch (IOException) + { + // No real console is attached (output is redirected); the text is shown as well as it can be. + } + } + + /// + public void WriteLine(string text = "") => Console.WriteLine(text); + + /// + public void WaitForKey() + { + Console.WriteLine(); + Console.WriteLine("Press any key to close this window..."); + try + { + Console.ReadKey(intercept: true); + } + catch (InvalidOperationException) + { + // The input is redirected (for example the program was started from a script), so there + // is no key to read. A line read keeps the "wait before closing" promise as well as possible. + Console.ReadLine(); + } + } +} diff --git a/samples/PDFStream.NET.TestPrint/PDFStream.NET.TestPrint.csproj b/samples/PDFStream.NET.TestPrint/PDFStream.NET.TestPrint.csproj new file mode 100644 index 0000000..d6cfe11 --- /dev/null +++ b/samples/PDFStream.NET.TestPrint/PDFStream.NET.TestPrint.csproj @@ -0,0 +1,38 @@ + + + + + + net10.0-windows + Exe + PDFStream.NET.TestPrint + PDFStream.NET.TestPrint + Double-click test-print program for PDFStream.NET. Reads settings.json next to the program, checks everything and, only when asked to, prints a PDF. + + false + + + + + + + + + + + + + diff --git a/samples/PDFStream.NET.TestPrint/Program.cs b/samples/PDFStream.NET.TestPrint/Program.cs new file mode 100644 index 0000000..572fa83 --- /dev/null +++ b/samples/PDFStream.NET.TestPrint/Program.cs @@ -0,0 +1,29 @@ +namespace PDFStream.NET.TestPrint; + +/// +/// The entry point. Double-clicking the program runs it with no switches: the real console, the real +/// printer list and the PDFStream.NET library are handed to , which does the work. +/// +internal static class Program +{ + private static int Main() + { + try + { + return new TestPrintApp( + new SystemConsoleIo(), + AppContext.BaseDirectory, + TestPrintApp.ListInstalledPrinters, + (path, options) => PdfPrinter.Print(path, options)).RunAndWait(); + } + catch (Exception ex) + { + // Only reached if even setting up failed. The window must still stay open long enough to read this. + Console.WriteLine("Something unexpected went wrong before the program could start, and nothing was printed."); + Console.WriteLine($"What Windows reported: {ex.Message}"); + Console.WriteLine("Please try again. If it keeps happening, send this text to whoever looks after this program."); + new SystemConsoleIo().WaitForKey(); + return 1; + } + } +} diff --git a/samples/PDFStream.NET.TestPrint/TestPrintApp.cs b/samples/PDFStream.NET.TestPrint/TestPrintApp.cs new file mode 100644 index 0000000..497890b --- /dev/null +++ b/samples/PDFStream.NET.TestPrint/TestPrintApp.cs @@ -0,0 +1,256 @@ +using System.Drawing.Printing; + +namespace PDFStream.NET.TestPrint; + +/// +/// The sending step of the program. In the real program it is ; +/// the tests pass their own so they can prove that a dry run never sends anything. +/// +/// The full path of the PDF. +/// What and where to print. +/// What the library reported. +public delegate PrintResult PrintAction(string pdfPath, PrintOptions options); + +/// +/// The whole logic of the double-click test-print program: read settings.json, check the printer +/// and the PDF, then either report what would happen (a dry run, the default) or really print. All +/// output goes through , and every message says what happened and what to do next. +/// +public sealed class TestPrintApp +{ + private readonly IConsoleIo _io; + private readonly string _folder; + private readonly Func> _installedPrinters; + private readonly PrintAction _print; + + /// Creates the program logic. + /// Where the text goes, and where the key press comes from. + /// The folder of the program: settings.json lives here and relative paths start here. + /// Lists the printers Windows has installed. + /// Sends the PDF to the printer. + public TestPrintApp(IConsoleIo io, string folder, Func> installedPrinters, PrintAction print) + { + _io = io; + _folder = folder; + _installedPrinters = installedPrinters; + _print = print; + } + + /// The printers installed on this computer, as lists them. + /// The names; an empty list when Windows cannot say (for example the Print Spooler is stopped). + public static IReadOnlyList ListInstalledPrinters() + { + try + { + return PrinterSettings.InstalledPrinters.Cast().ToList(); + } + catch (Exception ex) when (ex is InvalidPrinterException or System.ComponentModel.Win32Exception) + { + // Treated like "no printers": the caller then explains it in plain language. + return Array.Empty(); + } + } + + /// + /// Makes a path usable whatever folder the program was started from: a relative path is taken + /// relative to the program's own folder (a double-click and a shortcut start in different folders), + /// and a full path is returned unchanged. + /// + /// The folder of the program. + /// The path from the settings file. + /// The full path. + public static string ResolveNextToProgram(string folder, string path) => + Path.IsPathFullyQualified(path) ? path : Path.GetFullPath(Path.Combine(folder, path)); + + /// + /// Runs the program and always waits for a key press at the end, even after an unexpected error, + /// so the window never closes before the result can be read. + /// + /// 0 when nothing is wrong (including a dry run), 1 when the person has something to fix. + public int RunAndWait() + { + try + { + return Run(); + } + catch (Exception ex) + { + // The last safety net. The library itself never throws for bad input, but reading files and + // listing printers can still fail in ways nobody planned for; the person gets words, not a stack trace. + string detail = string.IsNullOrWhiteSpace(ex.Message) ? ex.GetType().Name : ex.Message; + _io.WriteLine(); + _io.WriteLine("Something unexpected went wrong, and nothing was printed."); + _io.WriteLine($"What Windows reported: {detail}"); + _io.WriteLine("Please try again. If it keeps happening, send this text to whoever looks after this program."); + return 1; + } + finally + { + _io.WaitForKey(); + } + } + + /// Runs the program once, without waiting for a key. Use from the entry point. + /// 0 when nothing is wrong (including a dry run), 1 when the person has something to fix. + public int Run() + { + _io.WriteLine("PDFStream.NET test print"); + _io.WriteLine("--------------------"); + + SettingsLoadResult loaded = SettingsFile.Load(_folder); + if (loaded.Outcome == SettingsOutcome.Invalid) + { + _io.WriteLine(loaded.Message); + return 1; + } + + IReadOnlyList printers = _installedPrinters(); + + if (loaded.Outcome == SettingsOutcome.Created) + { + _io.WriteLine(loaded.Message); + _io.WriteLine(); + ShowPrinters(printers); + _io.WriteLine(); + _io.WriteLine("What to do next:"); + _io.WriteLine(" 1. Open that file in Notepad (right-click it, then Open with)."); + _io.WriteLine(" 2. Copy your printer's name into PrinterName and set PdfFile to the PDF you want to print."); + _io.WriteLine(" 3. Save the file and double-click this program again."); + _io.WriteLine("Nothing was printed. The file explains every setting."); + return 0; + } + + TestPrintSettings settings = loaded.Settings!; + _io.WriteLine($"Checking your settings in {loaded.Path}"); + + // Every check is reported, not just the first failure, so the person can fix all of it in one edit. + bool problems = false; + + // The printer name decides what the library is given; an installed printer is matched + // ignoring capitalisation and the name is then passed exactly as Windows spells it. + string? printer = null; + if (settings.PrinterName.Length == 0) + { + problems = true; + _io.WriteLine(" Problem: PrinterName is empty in settings.json, so I do not know which printer to use."); + ShowPrinters(printers); + _io.WriteLine(" Copy one of the names above exactly into PrinterName in settings.json."); + } + else + { + printer = printers.FirstOrDefault(p => string.Equals(p, settings.PrinterName, StringComparison.OrdinalIgnoreCase)); + if (printer is null) + { + problems = true; + _io.WriteLine($" Problem: the printer \"{settings.PrinterName}\" is not installed on this computer."); + ShowPrinters(printers); + _io.WriteLine(" Copy one of the names above exactly into PrinterName in settings.json."); + } + else + { + _io.WriteLine($" OK: the printer \"{printer}\" is installed."); + } + } + + string pdfPath = string.Empty; + if (settings.PdfFile.Length == 0) + { + problems = true; + _io.WriteLine(" Problem: PdfFile is empty in settings.json, so I do not know which PDF to print. Set PdfFile to the PDF you want to print."); + } + else + { + pdfPath = ResolveNextToProgram(_folder, settings.PdfFile); + if (File.Exists(pdfPath)) + { + _io.WriteLine($" OK: the PDF file was found: {pdfPath}"); + } + else + { + problems = true; + _io.WriteLine($" Problem: the PDF file was not found: {pdfPath}"); + _io.WriteLine(" Put the PDF there, or change PdfFile in settings.json to where it really is."); + } + } + + if (settings.Copies < 1) + { + problems = true; + _io.WriteLine($" Problem: Copies must be 1 or more, but settings.json says {settings.Copies}. Change Copies to a whole number such as 1."); + } + + if (problems || printer is null) + { + _io.WriteLine(); + _io.WriteLine($"Nothing was printed. Fix the problems above in {loaded.Path}, save it and double-click this program again."); + return 1; + } + + string? outputFile = settings.OutputFile.Length == 0 ? null : ResolveNextToProgram(_folder, settings.OutputFile); + string pages = settings.Pages.Length == 0 ? "all pages" : settings.Pages; + + if (!settings.ReallyPrint) + { + _io.WriteLine(); + _io.WriteLine("This is a DRY RUN: ReallyPrint is false in settings.json, so nothing was sent to the printer."); + _io.WriteLine("This is exactly what would be sent:"); + _io.WriteLine($" Printer: {printer}"); + _io.WriteLine($" PDF file: {pdfPath}"); + _io.WriteLine($" Copies: {settings.Copies}"); + _io.WriteLine($" Pages: {pages}"); + _io.WriteLine($" Output file: {outputFile ?? "(none, it goes to the printer)"}"); + _io.WriteLine(); + _io.WriteLine("Nothing was printed. To really print, open settings.json, change \"ReallyPrint\": false to \"ReallyPrint\": true,"); + _io.WriteLine("save the file and double-click this program again."); + return 0; + } + + _io.WriteLine(); + _io.WriteLine($"Sending {Path.GetFileName(pdfPath)} to \"{printer}\" (ReallyPrint is true)..."); + + // Public API only, exactly as a customer would call it. The library never throws for bad + // input or printer trouble: whatever goes wrong comes back as a status and a plain message. + PrintResult result = _print(pdfPath, new PrintOptions + { + PrinterName = printer, + DocumentName = Path.GetFileName(pdfPath), + Copies = settings.Copies, + Pages = settings.Pages.Length == 0 ? null : settings.Pages, + OutputFile = outputFile, + }); + + _io.WriteLine(); + if (result.Succeeded) + { + _io.WriteLine($"Printed: {result.PagesPrinted} page(s) were sent to \"{printer}\"."); + if (outputFile is not null) + { + _io.WriteLine($"The printer was asked to write the result to: {outputFile}"); + } + + _io.WriteLine(result.Message); + return 0; + } + + _io.WriteLine($"The document was NOT printed: {result.PagesPrinted} page(s) were sent."); + _io.WriteLine(result.Message); + return 1; + } + + /// Shows the installed printers, or explains that there are none. + /// The installed printer names. + private void ShowPrinters(IReadOnlyList printers) + { + if (printers.Count == 0) + { + _io.WriteLine(" Windows reports no installed printers. Install a printer in Windows settings (or check that the Print Spooler service is running), then try again."); + return; + } + + _io.WriteLine(" These printers are installed on this computer:"); + foreach (string name in printers) + { + _io.WriteLine($" {name}"); + } + } +} diff --git a/samples/PDFStream.NET.TestPrint/TestPrintSettings.cs b/samples/PDFStream.NET.TestPrint/TestPrintSettings.cs new file mode 100644 index 0000000..f962d35 --- /dev/null +++ b/samples/PDFStream.NET.TestPrint/TestPrintSettings.cs @@ -0,0 +1,199 @@ +using System.Text.Json; + +namespace PDFStream.NET.TestPrint; + +/// +/// What the person can set in settings.json. Every property has a safe default, so a file that +/// leaves a key out still works, and the default of is the safe one: a dry run. +/// +public sealed class TestPrintSettings +{ + /// The printer to print to, exactly as Windows lists it. Empty means "show me the list of printers". + public string PrinterName { get; init; } = string.Empty; + + /// The PDF to print. A relative path is resolved next to the program. + public string PdfFile { get; init; } = "test.pdf"; + + /// How many copies to print; must be at least 1. + public int Copies { get; init; } = 1; + + /// The pages to print, for example 1-3, 5. Empty means every page. + public string Pages { get; init; } = string.Empty; + + /// The file to write instead of printing on paper, for printers such as Microsoft Print to PDF. Empty means none. + public string OutputFile { get; init; } = string.Empty; + + /// + /// (the default) is a dry run that only checks and reports; + /// really sends the PDF to the printer. + /// + public bool ReallyPrint { get; init; } +} + +/// How reading settings.json ended. +public enum SettingsOutcome +{ + /// The file existed and was read. + Loaded, + + /// The file did not exist, so a commented starter file was created. Nothing else should run yet. + Created, + + /// The file could not be read or created; says why and what to do. + Invalid, +} + +/// The result of . +/// How reading ended. +/// The settings; only set when is . +/// A plain-language explanation for and ; empty when loaded. +/// The full path of settings.json. +public sealed record SettingsLoadResult(SettingsOutcome Outcome, TestPrintSettings? Settings, string Message, string Path); + +/// Reads settings.json next to the program and creates a commented starter file when it is missing. +public static class SettingsFile +{ + /// The file name, always looked up next to the program. + public const string FileName = "settings.json"; + + /// The names of every setting, in the order they appear in the starter file. + public static readonly IReadOnlyList Keys = + new[] { "PrinterName", "PdfFile", "Copies", "Pages", "OutputFile", "ReallyPrint" }; + + /// + /// The text written on the first run. It is a plain string (not a serialised object) because JSON + /// has no comments of its own and the comments are the documentation for the person editing it. + /// + public const string StarterContent = """ + { + // PDFStream.NET test-print settings. + // Lines that start with // are comments: they explain each setting and are ignored. + // Save this file, then double-click PDFStream.NET.TestPrint.exe again. + // Windows paths: write them with forward slashes (C:/Docs/a.pdf) or double backslashes (C:\\Docs\\a.pdf). + + // PrinterName: the printer to use, exactly as Windows lists it. + // Leave it empty and run the program: it lists every installed printer, and you copy one name here. + "PrinterName": "", + + // PdfFile: the PDF to print. A path without a folder (like test.pdf) is looked for next to this program. + // Explorer's "Copy as path" adds quote marks around the path: the program removes them, but if the + // file then will not load, remove the doubled quote marks yourself ("C:/Docs/a.pdf", not ""C:/Docs/a.pdf""). + "PdfFile": "test.pdf", + + // Copies: how many copies to print. A whole number, 1 or more. + "Copies": 1, + + // Pages: which pages to print, for example "1-3, 5". Leave it empty ("") to print every page. + "Pages": "", + + // OutputFile: for printers that can print into a file, such as "Microsoft Print to PDF". + // Give the file to create, for example "result.pdf" (saved next to this program). Leave empty ("") for none. + "OutputFile": "", + + // ReallyPrint: false (the default) is a DRY RUN. The program only checks your settings and shows + // what it would send, and nothing is printed. Change it to true to really send the PDF to the printer. + "ReallyPrint": false + } + """; + + /// + /// Reads the options with the leniency a hand-edited file needs: // comments are skipped, a comma + /// after the last item is accepted and key names may use any capitalisation. + /// + private static readonly JsonSerializerOptions ReadOptions = new() + { + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + PropertyNameCaseInsensitive = true, + }; + + /// Reads the text of a settings file. Throws when the text is not valid settings. + /// The text of the file. + /// The settings, with defaults for anything left out. + public static TestPrintSettings Parse(string json) + { + TestPrintSettings? read = JsonSerializer.Deserialize(json, ReadOptions); + if (read is null) + { + // A file that holds only the word null deserialises to nothing at all. + throw new JsonException("The file does not contain any settings."); + } + + // A key set to null in the file bypasses the property defaults; fall back to them here so the + // rest of the program never meets a null text. + TestPrintSettings defaults = new(); + return new TestPrintSettings + { + PrinterName = Unquote(read.PrinterName ?? defaults.PrinterName), + PdfFile = Unquote(read.PdfFile ?? defaults.PdfFile), + Copies = read.Copies, + Pages = (read.Pages ?? defaults.Pages).Trim(), + OutputFile = Unquote(read.OutputFile ?? defaults.OutputFile), + ReallyPrint = read.ReallyPrint, + }; + } + + /// + /// Trims a text and removes ONE pair of matching surrounding quotes (double or single). Explorer's + /// "Copy as path" puts double quotes around a path, and people paste them into the file as they are; + /// a path that really starts with a quote character does not exist, so removing them is always safe. + /// + /// The text from the settings file. + /// The text without whitespace around it and without one pair of surrounding quotes. + private static string Unquote(string value) + { + string text = value.Trim(); + if (text.Length >= 2 && (text[0] == '"' || text[0] == '\'') && text[^1] == text[0]) + { + text = text[1..^1].Trim(); + } + + return text; + } + + /// Loads settings.json from the folder, creating the commented starter file first if it is missing. + /// The folder of the program. + /// What happened, with a plain-language message when the program cannot go on. + public static SettingsLoadResult Load(string folder) + { + string path = System.IO.Path.Combine(folder, FileName); + + if (!File.Exists(path)) + { + try + { + File.WriteAllText(path, StarterContent, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return new SettingsLoadResult(SettingsOutcome.Invalid, null, + $"There is no settings file yet, and I could not create one at {path} because Windows does not allow writing to that folder. " + + "Copy the whole program folder to a place you can write to, such as your Desktop, and double-click the program there.", path); + } + + return new SettingsLoadResult(SettingsOutcome.Created, null, + $"This is the first run, so there was no settings file yet. I created one for you at:{Environment.NewLine} {path}", path); + } + + try + { + return new SettingsLoadResult(SettingsOutcome.Loaded, Parse(File.ReadAllText(path)), string.Empty, path); + } + catch (JsonException ex) + { + // Only the line number is shown, never the exception text or a stack trace: they mean nothing to the reader. + string where = ex.LineNumber is long line ? $" Look near line {line + 1}." : string.Empty; + return new SettingsLoadResult(SettingsOutcome.Invalid, null, + $"I could not read your settings file at {path}.{where} " + + "Check that every text is in double quotes, that Copies is a plain number, that ReallyPrint is true or false without quotes, " + + "that Windows paths use forward slashes or doubled backslashes (a single backslash is not allowed), " + + "and that a path pasted from Explorer does not have extra quote marks around it (remove the doubled quotes). " + + "To start again, delete the file and run the program: it creates a fresh one.", path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return new SettingsLoadResult(SettingsOutcome.Invalid, null, + $"I could not open your settings file at {path}. Close any program that has it open and try again.", path); + } + } +} diff --git a/src/PDFStream.NET/DuplexMode.cs b/src/PDFStream.NET/DuplexMode.cs new file mode 100644 index 0000000..fe03e78 --- /dev/null +++ b/src/PDFStream.NET/DuplexMode.cs @@ -0,0 +1,17 @@ +namespace PDFStream.NET; + +/// Whether and how a print job uses both sides of the paper. +public enum DuplexMode +{ + /// Leave the setting alone and use whatever the printer is configured to do. + PrinterDefault, + + /// Print on one side only. + None, + + /// Print on both sides and flip along the long edge (like the pages of a book). + LongEdge, + + /// Print on both sides and flip along the short edge (like a notepad). + ShortEdge, +} diff --git a/src/PDFStream.NET/Engine/IPdfDocument.cs b/src/PDFStream.NET/Engine/IPdfDocument.cs new file mode 100644 index 0000000..0879a77 --- /dev/null +++ b/src/PDFStream.NET/Engine/IPdfDocument.cs @@ -0,0 +1,88 @@ +using System.Drawing; + +namespace PDFStream.NET.Engine; + +/// +/// An open PDF document. Page indexes are zero-based. Dispose it as soon as it is no longer +/// needed: it holds native memory (the engine's copy of the file and the parsed document). +/// +/// +/// Every member may be called from any thread. Implementations backed by a non-thread-safe +/// engine serialise the calls internally, so concurrent callers wait rather than fail. +/// +internal interface IPdfDocument : IDisposable +{ + /// Number of pages in the document (zero or more). + int PageCount { get; } + + /// + /// Gets the size of a page in points (1/72 inch), as the page is displayed: if the PDF + /// rotates the page by 90 or 270 degrees, width and height are already swapped. + /// + /// Zero-based page index. + /// The page width and height in points. + /// is not a page of this document. + SizeF GetPageSizePoints(int pageIndex); + + /// + /// Tells the document which pages are about to be drawn, before the first of them is, so that it can prepare + /// them together. Optional: a document that is never told still draws any page it is asked for. The default + /// does nothing. + /// + /// + /// The PDFium document uses it to look for form fields only among the pages a print job will draw, and to + /// copy those pages in one go (see ). Repeated and out-of-range indexes are + /// ignored; calls after the preparation has started change nothing. + /// + /// The zero-based indexes of the pages about to be drawn. + void PlanToDraw(IReadOnlyList pageIndices) + { + } + + /// + /// Renders a page straight onto a Windows device context (for example a printer page), + /// scaled to fill . Vector content stays vector, which + /// keeps print quality high and spool files small. + /// + /// Zero-based page index. + /// The device context to draw on. The caller owns it. + /// Where the page goes, in device pixels. The page is + /// stretched to this rectangle, so the caller keeps the aspect ratio. When + /// is odd the rectangle has the turned page's proportions + /// (a portrait page turned a quarter fills a landscape rectangle). + /// to render as for paper: annotations + /// marked "do not print" are left out and print-specific appearances are used. Form fields are drawn as + /// they print whatever this says: the first time a page with fields is drawn, the PDFium implementation + /// draws the fields, as they print, into a private copy of the page (or, when the copy would not look + /// exactly like the page, into the page itself) and draws that from then on (see + /// ). + /// Extra clockwise rotation in quarter turns, 0 to 3, applied on top + /// of the page's own rotation: 0 draws the page as it is displayed, 1 turns it 90 degrees + /// clockwise, 2 turns it upside down and 3 turns it 90 degrees counter-clockwise. + /// is not a page of + /// this document, the rectangle has no area, or is not 0 to 3. + /// is zero. + /// The engine could not load or draw the page, + /// for example because the device context refused the drawing calls. Callers that print can + /// fall back to . + void RenderToDeviceContext(int pageIndex, IntPtr hdc, Rectangle destinationPixels, bool forPrinting, int quarterTurns); + + /// + /// Renders a page to a new bitmap on a white background, at the given resolution, as for paper + /// (form fields included, as they print). + /// + /// Zero-based page index. + /// Resolution in dots per inch; the bitmap is the page size in points + /// times dpi / 72, and carries that resolution. + /// Extra clockwise rotation in quarter turns, 0 to 3, applied on top + /// of the page's own rotation (see ). When it is odd the + /// bitmap's width and height are swapped to hold the turned page. + /// A 32-bit ARGB bitmap the caller owns and must dispose. + /// is not a page of + /// this document, is not positive, is not + /// 0 to 3, or the page is too large to render at this resolution. + /// GDI+ cannot create a bitmap this large. + /// There is not enough memory for the bitmap. + /// The engine could not load or draw the page. + Bitmap RenderToBitmap(int pageIndex, int dpi, int quarterTurns); +} diff --git a/src/PDFStream.NET/Engine/IPdfEngine.cs b/src/PDFStream.NET/Engine/IPdfEngine.cs new file mode 100644 index 0000000..b2eab10 --- /dev/null +++ b/src/PDFStream.NET/Engine/IPdfEngine.cs @@ -0,0 +1,20 @@ +namespace PDFStream.NET.Engine; + +/// +/// Opens PDFs. This seam keeps the PDF binding (PDFium today) out of the public API and lets +/// tests replace the engine with a fake. +/// +internal interface IPdfEngine +{ + /// + /// Tries to open a PDF held in memory. + /// + /// The complete PDF file. The engine keeps its own copy, so the caller may + /// reuse or change the array as soon as this method returns. + /// The password to open the PDF with. and an + /// empty string both mean "no password". + /// The opened document when the result is ; + /// otherwise . The caller owns it and must dispose it. + /// Whether the PDF opened and, if not, why. + PdfLoadStatus TryLoad(byte[] pdf, string? password, out IPdfDocument? document); +} diff --git a/src/PDFStream.NET/Engine/PdfLoadStatus.cs b/src/PDFStream.NET/Engine/PdfLoadStatus.cs new file mode 100644 index 0000000..7203647 --- /dev/null +++ b/src/PDFStream.NET/Engine/PdfLoadStatus.cs @@ -0,0 +1,22 @@ +namespace PDFStream.NET.Engine; + +/// +/// The outcome of asking an to open a PDF. +/// +internal enum PdfLoadStatus +{ + /// The PDF opened and a document was returned. + Ok, + + /// + /// The bytes are not a PDF the engine can read: empty, not a PDF at all, damaged beyond + /// repair, or protected by a security scheme the engine does not support. + /// + Invalid, + + /// The PDF needs a password to open and none was given. + PasswordRequired, + + /// The PDF needs a password to open and the one given is wrong. A PDF that opens without a password (restrictions only) never returns this, whatever password is supplied. + PasswordInvalid, +} diff --git a/src/PDFStream.NET/Engine/PdfiumDocument.cs b/src/PDFStream.NET/Engine/PdfiumDocument.cs new file mode 100644 index 0000000..9539335 --- /dev/null +++ b/src/PDFStream.NET/Engine/PdfiumDocument.cs @@ -0,0 +1,1071 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; + +namespace PDFStream.NET.Engine; + +/// +/// Flattens one loaded page's annotations into its content (PDFium's FPDFPage_Flatten in +/// production). A seam so tests can make flattening fail. +/// +/// The loaded page (an FPDF_PAGE). +/// FLAT_NORMALDISPLAY (0) or FLAT_PRINT (1). +/// FLATTEN_FAIL (0), FLATTEN_SUCCESS (1) or FLATTEN_NOTHINGTODO (2). +internal delegate int PageFlattener(IntPtr page, int usage); + +/// +/// Copies pages of a document, in one call, to a new position in the same document (PDFium's +/// FPDF_ImportPagesByIndex, with the document as both source and destination, in production). A seam so +/// tests can make copying fail, change the copies or count the calls. +/// +/// The document (an FPDF_DOCUMENT); the pages are copied within it. +/// The pages to copy, in the order their copies are wanted. +/// Where the first copy goes, the others following it. PDFStream.NET passes the current +/// page count, which appends them. +/// when PDFium made the copies. +internal delegate bool PageCopier(IntPtr document, int[] pageIndices, int insertAt); + +/// How prepared a page for printing the first time it was drawn. +internal enum PagePreparation +{ + /// The page has no form fields; it is drawn exactly as PDFium draws it. + NoFormFields, + + /// The page's fields were flattened into a copy of the page, which is drawn in its place. + Copy, + + /// + /// The copy could not be used, so the fields were flattened into the page itself. A page that inherits its + /// /Resources from the page tree loses what it draws through them (the documented limitation). + /// + InPlace, + + /// The fields could not be flattened at all; the page is drawn as it is, its fields blank. + DrawnAsItIs, +} + +/// +/// Why a page with form fields was not printed from its copy ( or +/// ); when it was, or when it has no fields. +/// +internal enum CopyRejection +{ + /// Nothing was rejected: the copy was used, or the page has no form fields. + None, + + /// No copy was made: the PDF is larger than the copy budget. + OverBudget, + + /// No copy of this page was made: it was not among the pages planned when the one copy was made. + NotPlanned, + + /// No copy was made: the copy function failed or threw (for example, missing from pdfium.dll). + CopyFailed, + + /// The copy is not exactly the size of the page. + SizeDiffers, + + /// The copy could not be loaded. + CopyNotLoaded, + + /// The copy carries fewer or more annotations than the page (a damaged reference drops them all). + AnnotationsLost, + + /// The copy and the page draw differently (layers are the known cause), or they could not be compared. + LooksDifferent, + + /// Flattening the copy failed or changed its size. + FlattenFailed, + + /// Form handling itself failed before any copy was looked at (no form-fill environment, or an error). + FormHandlingFailed, +} + +/// +/// A PDF opened by PDFium. Every native call is made while holding +/// , so the document can be used from several threads. +/// +/// +/// +/// Form fields. PDFium's two page-drawing calls never draw form fields (widget annotations), so a filled-in +/// form would print blank. PDFStream.NET therefore prepares the pages with form fields inside its own in-memory +/// copy of the PDF (the caller's file or bytes are never changed): +/// +/// +/// The first time a page with fields is drawn, the pages about to be drawn (those named by +/// , or every page) are looked at once to find the ones with fields. For each of them the +/// document's form-fill environment builds the appearances that are not stored in the file (an annotation without +/// one, or every field when the form says /NeedAppearances), so nothing that PDFium would draw on the fly is lost +/// when the annotations become page content. +/// All those pages are copied to the end of the in-memory document in one call +/// (FPDF_ImportPagesByIndex with the document as both source and destination). Each copy carries, written +/// on itself, what its page inherits from the page tree (MediaBox, CropBox, Rotate and Resources), and the copies +/// get their own copies of the objects the pages use. Because it is one call, an object that several pages share +/// (one /Resources dictionary for the whole document and its images, for example) is copied once, not once per +/// page. The copy is made at most once per document, and only when the PDF is no larger than the copy budget +/// (). The pages themselves are not flattened if it can be avoided: flattening +/// adds its result to the page's own /Resources, creating an empty one when the page inherits them, and that empty +/// dictionary hides the inherited fonts, images and XObjects, so the page content that uses them would disappear +/// from the paper. +/// When a page with fields is drawn for the first time, its copy is checked. It must carry as many +/// annotations as the page (PDFium's copy drops a whole annotation list when one entry cannot be resolved), and +/// the copy and the page are drawn small and compared (within a fixed pixel budget; a page too odd in size or +/// shape to compare counts as not verified). The copy is used only if it draws exactly the same pixels. It does +/// not when something on the page depends on which object it refers to rather than on what the object contains; +/// optional content (layers) is the known case, because the document's layer settings name the page's layer +/// objects, not the copy's, so a layer the PDF switches off would show on the copy. +/// The visible box of the copy is written onto it as its CropBox (flattening rewrites the MediaBox and the +/// CropBox from the page's own entries), and FPDFPage_Flatten with FLAT_PRINT draws every annotation +/// marked for printing into its content (fields not marked for printing are left out, as on paper). +/// +/// +/// A page whose copy cannot be used for any reason has its fields flattened into the page itself instead, as +/// before the copy was introduced. No copy is made for a PDF over the budget, for a page outside the planned +/// ones, or when the copy function fails or is missing from pdfium.dll; a copy is not used when it is not +/// exactly the page's size, lost annotations, draws differently or could not be flattened. Flattening into the +/// page keeps its layers right; a page that also inherits its /Resources loses what it draws through them, which +/// is the documented limitation. Only when that fails too is the page drawn as it is (its fields blank, as +/// before form fields were handled), so preparing a page never makes a print fail. +/// +/// +/// From then on the copy (or the flattened page) is drawn for the page, through the vector path as before, +/// fields included. The copies lie after the last page the document reports, so no page index reaches them: +/// and the page sizes stay those of the PDF. Documents without form fields are never +/// touched. The cost falls on documents with fields only: every planned page is read once more to find the +/// fields, each page with fields is drawn twice at low resolution for the comparison and read once more, and the +/// copies hold one copy of the objects those pages refer to (their raw data, at most what the PDF file holds) +/// until the document is closed. One thing is still repeated per page: an attribute a page inherits as a direct +/// value (a /Resources dictionary written inline on the /Pages node, for example) is cloned onto every copy, so +/// its parsed size counts once per page with fields (see , which does not +/// bound it); such dictionaries normally hold only a few references. XFA-only forms have no fields of this kind +/// and still print only their page content; the bundled PDFium is built without XFA. +/// +/// +/// KNOWN LIMITATION (three or more form pages that share one indirect /Contents array). The copies, made in one +/// import call, share the cloned content array, and PDFium's flatten edits that array in place and names its +/// drawing after the first free /FFTn in the shared /XObject dictionary. So the second page's copy also draws +/// the first page's field. The pixel comparison catches that first contaminated copy (when the fields leave ink) +/// and the page takes the in-place fallback, but that flattens the page's ORIGINAL content array, which is +/// shared with the other original pages: from the third page on, the original and the copy differ as well, so +/// those pages also go in place and keep the drawing of the second page. The result is that later pages also +/// print the fields of earlier pages (page 3 shows page 2's field, page 4 shows the fields of pages 2 and 3), +/// with status Ok. It needs a PDF whose form pages share one indirect /Contents array and one indirect +/// /Resources dictionary, which is rare. Fixing it needs private objects per copy (one import call per page), +/// which brings back the memory growth the single call avoids, and PDFium has no call to unshare the array. It is +/// pinned by a characterization test (the one with Known_limitation in its name in FormFieldRenderingTests): +/// whoever fixes this must change that test and the limitation text in the documentation. +/// +/// +internal sealed class PdfiumDocument : IPdfDocument +{ + /// A page whose form fields have not been looked at yet (see ). + private const int NotPrepared = -1; + + /// The index returns when the loaded page is drawn as it is. + private const int DrawAsItIs = -1; + + /// The copy index of a page that has no copy (see ). + private const int NoCopy = -1; + + /// The resolution at which a page and its copy are drawn to check that they look the same. + private const int ComparisonDpi = 72; + + /// The most pixels either comparison drawing may have; larger pages are compared at a lower resolution. + internal const int ComparisonMaxPixels = 1_000_000; + + /// The most pixels either side of a comparison drawing may have, whatever the shape of the page. + internal const int ComparisonMaxSide = 4096; + + /// The most bytes one comparison drawing may take (four per pixel, within the pixel budget). + private const long ComparisonMaxBytes = 4L * ComparisonMaxPixels; + + /// + /// The copy budget: the largest PDF, in bytes (64 MB), whose pages with form fields are copied before their + /// fields are flattened. A larger PDF has the fields of every page flattened into the page itself. + /// + /// + /// + /// PDFium cannot say how much its page copy takes, so the size of the PDF stands in for it. What it bounds is + /// the copy of the objects the copied pages refer to (fonts, images, content streams, annotations): the one + /// copy holds their raw, still compressed data once, which cannot be more than the file holds. The limit + /// applies per document, so concurrent prints each have their own; forms and labels are almost always far + /// smaller than 64 MB. Going over it costs little: flattening into the page itself is exactly right for a page + /// that carries its own resources, and only a page that inherits them from the page tree loses what it draws + /// through them. + /// + /// + /// What it does not bound: a value a page inherits directly (written inline on a /Pages node rather than as a + /// separate object, typically a /Resources dictionary) is cloned onto the copy of every page with fields, in + /// PDFium's parsed form, which takes far more memory than its text. Normally such a dictionary holds only a + /// few references and costs a few kilobytes per page. A deliberately inflated one does not: measured with the + /// bundled build on x64, an inline array of 100,000 numbers (195 KB of text) inherited by 100 pages with + /// fields, in a 1.2 MB PDF, grew private memory by about 600 MB while the pages were drawn. + /// + /// + internal const long DefaultCopyBudgetBytes = 64L * 1024 * 1024; + + private readonly PdfiumDocumentHandle _handle; + private readonly PageFlattener _flattenPage; + private readonly PageCopier _copyPage; + + // For each page the caller can see, which page of PDFium's document is drawn for it: NotPrepared until the + // page is first drawn, then the page itself, or the index of its printable copy when it has form fields. + // Read and written only while holding PdfiumLibrary.Sync, so the work is done once per page however often + // and from however many threads the page is drawn (copies, the bitmap fallback). + private readonly int[] _drawnFrom; + + // For each page, the index of its unflattened copy once the one copy of the pages with fields has been made, + // or NoCopy. Read and written only while holding PdfiumLibrary.Sync. + private readonly int[] _copyOf; + + // For each page, whether the form-fill environment has already built its missing appearances. Read and + // written only while holding PdfiumLibrary.Sync. + private readonly bool[] _appearancesBuilt; + + // The size of the PDF, which stands in for the cost of the copy (see DefaultCopyBudgetBytes). + private readonly long _sourceLength; + + // The pages PlanToDraw named (null: every page), and whether the one copy has been attempted. Read and + // written only while holding PdfiumLibrary.Sync. + private int[]? _plannedPages; + private bool _copyAttempted; + + // What became of the one copy, for the reason a page without a copy reports. Read and written only while + // holding PdfiumLibrary.Sync. + private CopyOutcome _copyOutcome = CopyOutcome.NotAttempted; + + /// + /// Wraps an open handle. The caller must hold , because the page + /// count is read from PDFium here, once, instead of on every access. + /// + /// The open document; this object takes ownership of it. + /// How a page's annotations are flattened; uses + /// PDFium's FPDFPage_Flatten. Tests pass one that fails. + /// How the pages with form fields are copied within the document, in one call, before + /// they are flattened; uses PDFium's FPDF_ImportPagesByIndex. Tests pass one that + /// fails, changes the copies or counts the calls. + internal PdfiumDocument(PdfiumDocumentHandle handle, PageFlattener? flattenPage = null, PageCopier? copyPage = null) + { + _handle = handle; + _flattenPage = flattenPage ?? PdfiumNative.FPDFPage_Flatten; + _copyPage = copyPage ?? CopyWithinDocument; + + // Read once: the printable copies of form pages are added after the last page, and must never become + // visible as extra pages. + PageCount = PdfiumNative.FPDF_GetPageCount(handle.DangerousGetHandle()); + _drawnFrom = new int[Math.Max(0, PageCount)]; + Array.Fill(_drawnFrom, NotPrepared); + _copyOf = new int[_drawnFrom.Length]; + Array.Fill(_copyOf, NoCopy); + _appearancesBuilt = new bool[_drawnFrom.Length]; + _sourceLength = handle.SourceLength; + } + + /// + public int PageCount { get; } + + /// + /// Test hook: called with the pixel width and height of every picture drawn to compare a form page with its + /// copy, just before it is drawn, while the PDFium lock is held. Lets a test check that the comparison never + /// draws more than its budget, whatever the page size. (the default) in production. + /// + internal Action? ComparisonRendered { get; set; } + + /// + /// The copy budget of this document in bytes: unless a test lowers it to + /// see what happens to a PDF over the budget. Set it before the first page is drawn. + /// + internal long CopyBudgetBytes { get; set; } = DefaultCopyBudgetBytes; + + /// + /// Test hook: called once for every page, the first time it is drawn, with how it was prepared and, for a page + /// with form fields that was not printed from its copy, why. Called while the PDFium lock is held, so it must + /// not call back into the document. (the default) in production. + /// + internal Action? PagePrepared { get; set; } + + /// + /// + /// Only the first call before the pages with form fields are prepared counts: those pages are found among + /// the planned ones (instead of among every page of the PDF) and copied together. Nothing is read from the PDF + /// here, so a document without form fields costs nothing. + /// + public void PlanToDraw(IReadOnlyList pageIndices) + { + if (pageIndices is null) + { + return; + } + + lock (PdfiumLibrary.Sync) + { + if (_copyAttempted || _plannedPages is not null) + { + return; + } + + // In the order given, each page once, and only pages that exist. + var seen = new HashSet(); + var planned = new List(pageIndices.Count); + foreach (int index in pageIndices) + { + if ((uint)index < (uint)PageCount && seen.Add(index)) + { + planned.Add(index); + } + } + + _plannedPages = [.. planned]; + } + } + + /// + public SizeF GetPageSizePoints(int pageIndex) + { + ValidatePageIndex(pageIndex); + + lock (PdfiumLibrary.Sync) + { + return UseHandle(document => + { + if (PdfiumNative.FPDF_GetPageSizeByIndexF(document, pageIndex, out PdfiumNative.FsSizeF size) == 0) + { + throw new InvalidOperationException($"PDFium could not read the size of page {pageIndex + 1}."); + } + + return new SizeF(size.Width, size.Height); + }); + } + } + + /// + public void RenderToDeviceContext(int pageIndex, IntPtr hdc, Rectangle destinationPixels, bool forPrinting, int quarterTurns) + { + ValidatePageIndex(pageIndex); + ValidateQuarterTurns(quarterTurns); + if (hdc == IntPtr.Zero) + { + throw new ArgumentException("A device context is required.", nameof(hdc)); + } + + if (destinationPixels.Width <= 0 || destinationPixels.Height <= 0) + { + throw new ArgumentOutOfRangeException(nameof(destinationPixels), destinationPixels, "The destination rectangle must have a positive width and height."); + } + + int flags = PdfiumNative.RenderAnnotations | (forPrinting ? PdfiumNative.RenderForPrinting : 0); + + lock (PdfiumLibrary.Sync) + { + WithPage(pageIndex, page => + { + // PDFium adds the page's own /Rotate to this rotation itself, so quarterTurns is + // relative to the page as it is displayed (0 draws it exactly as a viewer shows it). + int rendered = PdfiumNative.FPDF_RenderPage( + hdc, + page, + destinationPixels.X, + destinationPixels.Y, + destinationPixels.Width, + destinationPixels.Height, + quarterTurns, + flags); + if (rendered == 0) + { + throw new InvalidOperationException($"PDFium could not draw page {pageIndex + 1} on the device context."); + } + }); + } + } + + /// + /// + /// The page is rendered with the printing flag. In PDFStream.NET a page bitmap is only ever the + /// fallback for a printer that refuses device-context rendering (or a check of printed + /// output), so it must look exactly like the device-context path with + /// forPrinting: true. + /// + public Bitmap RenderToBitmap(int pageIndex, int dpi, int quarterTurns) + { + ValidatePageIndex(pageIndex); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(dpi); + ValidateQuarterTurns(quarterTurns); + + // A quarter turn either way lays the page on its side, so the bitmap swaps width and height. + SizeF sizePoints = GetPageSizePoints(pageIndex); + bool sideways = quarterTurns % 2 == 1; + int width = ToPixels(sideways ? sizePoints.Height : sizePoints.Width, dpi); + int height = ToPixels(sideways ? sizePoints.Width : sizePoints.Height, dpi); + + var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + try + { + bitmap.SetResolution(dpi, dpi); + BitmapData pixels = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + lock (PdfiumLibrary.Sync) + { + WithPage(pageIndex, page => RenderInto(page, pixels, pageIndex, quarterTurns)); + } + } + finally + { + bitmap.UnlockBits(pixels); + } + + return bitmap; + } + catch + { + bitmap.Dispose(); + throw; + } + } + + /// Closes the document and frees its native memory. Safe to call more than once. + public void Dispose() => _handle.Dispose(); + + /// Converts a length in points to whole pixels at , never less than one. + private static int ToPixels(float points, int dpi) + { + double pixels = Math.Round(points * dpi / 72.0, MidpointRounding.AwayFromZero); + if (pixels > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(dpi), dpi, "The page is too large to render at this resolution."); + } + + return Math.Max(1, (int)pixels); + } + + /// + /// Points PDFium at the locked GDI+ pixels, paints them white and renders the page into them. + /// Must be called while holding . + /// + private static void RenderInto(IntPtr page, BitmapData pixels, int pageIndex, int quarterTurns) + { + // PDFium draws straight into the GDI+ bitmap's memory (same BGRA layout), so no pixel copy + // is needed. Destroying the PDFium bitmap afterwards leaves that memory untouched. + IntPtr pdfBitmap = PdfiumNative.FPDFBitmap_CreateEx(pixels.Width, pixels.Height, PdfiumNative.BitmapFormatBgra, pixels.Scan0, pixels.Stride); + if (pdfBitmap == IntPtr.Zero) + { + throw new InvalidOperationException($"PDFium could not create a {pixels.Width} x {pixels.Height} bitmap for page {pageIndex + 1}."); + } + + try + { + // PDF pages have no background of their own: without white paper underneath, every + // area the page does not paint would stay transparent black. + PdfiumNative.FPDFBitmap_FillRect(pdfBitmap, 0, 0, pixels.Width, pixels.Height, PdfiumNative.ColorWhite); + PdfiumNative.FPDF_RenderPageBitmap( + pdfBitmap, + page, + 0, + 0, + pixels.Width, + pixels.Height, + quarterTurns, + PdfiumNative.RenderAnnotations | PdfiumNative.RenderForPrinting); + } + finally + { + PdfiumNative.FPDFBitmap_Destroy(pdfBitmap); + } + } + + /// + /// Loads what is drawn for a page (the page itself, or its printable copy once it has one), prepares the + /// page the first time it is drawn (see the class remarks), runs on it and always + /// closes it again. Must be called while holding . + /// + private void WithPage(int pageIndex, Action action) + { + UseHandle(document => + { + bool firstDraw = _drawnFrom[pageIndex] == NotPrepared; + IntPtr page = LoadPage(document, firstDraw ? pageIndex : _drawnFrom[pageIndex], pageIndex); + try + { + if (firstDraw) + { + // Marked before the work, so a page whose preparation fails is drawn as it is and not + // tried again on every copy. + _drawnFrom[pageIndex] = pageIndex; + + // The page loaded above serves the form-field check, so a page without fields is loaded + // and parsed only once, as before form fields were handled. + (int drawFrom, PagePreparation how, CopyRejection why) = TryPrepareForPrinting(document, pageIndex, page); + PagePrepared?.Invoke(pageIndex, how, why); + // If this reload fails (the flattened page or copy cannot be loaded again), the unflattened + // page loaded above is drawn: its form fields stay blank and the print still reports Ok. + // That is accepted: it is practically unreachable, because the same index was loaded + // moments ago under the same lock, and a blank-fields page is what printing did before form + // fields were handled at all, so preparing a page never makes a print fail. + IntPtr prepared = drawFrom == DrawAsItIs ? IntPtr.Zero : PdfiumNative.FPDF_LoadPage(document, drawFrom); + if (prepared != IntPtr.Zero) + { + _drawnFrom[pageIndex] = drawFrom; + PdfiumNative.FPDF_ClosePage(page); + page = prepared; + } + } + + action(page); + } + finally + { + PdfiumNative.FPDF_ClosePage(page); + } + + return 0; + }); + } + + /// Loads a page or throws the engine's documented "could not draw" exception. + /// The document. + /// The page of PDFium's document to load: the page itself or its printable copy. + /// The page the caller asked for, which is the one the message names. + private static IntPtr LoadPage(IntPtr document, int index, int pageIndex) + { + IntPtr page = PdfiumNative.FPDF_LoadPage(document, index); + if (page == IntPtr.Zero) + { + throw new InvalidOperationException($"PDFium could not load page {pageIndex + 1}; the page may be damaged."); + } + + return page; + } + + /// + /// If the page has form fields, makes every annotation marked for printing part of the content that is drawn + /// for the page: in a copy of the page at the end of the document when the copy can be used, otherwise in the + /// page itself (see the class remarks for the steps and why each is needed). Must be called while holding + /// and a reference on the handle. Never throws. + /// + /// The document. + /// The page to prepare. + /// The page, loaded. It is not closed here, and is drawn as it is when this fails. + /// + /// How the page was prepared, why it was not printed from its copy (if it was not), and the page of PDFium's + /// document to draw for it from now on: the printable copy, or the page itself when its fields were flattened + /// into it (load it again: the loaded page still holds the old content). For + /// and the index is + /// : the loaded page is drawn as it is. + /// + private (int DrawFrom, PagePreparation How, CopyRejection Why) TryPrepareForPrinting(IntPtr document, int pageIndex, IntPtr page) + { + try + { + // Only pages that really carry form fields are prepared: every other page is drawn exactly as + // PDFium draws it. Checked per page, not from the catalog's /AcroForm, because pages copied out of + // a form by another tool often keep their fields but lose /AcroForm. + if (!HasFormFields(page)) + { + return (DrawAsItIs, PagePreparation.NoFormFields, CopyRejection.None); + } + + IntPtr environment = _handle.GetOrCreateFormFillEnvironment(); + if (environment == IntPtr.Zero) + { + // Without the form-fill module, annotations whose appearance PDFium builds only while drawing + // would be dropped by flattening. Drawing the page as it is loses only the fields. + return (DrawAsItIs, PagePreparation.DrawnAsItIs, CopyRejection.FormHandlingFailed); + } + + // The first page with fields makes the one copy of all the planned pages with fields, building their + // appearances first. A page whose appearances were not built then (it was not planned, or the PDF is + // over the copy budget) gets them now, before its fields are flattened into the page itself. + EnsureCopies(document, environment); + BuildAppearances(pageIndex, page, environment); + } + catch (Exception) + { + // Preparing a page is an improvement, never a requirement: if even the check for fields fails (for + // example a pdfium.dll without one of these functions), the page is drawn as it is. + return (DrawAsItIs, PagePreparation.DrawnAsItIs, CopyRejection.FormHandlingFailed); + } + + int copyIndex = _copyOf[pageIndex]; + CopyRejection why = copyIndex == NoCopy + ? _copyOutcome switch + { + CopyOutcome.OverBudget => CopyRejection.OverBudget, + CopyOutcome.Failed => CopyRejection.CopyFailed, + + // The one copy was made (or found no pages with fields to copy) without this page. + _ => CopyRejection.NotPlanned, + } + : TryFlattenCopy(document, pageIndex, page, copyIndex); + if (why == CopyRejection.None) + { + return (copyIndex, PagePreparation.Copy, CopyRejection.None); + } + + // There is no copy (over the budget, a page that was not planned, a copy that failed or a pdfium.dll + // without the copy function), or it cannot be used (the known cause is optional content, see the class + // remarks; others are a copy that lost annotations, a copy of another size or a failed flatten). + // Flatten the fields into the page itself instead, as before the copy was introduced: the fields print, + // the layers stay right, and only a page that also inherits its /Resources loses what it draws through + // them. Drawing the page as it is, with its fields blank, is left for a page whose fields cannot be + // flattened at all. + return TryFlattenInPlace(page) ? (pageIndex, PagePreparation.InPlace, why) : (DrawAsItIs, PagePreparation.DrawnAsItIs, why); + } + + /// + /// Makes, at most once per document, the one copy of the planned pages that have form fields: finds them, + /// builds their missing appearances (which the copies must carry), and copies them all to the end of the + /// document in one call, so that what they share is copied once. Nothing is copied when the PDF is over the + /// copy budget. Must be called while holding and a reference on the handle. + /// Never throws: whatever fails leaves the pages without copies, and they take the fallback. + /// + /// The document. + /// The document's form-fill environment. + private void EnsureCopies(IntPtr document, IntPtr environment) + { + if (_copyAttempted) + { + return; + } + + _copyAttempted = true; + _copyOutcome = CopyOutcome.Failed; + try + { + // Checked before anything is read: over the budget, no page is copied, and nothing needs finding. + if (_sourceLength > CopyBudgetBytes) + { + _copyOutcome = CopyOutcome.OverBudget; + return; + } + + var formPages = new List(); + foreach (int index in _plannedPages ?? Enumerable.Range(0, PageCount)) + { + IntPtr candidate = PdfiumNative.FPDF_LoadPage(document, index); + if (candidate == IntPtr.Zero) + { + // A page PDFium cannot load is not copied; drawing it reports the damage as before. + continue; + } + + try + { + if (HasFormFields(candidate)) + { + BuildAppearances(index, candidate, environment); + formPages.Add(index); + } + } + finally + { + PdfiumNative.FPDF_ClosePage(candidate); + } + } + + if (formPages.Count == 0) + { + _copyOutcome = CopyOutcome.NoPagesWithFields; + return; + } + + // The copies go after every page there is, so none can take the place of a page the caller sees + // (PageCount was read when the document was opened and does not change). One call, one object map + // inside PDFium: an object several of these pages refer to is copied once and shared by their copies. + int firstCopy = PdfiumNative.FPDF_GetPageCount(document); + int[] pages = [.. formPages]; + if (!_copyPage(document, pages, firstCopy) + || PdfiumNative.FPDF_GetPageCount(document) != firstCopy + pages.Length) + { + return; + } + + for (int k = 0; k < pages.Length; k++) + { + _copyOf[pages[k]] = firstCopy + k; + } + + _copyOutcome = CopyOutcome.Made; + } + catch (Exception) + { + // For example a pdfium.dll without FPDF_ImportPagesByIndex (an experimental PDFium function): every + // page with fields then has them flattened into the page itself. + } + } + + /// + /// Has the form-fill environment build the appearances of the page's annotations that are missing from the + /// file, once per page, and stores them in the annotations (showing the page to the module and taking it away + /// again; nothing else of the module is used). Must be called while holding . + /// + /// The page. + /// The page, loaded. + /// The document's form-fill environment. + private void BuildAppearances(int pageIndex, IntPtr page, IntPtr environment) + { + if (_appearancesBuilt[pageIndex]) + { + return; + } + + PdfiumNative.FORM_OnAfterLoadPage(page, environment); + PdfiumNative.FORM_OnBeforeClosePage(page, environment); + _appearancesBuilt[pageIndex] = true; + } + + /// + /// Checks that the page's copy can stand in for it, and flattens the copy's annotations for printing. Must be + /// called while holding and a reference on the handle. Never throws: every + /// failure means "the copy is not used". + /// + /// The document. + /// The page. + /// The page, loaded (it serves the comparison and the annotation count). + /// Where the page's unflattened copy is. + /// when the copy was flattened and can be drawn in place of the page; + /// otherwise why it cannot. + private CopyRejection TryFlattenCopy(IntPtr document, int pageIndex, IntPtr page, int copyIndex) + { + try + { + if (!HaveSameSize(document, pageIndex, copyIndex)) + { + return CopyRejection.SizeDiffers; + } + + IntPtr copy = PdfiumNative.FPDF_LoadPage(document, copyIndex); + if (copy == IntPtr.Zero) + { + return CopyRejection.CopyNotLoaded; + } + + int flattened; + try + { + // PDFium's page copy drops a whole /Annots array when one of its entries cannot be resolved (a + // damaged reference), leaving a copy without any fields. The pixel comparison below cannot see + // that, because it draws without the fields, so the annotations are counted first: a copy that + // does not carry every annotation of the page is not used. + if (PdfiumNative.FPDFPage_GetAnnotCount(copy) != PdfiumNative.FPDFPage_GetAnnotCount(page)) + { + return CopyRejection.AnnotationsLost; + } + + if (!CopyDrawsLikeThePage(document, page, pageIndex, copy)) + { + return CopyRejection.LooksDifferent; + } + + flattened = PinVisibleBoxAndFlatten(copy); + } + finally + { + // The copy loaded here still holds the content it parsed before flattening; the caller loads + // the copy again to draw the flattened content. + PdfiumNative.FPDF_ClosePage(copy); + } + + // The copy replaces the page only if it is still exactly the page's size: whatever is printed must + // land where the page would have. + return flattened == PdfiumNative.FlattenSuccess && HaveSameSize(document, pageIndex, copyIndex) + ? CopyRejection.None + : CopyRejection.FlattenFailed; + } + catch (Exception) + { + // Any failure on the copy path only means the copy is not used. It most likely came from flattening + // (the comparison catches its own failures), so it is reported as such. + return CopyRejection.FlattenFailed; + } + } + + /// + /// Flattens the page's annotations for printing into the page itself (the fallback when its copy cannot be + /// used). Must be called while holding . Never throws. + /// + /// The loaded page. Load it again afterwards to draw the flattened content. + /// when PDFium flattened the page. + private bool TryFlattenInPlace(IntPtr page) + { + try + { + return PinVisibleBoxAndFlatten(page) == PdfiumNative.FlattenSuccess; + } + catch (Exception) + { + // For example a pdfium.dll without FPDFPage_Flatten: the page is then drawn as it is. + return false; + } + } + + /// + /// Writes the loaded page's visible box onto it and flattens its annotations for printing. Flattening rewrites + /// the MediaBox and CropBox from the page's own entries, so an inherited box would otherwise become US Letter + /// (a copy already carries its boxes; writing the visible box as well keeps flattening from changing what + /// part of the page is shown). + /// + /// The loaded page. Load it again afterwards to draw the flattened content. + /// What the flattener returned, or FLATTEN_FAIL (0) when the box could not be read. + private int PinVisibleBoxAndFlatten(IntPtr page) + { + if (PdfiumNative.FPDF_GetPageBoundingBox(page, out PdfiumNative.FsRectF box) == 0) + { + return 0; + } + + PdfiumNative.FPDFPage_SetCropBox(page, box.Left, box.Bottom, box.Right, box.Top); + if (PdfiumNative.FPDFPage_GetMediaBox(page, out _, out _, out _, out _) == 0) + { + PdfiumNative.FPDFPage_SetMediaBox(page, box.Left, box.Bottom, box.Right, box.Top); + } + + return _flattenPage(page, PdfiumNative.FlattenForPrint); + } + + /// + /// Whether the (not yet flattened) copy of a page draws exactly the same pixels as the page itself: both are + /// rendered for printing, annotations included, at up to dpi and at most + /// pixels, and compared byte for byte. + /// + /// + /// The copy holds its own copies of the objects the page uses. That is what keeps inherited resources, but + /// anything whose meaning depends on which object it is, rather than on what it contains, changes: optional + /// content is the known case. Comparing the two drawings catches such a difference that shows when the page is + /// compared, without having to know its cause, and costs two small renders, once, for pages with form fields + /// only. It does not catch everything: see the known limitation about pages that share one content array in + /// the remarks of the class. + /// + /// The document. + /// The page, loaded. + /// The page's index, for its size. + /// The page's copy, loaded and not yet flattened. + /// + /// only when the comparison was made and the pictures are identical. Anything else (the + /// pictures differ, the page is too odd in size or shape to compare, or anything in the comparison fails) + /// is , "could not verify", and never an exception: the caller then takes its safe + /// fallback. + /// + private bool CopyDrawsLikeThePage(IntPtr document, IntPtr page, int pageIndex, IntPtr copy) + { + try + { + if (PdfiumNative.FPDF_GetPageSizeByIndexF(document, pageIndex, out PdfiumNative.FsSizeF size) == 0 + || !TryGetComparisonSize(size.Width, size.Height, out int width, out int height)) + { + return false; + } + + ComparisonRendered?.Invoke(width, height); + byte[] pagePixels = RenderForComparison(page, width, height); + ComparisonRendered?.Invoke(width, height); + return RenderForComparison(copy, width, height).AsSpan().SequenceEqual(pagePixels); + } + catch (Exception) + { + // The comparison is a safety check, not part of printing: if it cannot be made (no memory for the + // pictures, a page PDFium cannot draw, a size refused below), the copy is simply not verified. + return false; + } + } + + /// + /// The pixel size at which a page of the given size is drawn for the comparison: one pixel per point + /// (), scaled down so that neither side exceeds + /// and the area stays within . + /// + /// + /// The page size comes from the PDF, which may be damaged or hostile: a MediaBox can be enormous in one + /// direction and tiny in the other, or not a usable number at all. So the size is checked first, all the + /// arithmetic is done in , each side is clamped before the area, and the result is + /// rounded down so it can never round up over a limit. A page whose size is not finite and positive, or that + /// is so small or so long and thin that a side would be under one pixel, is not compared: its content would + /// collapse into a single row or column, which proves nothing. + /// + /// The page width in points, as PDFium reports it. + /// The page height in points, as PDFium reports it. + /// The comparison picture's width in pixels, 1 to . + /// The comparison picture's height in pixels, 1 to . + /// when the page must not be compared. + internal static bool TryGetComparisonSize(float widthPoints, float heightPoints, out int width, out int height) + { + width = 0; + height = 0; + if (!float.IsFinite(widthPoints) || !float.IsFinite(heightPoints) || widthPoints <= 0 || heightPoints <= 0) + { + return false; + } + + double scale = ComparisonDpi / 72.0; + double targetWidth = widthPoints * scale; + double targetHeight = heightPoints * scale; + + // First neither side over the cap (this alone tames a very long, thin page), then the area. + double fitSides = Math.Min(1.0, Math.Min(ComparisonMaxSide / targetWidth, ComparisonMaxSide / targetHeight)); + targetWidth *= fitSides; + targetHeight *= fitSides; + double area = targetWidth * targetHeight; + if (area > ComparisonMaxPixels) + { + double fitArea = Math.Sqrt(ComparisonMaxPixels / area); + targetWidth *= fitArea; + targetHeight *= fitArea; + } + + if (targetWidth < 1 || targetHeight < 1) + { + return false; + } + + // Both values are now between 1 and ComparisonMaxSide, so the conversions cannot overflow, and rounding + // down keeps the area within the budget. + width = Math.Min(ComparisonMaxSide, (int)Math.Floor(targetWidth)); + height = Math.Min(ComparisonMaxSide, (int)Math.Floor(targetHeight)); + return true; + } + + /// Renders a loaded page for printing onto white, into a new array of BGRA pixels. + /// The size is outside the comparison budget (a second line of + /// defence behind ). + private static byte[] RenderForComparison(IntPtr page, int width, int height) + { + // Computed in long and checked against the hard limit before anything is allocated. + long stride = (long)width * 4; + long length = stride * height; + if (width < 1 || height < 1 || width > ComparisonMaxSide || height > ComparisonMaxSide || length > ComparisonMaxBytes) + { + throw new ArgumentOutOfRangeException(nameof(width), $"A {width} x {height} comparison picture is outside the budget."); + } + + var pixels = new byte[length]; + + // Pinned only for the duration of this one render, so PDFium can draw straight into the array. + GCHandle pin = GCHandle.Alloc(pixels, GCHandleType.Pinned); + try + { + IntPtr bitmap = PdfiumNative.FPDFBitmap_CreateEx(width, height, PdfiumNative.BitmapFormatBgra, pin.AddrOfPinnedObject(), (int)stride); + if (bitmap == IntPtr.Zero) + { + throw new InvalidOperationException($"PDFium could not create a {width} x {height} bitmap to compare a page with its copy."); + } + + try + { + PdfiumNative.FPDFBitmap_FillRect(bitmap, 0, 0, width, height, PdfiumNative.ColorWhite); + PdfiumNative.FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, PdfiumNative.RenderAnnotations | PdfiumNative.RenderForPrinting); + } + finally + { + PdfiumNative.FPDFBitmap_Destroy(bitmap); + } + } + finally + { + pin.Free(); + } + + return pixels; + } + + /// + /// Copies pages within their own document with one PDFium page import, the production . + /// The import writes each page's inherited attributes onto its copy and gives the copies their own copies of + /// the objects the pages use, so what flattening changes in a copy (its resources, the appearance streams of + /// its annotations) is not shared with the pages themselves. Within the one call PDFium keeps one map from + /// original to copied objects, so an object several pages share is copied once and shared by their copies. + /// + private static bool CopyWithinDocument(IntPtr document, int[] pageIndices, int insertAt) => + PdfiumNative.FPDF_ImportPagesByIndex(document, document, pageIndices, (uint)pageIndices.Length, insertAt) != 0; + + /// Whether two pages of the document have exactly the same size as displayed (rotation included). + private static bool HaveSameSize(IntPtr document, int first, int second) => + PdfiumNative.FPDF_GetPageSizeByIndexF(document, first, out PdfiumNative.FsSizeF a) != 0 + && PdfiumNative.FPDF_GetPageSizeByIndexF(document, second, out PdfiumNative.FsSizeF b) != 0 + && a.Width == b.Width + && a.Height == b.Height; + + /// Whether the loaded page has at least one widget (form field) annotation. + private static bool HasFormFields(IntPtr page) + { + int count = PdfiumNative.FPDFPage_GetAnnotCount(page); + for (int index = 0; index < count; index++) + { + IntPtr annotation = PdfiumNative.FPDFPage_GetAnnot(page, index); + if (annotation == IntPtr.Zero) + { + continue; + } + + try + { + if (PdfiumNative.FPDFAnnot_GetSubtype(annotation) == PdfiumNative.AnnotationWidget) + { + return true; + } + } + finally + { + PdfiumNative.FPDFPage_CloseAnnot(annotation); + } + } + + return false; + } + + /// + /// Runs with the raw document pointer while holding a reference on the + /// safe handle, so a concurrent cannot close the document mid-call + /// (and a call after disposal fails cleanly with ). + /// + private T UseHandle(Func use) + { + bool added = false; + try + { + _handle.DangerousAddRef(ref added); + return use(_handle.DangerousGetHandle()); + } + finally + { + if (added) + { + _handle.DangerousRelease(); + } + } + } + + /// PDFium only knows the four quarter turns 0 to 3; anything else is a caller bug. + private static void ValidateQuarterTurns(int quarterTurns) + { + if ((uint)quarterTurns > 3) + { + throw new ArgumentOutOfRangeException(nameof(quarterTurns), quarterTurns, "Quarter turns must be 0, 1, 2 or 3."); + } + } + + /// What became of the one copy of a document's pages with form fields. + private enum CopyOutcome + { + /// No page with fields has been drawn yet. + NotAttempted, + + /// The copies were made. + Made, + + /// None of the planned pages has form fields, so nothing was copied. + NoPagesWithFields, + + /// The PDF is larger than the copy budget, so nothing was copied. + OverBudget, + + /// Copying failed (or threw), so nothing usable was copied. + Failed, + } + + private void ValidatePageIndex(int pageIndex) + { + if ((uint)pageIndex >= (uint)PageCount) + { + throw new ArgumentOutOfRangeException(nameof(pageIndex), pageIndex, $"The document has {PageCount} page(s); page indexes start at 0."); + } + } +} diff --git a/src/PDFStream.NET/Engine/PdfiumDocumentHandle.cs b/src/PDFStream.NET/Engine/PdfiumDocumentHandle.cs new file mode 100644 index 0000000..b06430a --- /dev/null +++ b/src/PDFStream.NET/Engine/PdfiumDocumentHandle.cs @@ -0,0 +1,166 @@ +using System.Runtime.InteropServices; + +namespace PDFStream.NET.Engine; + +/// +/// Owns one open PDFium document, the native copy of the PDF bytes it was loaded from and, once a page +/// with form fields has been printed, the document's form-fill environment; and releases all of them +/// exactly once: on , or by the finalizer if a caller forgot to dispose. +/// +/// +/// PDFium reads the file lazily from the buffer it was given for as long as the document is open, +/// so the buffer must outlive the document; the form-fill environment refers to the document, so it +/// must be closed before the document; and PDFium keeps a pointer to the environment's +/// FPDF_FORMFILLINFO block, so that block must outlive the environment. Keeping all of them in one +/// handle makes that ordering impossible to get wrong: environment, document, then the two blocks. +/// +internal sealed class PdfiumDocumentHandle : SafeHandle +{ + private IntPtr _buffer; + + // The form-fill environment and the zeroed FPDF_FORMFILLINFO block it was created with. Both stay + // IntPtr.Zero until GetOrCreateFormFillEnvironment is first called, which only happens for a document + // that has a page with form fields. Read and written only while holding PdfiumLibrary.Sync. + private IntPtr _formEnvironment; + private IntPtr _formFillInfo; + private bool _formEnvironmentAttempted; + + private PdfiumDocumentHandle() + : base(IntPtr.Zero, ownsHandle: true) + { + } + + /// + public override bool IsInvalid => handle == IntPtr.Zero; + + /// The size in bytes of the PDF the document was opened from (see ). + internal long SourceLength { get; private set; } + + /// + /// Copies into native memory and asks PDFium to open it. + /// The caller must hold and have initialised the library. + /// + /// The PDF file; must not be empty. + /// The password, or . + /// PDFium's FPDF_ERR_* code when the load fails; 0 on success. + /// The open document, or if PDFium could not open it. + internal static PdfiumDocumentHandle? Open(byte[] pdf, string? password, out int error) + { + // The handle object exists before any native work so that, once PDFium has returned a + // document, nothing that could throw stands between the document and its owner. + var owner = new PdfiumDocumentHandle(); + + // The bytes are copied rather than pinned: the caller keeps ownership of its array and may + // reuse it, and pinning a large managed array for the document's lifetime would fragment + // the garbage-collected heap. Rendering costs far more than this one copy. + IntPtr buffer = Marshal.AllocHGlobal(pdf.Length); + IntPtr document; + try + { + Marshal.Copy(pdf, 0, buffer, pdf.Length); + document = PdfiumNative.FPDF_LoadMemDocument64(buffer, (nuint)pdf.Length, password); + error = document == IntPtr.Zero ? Marshal.GetLastPInvokeError() : 0; + } + catch + { + Marshal.FreeHGlobal(buffer); + owner.SetHandleAsInvalid(); + throw; + } + + if (document == IntPtr.Zero) + { + Marshal.FreeHGlobal(buffer); + + // Nothing to release: mark the unused handle as closed so its finalizer has no work. + owner.SetHandleAsInvalid(); + return null; + } + + owner._buffer = buffer; + owner.SourceLength = pdf.Length; + owner.SetHandle(document); + return owner; + } + + /// + /// Returns the document's form-fill environment, creating it the first time it is asked for. PDFium's + /// form-fill module builds the appearance of fields (and of other annotations) that have none stored, + /// which flattening needs; see . + /// + /// + /// The caller must hold and a reference on this handle (so the document + /// cannot be closed meanwhile). The environment is created with every host callback left empty and no + /// JavaScript platform: PDFium checks each callback for null before calling it, so the module never + /// calls back into the program, never runs a script and never performs an action such as opening a link. + /// Creation is attempted once; if PDFium refuses, the answer stays . + /// + /// The environment, or when PDFium could not create one. + internal IntPtr GetOrCreateFormFillEnvironment() + { + if (_formEnvironmentAttempted) + { + return _formEnvironment; + } + + _formEnvironmentAttempted = true; + + int size = PdfiumNative.FormFillInfoSlots * IntPtr.Size; + IntPtr info = Marshal.AllocHGlobal(size); + IntPtr environment; + try + { + // Every byte zero (no callbacks, no JavaScript platform), then the version in the first member. + Marshal.Copy(new byte[size], 0, info, size); + Marshal.WriteInt32(info, 0, PdfiumNative.FormFillInfoVersion); + environment = PdfiumNative.FPDFDOC_InitFormFillEnvironment(handle, info); + } + catch + { + Marshal.FreeHGlobal(info); + throw; + } + + if (environment == IntPtr.Zero) + { + Marshal.FreeHGlobal(info); + return IntPtr.Zero; + } + + // From here on ReleaseHandle owns both and frees them in the right order. + _formFillInfo = info; + _formEnvironment = environment; + return environment; + } + + /// + protected override bool ReleaseHandle() + { + // This can run on the finalizer thread, so it takes the same lock as every other PDFium + // call. It may wait for a render on another thread to finish; that is the price of PDFium + // not being thread-safe, and far better than a crash. + lock (PdfiumLibrary.Sync) + { + // The form-fill environment refers to the document, so it is closed first. + if (_formEnvironment != IntPtr.Zero) + { + PdfiumNative.FPDFDOC_ExitFormFillEnvironment(_formEnvironment); + _formEnvironment = IntPtr.Zero; + } + + PdfiumNative.FPDF_CloseDocument(handle); + } + + // PDFium kept a pointer to the FPDF_FORMFILLINFO block until the environment was closed, and read + // the PDF from the buffer until the document was closed; only now may both go. + if (_formFillInfo != IntPtr.Zero) + { + Marshal.FreeHGlobal(_formFillInfo); + _formFillInfo = IntPtr.Zero; + } + + Marshal.FreeHGlobal(_buffer); + _buffer = IntPtr.Zero; + return true; + } +} diff --git a/src/PDFStream.NET/Engine/PdfiumEngine.cs b/src/PDFStream.NET/Engine/PdfiumEngine.cs new file mode 100644 index 0000000..5224bb2 --- /dev/null +++ b/src/PDFStream.NET/Engine/PdfiumEngine.cs @@ -0,0 +1,91 @@ +namespace PDFStream.NET.Engine; + +/// +/// The PDFium implementation of . Holds no state of its own beyond its settings and +/// is safe to share: all PDFium state is process-wide and guarded by . +/// +internal sealed class PdfiumEngine : IPdfEngine +{ + private readonly PageFlattener? _flattenPage; + private readonly PageCopier? _copyPage; + + /// Creates the engine. + /// How the documents it opens flatten a page with form fields (or its copy); + /// (the default, and what PDFStream.NET uses) means PDFium's own FPDFPage_Flatten. + /// Tests pass one that fails, to show that a page that cannot be flattened still prints. + /// How the documents it opens copy their pages with form fields, in one call, before + /// flattening them; (the default, and what PDFStream.NET uses) means PDFium's own + /// FPDF_ImportPagesByIndex. Tests pass one that fails, to show that such pages still print, or one that + /// counts the calls. + internal PdfiumEngine(PageFlattener? flattenPage = null, PageCopier? copyPage = null) + { + _flattenPage = flattenPage; + _copyPage = copyPage; + } + + /// + /// + /// A or empty array returns without + /// calling PDFium. Owner-only protected PDFs (restrictions but no open password) open without + /// a password; their restrictions are not enforced, and a password supplied for such a PDF is + /// ignored rather than rejected. + /// + /// pdfium.dll for this processor architecture is missing. + public PdfLoadStatus TryLoad(byte[] pdf, string? password, out IPdfDocument? document) + { + document = null; + if (pdf is null || pdf.Length == 0) + { + return PdfLoadStatus.Invalid; + } + + lock (PdfiumLibrary.Sync) + { + PdfiumLibrary.EnsureInitialized(); + + PdfiumDocumentHandle? handle = PdfiumDocumentHandle.Open(pdf, password, out int error); + + // A PDF with only an owner password opens without any password, but PDFium reports a + // password error when a password that does not match is supplied. A caller that + // always passes a password (for example a print agent with one setting for all jobs) + // must not fail on such a file, so try once more with no password before concluding + // that the password is wrong. + if (handle is null && error == PdfiumNative.ErrorPassword && !string.IsNullOrEmpty(password)) + { + handle = PdfiumDocumentHandle.Open(pdf, null, out error); + } + + if (handle is null) + { + return MapLoadError(error, password); + } + + try + { + document = new PdfiumDocument(handle, _flattenPage, _copyPage); + } + catch + { + handle.Dispose(); + throw; + } + + return PdfLoadStatus.Ok; + } + } + + /// Turns PDFium's FPDF_ERR_* load error into a . + private static PdfLoadStatus MapLoadError(int error, string? password) + { + // PDFium uses one code for "password needed" and "password wrong". Which one it was + // depends only on whether the caller actually supplied a password. + if (error == PdfiumNative.ErrorPassword) + { + return string.IsNullOrEmpty(password) ? PdfLoadStatus.PasswordRequired : PdfLoadStatus.PasswordInvalid; + } + + // Format, file, unknown and unsupported-security errors all mean the same to a caller: + // this PDF cannot be opened. + return PdfLoadStatus.Invalid; + } +} diff --git a/src/PDFStream.NET/Engine/PdfiumLibrary.cs b/src/PDFStream.NET/Engine/PdfiumLibrary.cs new file mode 100644 index 0000000..1b6d153 --- /dev/null +++ b/src/PDFStream.NET/Engine/PdfiumLibrary.cs @@ -0,0 +1,47 @@ +using System.Diagnostics; + +namespace PDFStream.NET.Engine; + +/// +/// Process-wide PDFium state: the single lock every native call is made under, and one-time +/// library initialisation. +/// +/// +/// PDFium is not thread-safe: two threads inside it at once, even on different documents, can +/// corrupt its shared caches and crash the process. So there is exactly one lock for the whole +/// process, and documents serialise all their work through it. Callers on several threads are +/// safe; they simply take turns. +/// +internal static class PdfiumLibrary +{ + /// + /// The lock that must be held around every call into PDFium, including initialisation, + /// page open and close, rendering and closing a document (also from a finalizer). + /// + internal static readonly object Sync = new(); + + // Written and read only while holding Sync, so it needs no volatile or interlocked access. + private static bool s_initialized; + + /// + /// Initialises PDFium the first time it is needed. The caller must already hold . + /// + /// + /// PDFium is deliberately never shut down (FPDF_DestroyLibrary). Documents can still be + /// closed late by the finalizer thread, and closing a document after the library is destroyed + /// would crash; the operating system reclaims everything when the process exits. + /// + /// pdfium.dll for this processor architecture is missing. + internal static void EnsureInitialized() + { + Debug.Assert(Monitor.IsEntered(Sync), "PDFium must only be initialised while holding PdfiumLibrary.Sync."); + + if (s_initialized) + { + return; + } + + PdfiumNative.FPDF_InitLibrary(); + s_initialized = true; + } +} diff --git a/src/PDFStream.NET/Engine/PdfiumNative.cs b/src/PDFStream.NET/Engine/PdfiumNative.cs new file mode 100644 index 0000000..5bc9f0c --- /dev/null +++ b/src/PDFStream.NET/Engine/PdfiumNative.cs @@ -0,0 +1,270 @@ +using System.Runtime.InteropServices; + +namespace PDFStream.NET.Engine; + +/// +/// P/Invoke declarations for the handful of PDFium functions PDFStream.NET uses, written from the +/// public PDFium headers (fpdfview.h, fpdf_formfill.h, fpdf_flatten.h, +/// fpdf_annot.h, fpdf_transformpage.h and fpdf_ppo.h, BSD-3-Clause) of the bundled build. +/// +/// +/// +/// Never call these directly from outside the engine: PDFium is not thread-safe, and every call +/// must be made while holding . +/// +/// +/// Calling convention: FPDF_CALLCONV only becomes __stdcall when PDFium is built +/// with FPDFSDK_EXPORTS, which the bundled build is not. Disassembly of the win-x86 +/// pdfium.dll confirms plain ret (caller clean-up) and undecorated export names, +/// i.e. cdecl. Cdecl is therefore stated explicitly: the .NET default on x86 is stdcall, and a +/// mismatch would corrupt the stack on 32-bit processes only. On x64 and arm64 there is a single +/// calling convention and the setting is ignored. +/// +/// +internal static class PdfiumNative +{ + /// + /// Base name of the native library. The .NET host finds runtimes/<rid>/native/pdfium.dll + /// for the architecture of the running process. + /// + private const string Library = "pdfium"; + + /// FPDF_ERR_PASSWORD: password required, or the password given is wrong. + public const int ErrorPassword = 4; + + /// + /// FPDF_ANNOT: draw the page's annotations that have an appearance (stamps, comments, shapes). + /// It does NOT draw form fields: PDFium's two page-drawing calls ( and + /// ) never draw widget annotations, whatever the flags. Only the + /// form-fill module's own drawing call (which draws only into a bitmap) or flattening the fields into the + /// page content does; flattens them into a copy of the page, or into the page + /// itself (see its remarks). + /// + public const int RenderAnnotations = 0x01; + + /// FPDF_PRINTING: render for printing (honours the annotations' print flags). + public const int RenderForPrinting = 0x800; + + /// FPDFBitmap_BGRA: 4 bytes per pixel in blue, green, red, alpha order, which is the + /// memory layout of a GDI+ 32bpp ARGB bitmap on little-endian Windows. + public const int BitmapFormatBgra = 4; + + /// Opaque white in PDFium's 0xAARRGGBB colour format. + public const uint ColorWhite = 0xFFFFFFFF; + + /// FPDF_ANNOT_WIDGET: the annotation subtype of a form field on a page. + public const int AnnotationWidget = 20; + + /// FLAT_PRINT: flatten the annotations as they print (only those with the Print flag). + public const int FlattenForPrint = 1; + + /// FLATTEN_SUCCESS: annotations were flattened into the page content. + public const int FlattenSuccess = 1; + + /// + /// The FPDF_FORMFILLINFO version PDFStream.NET declares. Version 1 means "stable interfaces only": PDFium + /// reads the version-2 members only when the version is 2 or more. + /// + public const int FormFillInfoVersion = 1; + + /// + /// How many pointer-sized slots PDFStream.NET allocates for FPDF_FORMFILLINFO. In the bundled build the + /// structure is an int version followed by 34 pointer-sized members (the host callbacks, the + /// JavaScript platform pointer and the version-2 additions), so 64 slots, all zero, leave a wide margin. + /// + public const int FormFillInfoSlots = 64; + + /// + /// FS_RECTF: a rectangle in PDF user space, in points. Note the member order (left, top, right, bottom); + /// for a page box is greater than . + /// + [StructLayout(LayoutKind.Sequential)] + public struct FsRectF + { + /// Left edge. + public float Left; + + /// Top edge. + public float Top; + + /// Right edge. + public float Right; + + /// Bottom edge. + public float Bottom; + } + + /// FS_SIZEF: a width and height in points (named apart from System.Drawing.SizeF). + [StructLayout(LayoutKind.Sequential)] + public struct FsSizeF + { + /// Width in points. + public float Width; + + /// Height in points. + public float Height; + } + + /// void FPDF_InitLibrary(): initialises PDFium once per process. + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDF_InitLibrary(); + + /// + /// FPDF_DOCUMENT FPDF_LoadMemDocument64(const void* data_buf, size_t size, FPDF_BYTESTRING password). + /// PDFium does not copy the buffer: it must stay valid until . + /// + /// + /// SetLastError is on because on Windows PDFium reports why a load failed through the + /// Win32 last-error value (FPDF_GetLastError is a direct jump to kernel32 + /// GetLastError in this build). The runtime may overwrite that value between two + /// P/Invoke calls, so it is captured right after this call and read with + /// instead of a second call into PDFium. + /// The password is passed as UTF-8, which PDFium accepts and converts to Latin-1 itself for + /// older encryption revisions that expect it. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, SetLastError = true)] + public static extern IntPtr FPDF_LoadMemDocument64(IntPtr dataBuffer, nuint size, [MarshalAs(UnmanagedType.LPUTF8Str)] string? password); + + /// void FPDF_CloseDocument(FPDF_DOCUMENT document). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDF_CloseDocument(IntPtr document); + + /// int FPDF_GetPageCount(FPDF_DOCUMENT document). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDF_GetPageCount(IntPtr document); + + /// FPDF_BOOL FPDF_GetPageSizeByIndexF(FPDF_DOCUMENT document, int page_index, FS_SIZEF* size). + /// Reads the size without loading the whole page. + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDF_GetPageSizeByIndexF(IntPtr document, int pageIndex, out FsSizeF size); + + /// FPDF_PAGE FPDF_LoadPage(FPDF_DOCUMENT document, int page_index). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr FPDF_LoadPage(IntPtr document, int pageIndex); + + /// void FPDF_ClosePage(FPDF_PAGE page). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDF_ClosePage(IntPtr page); + + /// + /// FPDF_BOOL FPDF_RenderPage(HDC dc, FPDF_PAGE page, int start_x, int start_y, int size_x, + /// int size_y, int rotate, int flags). Windows only; draws onto a device context. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDF_RenderPage(IntPtr hdc, IntPtr page, int startX, int startY, int sizeX, int sizeY, int rotate, int flags); + + /// + /// FPDF_BITMAP FPDFBitmap_CreateEx(int width, int height, int format, void* first_scan, int stride). + /// With an external buffer PDFium draws into memory the caller owns and never frees it. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr FPDFBitmap_CreateEx(int width, int height, int format, IntPtr firstScan, int stride); + + /// FPDF_BOOL FPDFBitmap_FillRect(FPDF_BITMAP bitmap, int left, int top, int width, + /// int height, FPDF_DWORD color). FPDF_DWORD is a 32-bit unsigned long on Windows. + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDFBitmap_FillRect(IntPtr bitmap, int left, int top, int width, int height, uint color); + + /// void FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int start_x, + /// int start_y, int size_x, int size_y, int rotate, int flags). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDF_RenderPageBitmap(IntPtr bitmap, IntPtr page, int startX, int startY, int sizeX, int sizeY, int rotate, int flags); + + /// void FPDFBitmap_Destroy(FPDF_BITMAP bitmap). Does not free an external buffer. + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDFBitmap_Destroy(IntPtr bitmap); + + /// + /// FPDF_FORMHANDLE FPDFDOC_InitFormFillEnvironment(FPDF_DOCUMENT document, FPDF_FORMFILLINFO* formInfo). + /// Returns NULL on failure. PDFium keeps the pointer: the block must stay + /// valid until , and the environment must be closed before + /// the document. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr FPDFDOC_InitFormFillEnvironment(IntPtr document, IntPtr formInfo); + + /// void FPDFDOC_ExitFormFillEnvironment(FPDF_FORMHANDLE hHandle). A no-op for NULL. + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDFDOC_ExitFormFillEnvironment(IntPtr formHandle); + + /// + /// void FORM_OnAfterLoadPage(FPDF_PAGE page, FPDF_FORMHANDLE hHandle). Gives the form-fill module the + /// page; it reads the page's annotations and builds the appearances that are missing (or, when the form + /// says /NeedAppearances, rebuilds the fields' appearances from their values). + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FORM_OnAfterLoadPage(IntPtr page, IntPtr formHandle); + + /// void FORM_OnBeforeClosePage(FPDF_PAGE page, FPDF_FORMHANDLE hHandle). Must follow + /// before the page is closed. + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FORM_OnBeforeClosePage(IntPtr page, IntPtr formHandle); + + /// + /// int FPDFPage_Flatten(FPDF_PAGE page, int nFlag). Draws the page's annotation appearances into its + /// content and removes the annotations. Returns FLATTEN_FAIL (0), FLATTEN_SUCCESS (1) or + /// FLATTEN_NOTHINGTODO (2). The page object passed in keeps its old content; load the page again to + /// draw the result. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDFPage_Flatten(IntPtr page, int usage); + + /// int FPDFPage_GetAnnotCount(FPDF_PAGE page). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDFPage_GetAnnotCount(IntPtr page); + + /// FPDF_ANNOTATION FPDFPage_GetAnnot(FPDF_PAGE page, int index). NULL on failure; close the + /// result with . + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr FPDFPage_GetAnnot(IntPtr page, int index); + + /// FPDF_ANNOTATION_SUBTYPE FPDFAnnot_GetSubtype(FPDF_ANNOTATION annot) (an int). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDFAnnot_GetSubtype(IntPtr annotation); + + /// void FPDFPage_CloseAnnot(FPDF_ANNOTATION annot). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDFPage_CloseAnnot(IntPtr annotation); + + /// + /// FPDF_BOOL FPDF_GetPageBoundingBox(FPDF_PAGE page, FS_RECTF* rect): the page's visible box, the + /// intersection of its MediaBox and CropBox, including boxes the page inherits from its parents. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDF_GetPageBoundingBox(IntPtr page, out FsRectF rect); + + /// + /// FPDF_BOOL FPDFPage_GetMediaBox(FPDF_PAGE page, float* left, float* bottom, float* right, float* top). + /// Reads only the page's own dictionary: an inherited MediaBox reports false. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDFPage_GetMediaBox(IntPtr page, out float left, out float bottom, out float right, out float top); + + /// void FPDFPage_SetMediaBox(FPDF_PAGE page, float left, float bottom, float right, float top). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDFPage_SetMediaBox(IntPtr page, float left, float bottom, float right, float top); + + /// void FPDFPage_SetCropBox(FPDF_PAGE page, float left, float bottom, float right, float top). + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void FPDFPage_SetCropBox(IntPtr page, float left, float bottom, float right, float top); + + /// + /// FPDF_BOOL FPDF_ImportPagesByIndex(FPDF_DOCUMENT dest_doc, FPDF_DOCUMENT src_doc, const int* page_indices, + /// unsigned long length, int index) (fpdf_ppo.h, marked experimental). Inserts copies of the listed + /// pages of into before page + /// (the page count appends them). Returns false if a page index is invalid. + /// + /// + /// PDFStream.NET passes the same document as both, to copy its pages with form fields to the end of its own + /// in-memory document, all in one call. Each copy gets the attributes its page inherits from the page tree + /// written onto itself, and the copies get their own copies of the objects the pages refer to (checked with the + /// bundled build: a copy of a page that inherits its MediaBox, Resources and Rotate draws the same pixels as + /// the page, and has a MediaBox of its own). One call keeps one map from original to copied objects, so an + /// object several of the pages share is copied once (measured with the bundled build on x64: drawing 40 form + /// pages that share 8 MB of images grew private memory by 14 to 17 MB, against about 290 MB with one call per + /// page). + /// unsigned long is 32 bits on Windows, for x86 and x64 alike. + /// + [DllImport(Library, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int FPDF_ImportPagesByIndex(IntPtr destination, IntPtr source, int[] pageIndices, uint length, int index); +} diff --git a/src/PDFStream.NET/Messages.cs b/src/PDFStream.NET/Messages.cs new file mode 100644 index 0000000..b923a95 --- /dev/null +++ b/src/PDFStream.NET/Messages.cs @@ -0,0 +1,153 @@ +namespace PDFStream.NET; + +/// +/// The plain-language text for every . Each message says what happened and, +/// for a failure, ends with what to do next, so it can be shown to an end user as it is. +/// +internal static class Messages +{ + /// Returns the standard message for a status. + /// The status to describe. + internal static string For(PrintStatus status) => status switch + { + PrintStatus.Ok => Ok(), + PrintStatus.FileNotFound => FileNotFound(), + PrintStatus.InvalidPdf => InvalidPdf(), + PrintStatus.PasswordRequired => PasswordRequired(), + PrintStatus.PasswordInvalid => PasswordInvalid(), + PrintStatus.PrinterNotFound => PrinterNotFound(), + PrintStatus.PrinterUnavailable => PrinterUnavailable(), + PrintStatus.InvalidPageRange => InvalidPageRange(), + PrintStatus.PageNotFound => PageNotFound(), + PrintStatus.InvalidOptions => InvalidOptions(), + PrintStatus.Cancelled => Cancelled(), + PrintStatus.UnknownError => UnknownError(), + + // A status added to the enum without a message must fail loudly in the tests rather than + // reach a user with an empty text. + _ => throw new ArgumentOutOfRangeException(nameof(status), status, "No message is defined for this status."), + }; + + /// The job printed. + internal static string Ok() => + "The document was printed. All requested pages were sent to the printer."; + + /// The file is missing or unreadable. + internal static string FileNotFound() => + "The PDF file could not be found or read. Check that the file path is correct and that this account is allowed to open the file."; + + /// The bytes are not a usable PDF. + internal static string InvalidPdf() => + "The file is not a valid PDF, or it is damaged and cannot be opened. Check that the file is a complete PDF and try opening it in a PDF viewer."; + + /// A protected PDF without a password. + internal static string PasswordRequired() => + "The PDF is protected with a password and none was given. Enter the password in the print options and try again."; + + /// A protected PDF with the wrong password. + internal static string PasswordInvalid() => + "The password given for the PDF is not correct. Check the password and try again."; + + /// No installed printer has that name. + internal static string PrinterNotFound() => + "No printer with that name is installed on this computer. Check the printer name exactly as Windows lists it, and that the printer is visible to the account running this program."; + + /// The printer cannot be opened or rejects the settings. + internal static string PrinterUnavailable() => + "The printer could not be opened, or it does not accept the requested settings. Check that the printer is switched on and connected and that the Windows Print Spooler service is running, then try again or choose different print settings."; + + /// The page range text is malformed. + internal static string InvalidPageRange() => + "The page range is not valid. Use page numbers starting at 1, separated by commas, and write ranges from the lower to the higher number, for example 1-5, 8, 10-12."; + + /// The page range names a page the PDF does not have. + internal static string PageNotFound() => + "The page range includes a page that is not in the PDF. Check the number of pages in the document and choose pages within it."; + + /// The options themselves are unusable. + internal static string InvalidOptions() => + "The print options are not valid, for example the printer name is empty or the number of copies is less than 1. Check the print options and try again."; + + /// + /// The requested paper source (tray) is not one of the printer's. No existing status text can + /// name the printer's real trays, which is what lets the caller fix the setting, so this one + /// takes them as a list. + /// + /// The paper source name the caller asked for. + /// The paper source names the printer reports; may be empty. + internal static string UnknownPaperSource(string requested, IReadOnlyList available) => + available.Count == 0 + ? $"The paper source \"{requested}\" is not available because this printer does not report any selectable paper sources. Leave the paper source empty to use the printer's default tray." + : $"The paper source \"{requested}\" is not available on this printer. The available paper sources are: {string.Join(", ", available)}. Use one of these names exactly, or leave the paper source empty to use the printer's default tray."; + + /// + /// The output file cannot be written to: the path is malformed, names a folder, or its folder + /// does not exist. Reported before printing so no job is started that is bound to fail. + /// + /// The output file path the caller gave. + internal static string InvalidOutputFile(string path) => + $"The output file \"{path}\" cannot be used. Check that the path is a file name (not a folder) and that the folder it is in already exists."; + + /// The printer queue is paused in Windows. + /// The printer, as Windows lists it. + internal static string PrinterPaused(string printerName) => + $"The printer \"{printerName}\" is paused in Windows, so the document was not sent. Open the printer's queue (Settings, Printers & scanners), choose Resume, then print again."; + + /// The printer is set to "Use printer offline" in Windows. + /// The printer, as Windows lists it. + internal static string PrinterWorkOffline(string printerName) => + $"The printer \"{printerName}\" is set to \"Use printer offline\" in Windows, so the document was not sent. Open the printer's queue, clear \"Use printer offline\" in the Printer menu, then print again."; + + /// Windows reports the printer as not available. + /// The printer, as Windows lists it. + internal static string PrinterNotAvailable(string printerName) => + $"The printer \"{printerName}\" is not available at the moment, so the document was not sent. Check that the printer is switched on and connected, then print again."; + + /// The printer is being removed from Windows. + /// The printer, as Windows lists it. + internal static string PrinterPendingDeletion(string printerName) => + $"The printer \"{printerName}\" is being removed from Windows and no longer accepts documents, so the document was not sent. Choose another printer, or add this printer again, then print again."; + + /// Windows could not open the printer's queue, for a reason other than a stopped spooler. + /// The printer, as Windows lists it. + internal static string PrinterCannotBeOpened(string printerName) => + $"Windows could not open the printer \"{printerName}\", so the document was not sent. Check that the Windows Print Spooler service is running and that the account running this program is allowed to use this printer, then print again."; + + /// The Windows Print Spooler service is not running. + internal static string SpoolerNotRunning() => + "The Windows Print Spooler service is not running, so no printer can be used and the document was not sent. Start the Print Spooler service (in Services, or ask the person who looks after this computer), then print again."; + + /// The job was stopped. + internal static string Cancelled() => + "Printing was cancelled before it finished, so some pages may not have been printed. Start the job again if the document is still needed."; + + /// Anything else. + internal static string UnknownError() => + "Printing failed for an unexpected reason. Try again, and if it keeps happening contact the person who looks after this program."; + + /// + /// Anything else, with the technical reason added at the end for the person who looks after the + /// program (the first sentences stay readable for everyone else). + /// + /// The technical reason, usually an exception message. + internal static string UnknownError(string details) => + $"{UnknownError()} Details: {details}"; + + /// + /// A page could not be drawn by either print path, so the job was stopped. The job is aborted + /// rather than finished, so no half-drawn sheet should come out; the text says "may have been + /// withdrawn" because the print system, not this library, removes an aborted job from the queue. + /// + /// The page that failed, counted from 1. + /// The technical reason, usually the engine's exception message. + internal static string PageFailed(int pageNumber, string details) => + $"Page {pageNumber} of the PDF could not be drawn, so printing was stopped and the unfinished job may have been withdrawn from the print queue. Check the print queue for a job left over from this document and delete it, then open the PDF in a PDF viewer to check that the page is not damaged and print the document again. Details: {details}"; + + /// + /// The printer refused the page as drawing commands and the page is too large to send as a + /// picture instead (not enough memory for the image, which happens most in 32-bit programs). + /// + /// The page that failed, counted from 1. + internal static string PageTooLarge(int pageNumber) => + $"Page {pageNumber} could not be printed: the printer did not accept it as drawing commands, and the page is too large to send as a picture with the memory available. Printing was stopped and the unfinished job may have been withdrawn from the print queue, so check the print queue for a job left over from this document and delete it. Choose a smaller paper size, or split the document into smaller parts, then try again."; +} diff --git a/src/PDFStream.NET/PDFStream.NET.csproj b/src/PDFStream.NET/PDFStream.NET.csproj new file mode 100644 index 0000000..8ef9b00 --- /dev/null +++ b/src/PDFStream.NET/PDFStream.NET.csproj @@ -0,0 +1,74 @@ + + + + + PDFStream.NET + PDFStream.NET + Free, open-source silent PDF printing for .NET on Windows, powered by PDFium. No Adobe Reader, no licence keys, no watermarks. + + + + + + PDFStream.NET + PDFStream.NET + pdf;print;printing;printer;silent;pdfium;windows;service + README.md + https://github.com/P4Software/PDFStream.NET + https://github.com/P4Software/PDFStream.NET + git + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/PDFStream.NET/PageRangeParser.cs b/src/PDFStream.NET/PageRangeParser.cs new file mode 100644 index 0000000..6bfd353 --- /dev/null +++ b/src/PDFStream.NET/PageRangeParser.cs @@ -0,0 +1,169 @@ +using System.Globalization; + +namespace PDFStream.NET; + +/// +/// Turns the page-range text of (for example "1-5, 8, 10-12") +/// into the zero-based page indexes the engine uses. +/// +internal static class PageRangeParser +{ + /// Tries to turn a page-range text into zero-based page indexes. + /// The text, with pages counted from 1. , empty or blank means every page. + /// How many pages the document has. + /// + /// The pages to print, in the order and with the repeats written in ; + /// empty when the method returns . + /// + /// + /// on success, for text + /// that is not a page range, or for a page the document does not have. + /// + /// when is usable. + internal static bool TryParse(string? spec, int pageCount, out IReadOnlyList zeroBasedPages, out PrintStatus error) + { + if (string.IsNullOrWhiteSpace(spec)) + { + zeroBasedPages = Enumerable.Range(0, Math.Max(pageCount, 0)).ToArray(); + error = PrintStatus.Ok; + return true; + } + + // Two passes on purpose. The first checks only the text, so a typo is reported as a typo + // even when an earlier part names a missing page; the second checks the page numbers + // against the document. Each range is checked before it is expanded, so "1-2000000000" + // is rejected without building a two-billion-entry list. + var ranges = new List<(int First, int Last)>(); + foreach (string part in spec.Split(',')) + { + if (!TryParsePart(part, out (int First, int Last) range, out bool overflow)) + { + return Fail(PrintStatus.InvalidPageRange, out zeroBasedPages, out error); + } + + ranges.Add(overflow ? (int.MaxValue, int.MaxValue) : range); + } + + foreach ((_, int last) in ranges) + { + if (last > pageCount) + { + return Fail(PrintStatus.PageNotFound, out zeroBasedPages, out error); + } + } + + var pages = new List(); + foreach ((int first, int last) in ranges) + { + for (int page = first; page <= last; page++) + { + pages.Add(page - 1); + } + } + + zeroBasedPages = pages; + error = PrintStatus.Ok; + return true; + } + + /// + /// Parses one comma-separated piece: a page ("8") or a range ("10-12"), spaces allowed around + /// the numbers. Fails for anything else, including empty pieces, 0, signs and reversed ranges. + /// + /// The piece, without the surrounding commas. + /// The first and last page, 1-based, equal for a single page. + /// + /// when a number is made of digits but is too large for an int. Such a + /// page certainly does not exist, so the caller reports it as a missing page, not as a typo (a + /// reversed range is still a typo, whatever the size of the numbers). + /// + private static bool TryParsePart(string part, out (int First, int Last) range, out bool overflow) + { + range = default; + overflow = false; + + string[] numbers = part.Split('-'); + if (numbers.Length is < 1 or > 2) + { + return false; + } + + if (!TryParsePage(numbers[0], out int first, out bool firstOverflow, out string firstDigits)) + { + return false; + } + + int last = first; + bool lastOverflow = firstOverflow; + string lastDigits = firstDigits; + if (numbers.Length == 2 && !TryParsePage(numbers[1], out last, out lastOverflow, out lastDigits)) + { + return false; + } + + overflow = firstOverflow || lastOverflow; + + // A reversed range is a typo whatever the size of the numbers, so the check runs when a bound + // overflows too; only then the digits are compared, because an int cannot hold the value. + bool reversed = overflow ? CompareDigits(firstDigits, lastDigits) > 0 : last < first; + if (reversed) + { + return false; + } + + range = (first, last); + return true; + } + + /// + /// Parses one page number made only of the digits 0-9 (after trimming spaces). A leading sign, + /// a decimal point and non-ASCII digits are refused on purpose: the format is the one a user + /// types into a print dialog, not whatever the current culture accepts. + /// + /// The text of the number. + /// The page number, 1 or more. + /// Whether the digits were valid but too large for an int. + /// The digits without spaces and leading zeros, kept so two numbers too large for an int can still be compared. + private static bool TryParsePage(string text, out int page, out bool overflow, out string digits) + { + page = 0; + overflow = false; + + string trimmed = text.Trim(); + digits = trimmed; + if (trimmed.Length == 0 || !trimmed.All(char.IsAsciiDigit)) + { + return false; + } + + // "0007" is page 7; stripping the zeros also makes the length a valid measure of size. + digits = trimmed.TrimStart('0'); + if (digits.Length == 0) + { + // Only zeros: page 0, which does not exist. + return false; + } + + if (!int.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out page)) + { + overflow = true; + } + + return true; + } + + /// + /// Compares two numbers written as digits without leading zeros, with no limit on their size: + /// the longer one is larger, and equal lengths compare digit by digit. + /// + /// A positive number when is larger, negative when smaller, 0 when equal. + private static int CompareDigits(string a, string b) => + a.Length != b.Length ? a.Length.CompareTo(b.Length) : string.CompareOrdinal(a, b); + + private static bool Fail(PrintStatus status, out IReadOnlyList zeroBasedPages, out PrintStatus error) + { + zeroBasedPages = Array.Empty(); + error = status; + return false; + } +} diff --git a/src/PDFStream.NET/PdfPrinter.cs b/src/PDFStream.NET/PdfPrinter.cs new file mode 100644 index 0000000..6450033 --- /dev/null +++ b/src/PDFStream.NET/PdfPrinter.cs @@ -0,0 +1,251 @@ +using System.Drawing.Printing; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; + +namespace PDFStream.NET; + +/// +/// Runs one print job on a Windows printer. This is the delegate form of +/// without its optional print controller, so tests can replace the job and the facade can be checked +/// without a printer. +/// +/// The open document. +/// Zero-based page indexes, in print order. +/// Ready printer settings. +/// The name for the print queue; may be blank. +/// How each page is sized onto the paper. +/// Cancels the job between pages. +/// What the job did. +internal delegate PrintResult PrintJobRunner( + IPdfDocument doc, + IReadOnlyList pages, + PrinterSettings settings, + string documentName, + ScaleMode scale, + CancellationToken token); + +/// +/// Silently prints a PDF on a Windows printer: no dialog, no PDF viewer and no command line. Pass the PDF +/// as a file path, a stream or a byte array together with the , and read the +/// returned . +/// +/// +/// +/// None of the methods throws managed exceptions for bad input or printer problems (a missing file, a damaged +/// or protected PDF, a wrong printer name, a paused printer, a bad page range, even an unexpected internal +/// failure): each returns a whose says in plain +/// language what happened and what to do next. +/// +/// +/// Limits: PDFium runs inside the calling process without a sandbox, so a malformed or hostile PDF that causes a +/// memory fault inside it ends the whole process, which .NET cannot catch; print PDFs you do not trust in a +/// separate worker process. One process-wide lock is held while a page is drawn, so a printer driver that hangs +/// stalls every print in the process, and cancellation is checked between pages only. The "Security and limits" +/// section of the usage guide (docs/usage.md) explains these. +/// +/// +/// The steps run in this order, and the first problem ends the call: the options are checked, the PDF is +/// opened, the page range is checked against the real page count, the printer and its settings are +/// prepared, and then the job runs. A PDF that is protected only by an owner password (restrictions but +/// no open password) prints without any password. +/// +/// +/// PDFium, the engine that reads and draws the PDF, is not thread-safe, so every call into it is made under +/// one lock for the whole process. The lock is held for a single engine call (opening the PDF, measuring or +/// drawing one page, closing it), not for a whole job. The methods may therefore be called from several +/// threads at once: the jobs run side by side and their engine work takes turns, so they interleave at page +/// level and each takes longer than it would alone. Each call is still its own print job with its own pages +/// in their own order, and no call fails because another one is running. +/// +/// +public static class PdfPrinter +{ + /// The job runner used outside the tests: the real print job. + private static readonly PrintJobRunner RealJob = (doc, pages, settings, documentName, scale, token) => + PrintJob.Run(doc, pages, settings, documentName, scale, token); + + /// Opens the PDF with the password from the options; what it returns is owned by the caller. + private delegate PrintStatus DocumentLoader(string? password, out IPdfDocument? document); + + /// Prints a PDF file. + /// The path of the PDF file. A missing, unreadable or blank path returns . + /// What and where to print. returns . + /// + /// Stops the job. It is checked before the PDF is opened and between pages; a job stopped between + /// pages ends normally, so the pages already sent do print and counts them. + /// + /// + /// The outcome. No managed exception is thrown for bad input or printer problems (see the class remarks for + /// the limits). is only when every requested page + /// was rendered and sent to the printer. + /// + /// + /// Safe to call from several threads at once. PDFium work is serialised one engine call at a time across the + /// whole process, so concurrent calls run side by side and take turns page by page; each stays its own print job. + /// + public static PrintResult Print(string path, PrintOptions options, CancellationToken cancellationToken = default) => + Print(path, options, new PdfiumEngine(), SystemPrinterCatalog.Instance, RealJob, cancellationToken); + + /// Prints a PDF read from a stream. + /// + /// A readable stream holding the whole PDF, read from its current position to its end. It does not need + /// to support seeking and is left open: it belongs to the caller. , an empty or an + /// unreadable stream returns . + /// + /// What and where to print. returns . + /// + /// Stops the job. It is checked before the PDF is opened and between pages; a job stopped between + /// pages ends normally, so the pages already sent do print and counts them. + /// + /// + /// The outcome. No managed exception is thrown for bad input or printer problems (see the class remarks for + /// the limits). is only when every requested page + /// was rendered and sent to the printer. + /// + /// + /// Safe to call from several threads at once. PDFium work is serialised one engine call at a time across the + /// whole process, so concurrent calls run side by side and take turns page by page; each stays its own print job. + /// + public static PrintResult Print(Stream pdf, PrintOptions options, CancellationToken cancellationToken = default) => + Print(pdf, options, new PdfiumEngine(), SystemPrinterCatalog.Instance, RealJob, cancellationToken); + + /// Prints a PDF held in memory. + /// The complete PDF file. or empty returns . The array is not changed or kept. + /// What and where to print. returns . + /// + /// Stops the job. It is checked before the PDF is opened and between pages; a job stopped between + /// pages ends normally, so the pages already sent do print and counts them. + /// + /// + /// The outcome. No managed exception is thrown for bad input or printer problems (see the class remarks for + /// the limits). is only when every requested page + /// was rendered and sent to the printer. + /// + /// + /// Safe to call from several threads at once. PDFium work is serialised one engine call at a time across the + /// whole process, so concurrent calls run side by side and take turns page by page; each stays its own print job. + /// + public static PrintResult Print(byte[] pdf, PrintOptions options, CancellationToken cancellationToken = default) => + Print(pdf, options, new PdfiumEngine(), SystemPrinterCatalog.Instance, RealJob, cancellationToken); + + /// The file overload with the engine, the printer list and the job replaceable (for tests). + internal static PrintResult Print( + string path, + PrintOptions options, + IPdfEngine engine, + IPrinterCatalog catalog, + PrintJobRunner runner, + CancellationToken cancellationToken = default) => + Execute(options, catalog, runner, cancellationToken, (string? password, out IPdfDocument? document) => + PdfSource.Load(engine, path, password, out document)); + + /// The stream overload with the engine, the printer list and the job replaceable (for tests). + internal static PrintResult Print( + Stream pdf, + PrintOptions options, + IPdfEngine engine, + IPrinterCatalog catalog, + PrintJobRunner runner, + CancellationToken cancellationToken = default) => + Execute(options, catalog, runner, cancellationToken, (string? password, out IPdfDocument? document) => + PdfSource.Load(engine, pdf, password, out document)); + + /// The byte-array overload with the engine, the printer list and the job replaceable (for tests). + internal static PrintResult Print( + byte[] pdf, + PrintOptions options, + IPdfEngine engine, + IPrinterCatalog catalog, + PrintJobRunner runner, + CancellationToken cancellationToken = default) => + Execute(options, catalog, runner, cancellationToken, (string? password, out IPdfDocument? document) => + PdfSource.Load(engine, pdf, password, out document)); + + /// + /// The steps every overload shares, in the order that reports the cheapest-to-fix problem first: + /// options, cancellation, load, page range, printer settings, job. Nothing escapes as an exception. + /// + private static PrintResult Execute( + PrintOptions options, + IPrinterCatalog catalog, + PrintJobRunner runner, + CancellationToken cancellationToken, + DocumentLoader load) + { + IPdfDocument? document = null; + try + { + // Options first: a wrong option should fail the same way whatever the file is, and before + // any file or printer is touched. + if (!PrinterLocator.AreOptionsUsable(options)) + { + return PrintResult.Failure(PrintStatus.InvalidOptions); + } + + if (cancellationToken.IsCancellationRequested) + { + return PrintResult.Failure(PrintStatus.Cancelled); + } + + PrintStatus loaded = load(options.Password, out document); + if (loaded != PrintStatus.Ok || document is null) + { + return PrintResult.Failure(loaded == PrintStatus.Ok ? PrintStatus.InvalidPdf : loaded); + } + + // Opening a big file can take a while, so a cancellation that arrived meanwhile is honoured + // before the printer is touched. + if (cancellationToken.IsCancellationRequested) + { + return PrintResult.Failure(PrintStatus.Cancelled); + } + + // The range is checked against the real page count, which is only known now. + if (!PageRangeParser.TryParse(options.Pages, document.PageCount, out IReadOnlyList pages, out PrintStatus rangeError)) + { + return PrintResult.Failure(rangeError); + } + + // The overload with a message, so the cause-specific text (paused queue, the list of paper + // trays, a stopped Print Spooler) reaches the caller instead of the generic one. + PrintStatus prepared = PrinterLocator.TryCreateSettings(options, catalog, out PrinterSettings? settings, out string message); + if (prepared != PrintStatus.Ok || settings is null) + { + return PrintResult.Failure(prepared == PrintStatus.Ok ? PrintStatus.PrinterUnavailable : prepared, message); + } + + // The job's result is passed on as it is: it already counts 0 pages after any failure and the + // exact number after a cancellation that ended the job normally. A null from a replaced job + // runner is a bug in that runner and is reported like any other unexpected failure. + return runner(document, pages, settings, options.DocumentName ?? string.Empty, options.Scale, cancellationToken) + ?? PrintResult.Failure(PrintStatus.UnknownError, Messages.UnknownError("The print job returned no result.")); + } + catch (Exception ex) + { + // The promise of this class: no exception reaches the caller. The text of the exception is added + // for the person who looks after the program; an empty message falls back to the type name. + string details = string.IsNullOrWhiteSpace(ex.Message) ? ex.GetType().Name : ex.Message; + return PrintResult.Failure(PrintStatus.UnknownError, Messages.UnknownError(details)); + } + finally + { + Release(document); + } + } + + /// + /// Disposes the document on every path. A failure while releasing is swallowed: the outcome of the job + /// is already decided, and an exception thrown from here would replace the result the caller is owed. + /// + private static void Release(IPdfDocument? document) + { + try + { + document?.Dispose(); + } + catch (Exception) + { + // Nothing useful can be done with a failed release; the result stands. + } + } +} diff --git a/src/PDFStream.NET/PdfSource.cs b/src/PDFStream.NET/PdfSource.cs new file mode 100644 index 0000000..ea259cc --- /dev/null +++ b/src/PDFStream.NET/PdfSource.cs @@ -0,0 +1,145 @@ +using PDFStream.NET.Engine; + +namespace PDFStream.NET; + +/// +/// Turns the three ways a caller can hand over a PDF (a file path, a stream or a byte array) +/// into an open , and every way that can go wrong into a +/// . Nothing in here throws for bad input: the public print methods +/// promise a result with a message instead of an exception. The one thing that does come out as an +/// exception is a failure of the engine itself (for example pdfium.dll missing for this processor): +/// it is not about the caller's file, and the facade turns it into an unknown-error result that +/// carries the exception's message, which the person fixing the installation needs to see. +/// +internal static class PdfSource +{ + /// Loads a PDF from a file. + /// The engine that opens the PDF. + /// Path of the PDF file. + /// Password for a protected PDF; or empty for none. + /// The open document when the result is , otherwise + /// . The caller owns it and must dispose it. + /// , or the reason the PDF could not be loaded. + internal static PrintStatus Load(IPdfEngine engine, string path, string? password, out IPdfDocument? doc) + { + doc = null; + if (string.IsNullOrWhiteSpace(path)) + { + return PrintStatus.FileNotFound; + } + + byte[] bytes; + try + { + bytes = File.ReadAllBytes(path); + } + catch (Exception ex) when (IsFileAccessProblem(ex)) + { + // Missing file, missing folder, a folder instead of a file, no permission, a sharing + // violation, a path that is too long or malformed: for the person using the program + // these are all "the file cannot be found or read", which is what the message says. + return PrintStatus.FileNotFound; + } + + return Load(engine, bytes, password, out doc); + } + + /// + /// Loads a PDF from a stream. The stream is read from its current position to its end and is + /// left open: it belongs to the caller. + /// + /// The engine that opens the PDF. + /// A readable stream. It does not need to support seeking. + /// Password for a protected PDF; or empty for none. + /// The open document when the result is , otherwise + /// . The caller owns it and must dispose it. + /// , or the reason the PDF could not be loaded. + internal static PrintStatus Load(IPdfEngine engine, Stream input, string? password, out IPdfDocument? doc) + { + doc = null; + if (input is null) + { + return PrintStatus.InvalidPdf; + } + + byte[] bytes; + try + { + // Copy to the end instead of trusting Length: network and pipe streams cannot report + // one, and a stream that is not at the start must give only what is left. + using var buffer = new MemoryStream(); + input.CopyTo(buffer); + bytes = buffer.ToArray(); + } + catch (Exception ex) when (IsStreamProblem(ex)) + { + // The data never arrived in full (closed, broken or unreadable stream), so what the + // caller handed over is not a complete PDF. + return PrintStatus.InvalidPdf; + } + + return Load(engine, bytes, password, out doc); + } + + /// Loads a PDF from memory. + /// The engine that opens the PDF. + /// The complete PDF file. + /// Password for a protected PDF; or empty for none. + /// The open document when the result is , otherwise + /// . The caller owns it and must dispose it. + /// , or the reason the PDF could not be loaded. + internal static PrintStatus Load(IPdfEngine engine, byte[] input, string? password, out IPdfDocument? doc) + { + doc = null; + if (input is null || input.Length == 0) + { + return PrintStatus.InvalidPdf; + } + + IPdfDocument? opened = null; + try + { + PdfLoadStatus loaded = engine.TryLoad(input, password, out opened); + switch (loaded) + { + case PdfLoadStatus.Ok when opened is not null: + if (opened.PageCount < 1) + { + // A valid PDF with no pages has nothing to print. Reporting it here keeps + // every later step free to assume a document has at least one page. + return PrintStatus.InvalidPdf; + } + + doc = opened; + opened = null; + return PrintStatus.Ok; + + case PdfLoadStatus.PasswordRequired: + return PrintStatus.PasswordRequired; + + case PdfLoadStatus.PasswordInvalid: + return PrintStatus.PasswordInvalid; + + default: + // Invalid, and an engine that claims success without a document. + return PrintStatus.InvalidPdf; + } + } + finally + { + // Anything opened but not handed to the caller (zero pages, or an exception after + // the open) is released here so native memory is never leaked. An engine failure is + // deliberately not caught here: the facade reports it with the exception's message, + // which a bare status could not carry. + opened?.Dispose(); + } + } + + /// True for the exceptions reading a file can raise for reasons outside the caller's code. + private static bool IsFileAccessProblem(Exception ex) => + ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException or System.Security.SecurityException; + + /// True for the exceptions reading a stream can raise when the stream is broken or unusable. + private static bool IsStreamProblem(Exception ex) => + ex is IOException or NotSupportedException or ObjectDisposedException or UnauthorizedAccessException; +} diff --git a/src/PDFStream.NET/PrintOptions.cs b/src/PDFStream.NET/PrintOptions.cs new file mode 100644 index 0000000..7098b49 --- /dev/null +++ b/src/PDFStream.NET/PrintOptions.cs @@ -0,0 +1,74 @@ +namespace PDFStream.NET; + +/// +/// The settings for one print job. Every property is init-only: build the object once with an +/// object initializer and pass it to the print call. Anything left out keeps the printer's own +/// setting, except where a default is stated. +/// +public sealed class PrintOptions +{ + /// + /// The printer to print to, exactly as Windows lists it, including network names such as + /// \\server\printer. Required: an empty name makes the print call return + /// instead of printing. + /// + /// + /// It defaults to an empty string rather than being a C# "required" member so that a + /// forgotten name becomes a normal result with a message, not a compile-time wall for callers + /// who fill the options from a settings file. + /// + public string PrinterName { get; init; } = string.Empty; + + /// The name shown for the job in the print queue. lets the library choose one. + public string? DocumentName { get; init; } + + /// The password of a protected PDF. or empty means the PDF has no password. + public string? Password { get; init; } + + /// + /// The pages to print, counted from 1, for example "1-5, 8, 10-12". Pages print in the + /// order written. or empty means every page. + /// + public string? Pages { get; init; } + + /// How many copies to print. Must be at least 1; the default is 1. + public int Copies { get; init; } = 1; + + /// Single-sided or double-sided printing. The default leaves the printer's own setting. + public DuplexMode Duplex { get; init; } + + /// + /// Colour or black and white. (the default) keeps the printer's own colour setting, + /// asks the printer for colour and for black and white. + /// + /// + /// The default changes nothing on purpose: a program that sets no colour gets what the printer is set up to + /// do, as it would printing from any other application. A printer that cannot print in colour prints in + /// black and white whatever is asked. + /// + public bool? Color { get; init; } + + /// How pages are sized onto the paper. The default fits each page to the paper. + public ScaleMode Scale { get; init; } = ScaleMode.FitToPage; + + /// The paper source (tray) name as the printer reports it. keeps the printer's default tray. + public string? PaperSource { get; init; } + + /// + /// When set, the job is written to this file instead of being sent to the printer's port. It + /// is how a "print to file" printer such as Microsoft Print to PDF runs without showing a Save As dialog. + /// + /// + /// + /// The folder must already exist; a relative path is taken from the current folder of the process. An + /// existing file is replaced. An empty or blank text is not the same as leaving the option out: it returns + /// . + /// + /// + /// The print system may still be writing the file when the print call returns: Microsoft Print to PDF + /// finishes it a moment later. A program that opens the file straight afterwards must wait until the file + /// can be opened on its own (try again every half second or so, for a few seconds) instead of reading it at once. + /// + /// + public string? OutputFile { get; init; } +} diff --git a/src/PDFStream.NET/PrintResult.cs b/src/PDFStream.NET/PrintResult.cs new file mode 100644 index 0000000..2b9758b --- /dev/null +++ b/src/PDFStream.NET/PrintResult.cs @@ -0,0 +1,64 @@ +namespace PDFStream.NET; + +/// +/// What a print call did. The library does not throw managed exceptions for bad input or printer problems; it +/// returns one of these instead. Check , and log (see there for when +/// it may be shown to people as it is). +/// +public sealed class PrintResult +{ + private PrintResult(PrintStatus status, string message, int pagesPrinted) + { + Status = status; + Message = message; + PagesPrinted = pagesPrinted; + } + + /// when the pages were rendered and sent to the printer ( is ). + public bool Succeeded => Status == PrintStatus.Ok; + + /// The outcome as a value to branch on. + public PrintStatus Status { get; } + + /// + /// The outcome in plain language: what happened and, for a failure, what to do next. + /// + /// + /// Most messages can be shown to the person running the program as they are. An + /// message, however, may end with technical details (the text of an + /// internal exception, which can name files or internal parts of the program), so log the message rather than + /// show it in a public web page. + /// + public string Message { get; } + + /// + /// How many pages were sent to the printer. When the library makes the copies itself (it repeats the whole + /// document in software because the driver cannot make that many) it is pages times copies; when the + /// driver makes the copies, each page is sent once and it is the number of pages only. After a cancellation + /// it is the exact number sent before printing stopped; the job is then finished normally, so those pages + /// print. After a failure it is 0: the unfinished job is aborted and may have been withdrawn from the print + /// queue by the print system, so pages drawn before the failure normally do not come out. + /// + public int PagesPrinted { get; } + + /// Creates the result of a job that printed. + /// The number of pages sent to the printer. + internal static PrintResult Success(int pagesPrinted) => + new(PrintStatus.Ok, Messages.For(PrintStatus.Ok), pagesPrinted); + + /// Creates the result of a job that did not (fully) print. + /// The reason. It must not be . + /// A more specific message than the standard one for the status. , empty or blank means the standard one: a blank line is never shown to the user. + /// The exact pages sent when a cancellation ended the job normally; 0 (the default) after a failure, because an unfinished job is aborted and may have been withdrawn. + internal static PrintResult Failure(PrintStatus status, string? message = null, int pagesPrinted = 0) + { + // Succeeded is derived from Status, so a "failure" with the Ok status would claim success + // while the caller meant the opposite. It is a programming error inside the library. + if (status == PrintStatus.Ok) + { + throw new ArgumentException("A failure result cannot have the Ok status.", nameof(status)); + } + + return new PrintResult(status, string.IsNullOrWhiteSpace(message) ? Messages.For(status) : message, pagesPrinted); + } +} diff --git a/src/PDFStream.NET/PrintStatus.cs b/src/PDFStream.NET/PrintStatus.cs new file mode 100644 index 0000000..3e43de8 --- /dev/null +++ b/src/PDFStream.NET/PrintStatus.cs @@ -0,0 +1,44 @@ +namespace PDFStream.NET; + +/// +/// The outcome of a print call. Every failure reason has its own value so a caller can react in +/// code; carries the same reason in plain language. +/// +public enum PrintStatus +{ + /// The pages were rendered and sent to the printer. + Ok, + + /// The PDF file does not exist or could not be read. + FileNotFound, + + /// The data is not a PDF, or the PDF is damaged and cannot be opened. + InvalidPdf, + + /// The PDF is protected and no password was supplied. + PasswordRequired, + + /// The PDF is protected and the supplied password is wrong. + PasswordInvalid, + + /// No printer with the given name is installed. + PrinterNotFound, + + /// The printer exists but could not be opened, or the requested settings are not valid for it. + PrinterUnavailable, + + /// The page range text is malformed, for example "5-2", "0" or "abc". + InvalidPageRange, + + /// The page range is well formed but names a page the PDF does not have. + PageNotFound, + + /// The print options are not usable, for example a missing printer name or fewer than one copy. + InvalidOptions, + + /// Printing was cancelled before it finished; some pages may already have been sent. + Cancelled, + + /// Something unexpected went wrong that none of the other values describes. + UnknownError, +} diff --git a/src/PDFStream.NET/Printing/IPrinterCatalog.cs b/src/PDFStream.NET/Printing/IPrinterCatalog.cs new file mode 100644 index 0000000..1616eee --- /dev/null +++ b/src/PDFStream.NET/Printing/IPrinterCatalog.cs @@ -0,0 +1,17 @@ +namespace PDFStream.NET.Printing; + +/// +/// The list of printers Windows knows about. It exists as a seam: the real list comes from the +/// print system, but tests hand in a fake list so printer-name matching (case, spaces, non-ASCII +/// letters, network names such as \\server\printer) and the "no such printer" path can be +/// checked without any printer or print spooler. +/// +internal interface IPrinterCatalog +{ + /// + /// Returns the names of the installed printers exactly as Windows lists them. May throw when + /// the print system is not available (for example the Print Spooler service is stopped); the + /// caller turns that into a status. + /// + IReadOnlyList GetInstalledPrinterNames(); +} diff --git a/src/PDFStream.NET/Printing/IPrinterStatusProbe.cs b/src/PDFStream.NET/Printing/IPrinterStatusProbe.cs new file mode 100644 index 0000000..9b32026 --- /dev/null +++ b/src/PDFStream.NET/Printing/IPrinterStatusProbe.cs @@ -0,0 +1,49 @@ +namespace PDFStream.NET.Printing; + +/// What happened when a printer queue's status was read. +internal enum PrinterStatusReadOutcome +{ + /// The status and attributes were read. + Read, + + /// + /// The queue opened, but its status could not be read. Printing goes ahead as if the printer were + /// fine: an unreadable status is never a reason to refuse a job. + /// + Unreadable, + + /// The Windows Print Spooler service is not running, so no printer can be used at all. + SpoolerNotRunning, + + /// + /// The queue could not be opened at all, for a reason other than a stopped spooler (for example the + /// account running the program is not allowed to use the printer, or the printer no longer exists). + /// + CannotOpen, +} + +/// +/// Reads a printer queue's status as Windows reports it. It exists as a seam: the real reading comes +/// from the print spooler, but tests hand in a fake so every queue state (paused, not available, paper +/// out, and so on) can be checked without pausing or unplugging a real printer. +/// +internal interface IPrinterStatusProbe +{ + /// Reads the queue's status bits and attribute bits. + /// The printer name exactly as Windows lists it. + /// The PRINTER_STATUS_* bits when the outcome is ; otherwise 0. + /// The PRINTER_ATTRIBUTE_* bits when the outcome is ; otherwise 0. + /// Whether the values were read and, if not, why. May also throw; callers treat that as unreadable. + PrinterStatusReadOutcome TryRead(string printerName, out uint status, out uint attributes); + + /// + /// Says whether the local Windows Print Spooler service is clearly not running. Used when the printer + /// list cannot be read, or does not hold the requested printer, to tell a stopped spooler apart from a + /// printer that is simply not installed. + /// + /// + /// only when the spooler definitely did not answer; when it + /// answered or when the answer is unclear. May also throw; callers treat that as . + /// + bool IsSpoolerStopped(); +} diff --git a/src/PDFStream.NET/Printing/PagePainter.cs b/src/PDFStream.NET/Printing/PagePainter.cs new file mode 100644 index 0000000..fd12d8d --- /dev/null +++ b/src/PDFStream.NET/Printing/PagePainter.cs @@ -0,0 +1,269 @@ +using System.Drawing; +using System.Drawing.Drawing2D; +using PDFStream.NET.Engine; + +namespace PDFStream.NET.Printing; + +/// +/// Puts one PDF page on one printer sheet. First it decides where the page goes, how large it is and +/// whether it is turned (, pure layout math). Then it draws the page: +/// straight onto the printer's device context, or, when the driver refuses that, as a bitmap at the +/// printer's resolution. +/// +/// +/// Units: page sizes are in points (1/72 inch), as PDF measures them. Printable areas and destinations +/// are in hundredths of an inch, as the Windows print system measures them. Device rectangles are in +/// printer pixels. All PDFium work goes through , which holds the engine lock. +/// +internal static class PagePainter +{ + /// + /// The highest resolution, in dots per inch on paper, that the bitmap fallback renders at. A US + /// Letter page is about 34 MB as a 32-bit bitmap at 300 dpi, but 135 MB at 600 dpi and 540 MB at + /// 1200 dpi, and a 32-bit process often cannot get that much memory in one block. 300 dpi still + /// keeps text and barcodes sharp on paper. + /// + internal const int MaxFallbackDpi = 300; + + /// Hundredths of an inch per point (a point is 1/72 inch). + private const double HundredthsPerPoint = 100.0 / 72.0; + + /// + /// How much bigger the turned page must come out before it is turned. Without this margin, rounding + /// noise could turn a page whose two orientations fit equally well, such as a square page. + /// + private const double TurnGainThreshold = 1e-6; + + /// + /// The largest device coordinate passed on. It keeps the arithmetic for a huge page printed at + /// actual size far from integer overflow; everything beyond the sheet is cut off anyway. + /// + private const double MaxDeviceCoordinate = 1 << 30; + + /// + /// Works out where a page goes on the sheet. Fit to page scales the page to the largest size that + /// fits the printable area while keeping its proportions, and centres it. Actual size keeps the + /// page at 100% and centres it, so a page larger than the area loses the same amount on each side. + /// In both modes a page is turned a quarter onto the sheet (landscape onto portrait or the reverse) + /// when that makes it larger (fit) or keeps more of it on the paper (actual size). + /// + /// The page size as displayed, in points (any /Rotate already applied). + /// The part of the sheet the printer can reach, in hundredths of an inch. + /// Fit to page or actual size. + /// when the page must be drawn turned a quarter. The + /// returned rectangle is then the turned page's footprint (its width comes from the page height). + /// The rectangle the page fills on the sheet, in hundredths of an inch. With actual size it + /// may reach beyond the printable area. + /// The page or the area has no positive, finite size, + /// or is not a known mode. + internal static RectangleF ComputeDestination(SizeF pageSizePoints, RectangleF printableArea, ScaleMode scale, out bool rotate) + { + RequireUsableSize(pageSizePoints.Width, pageSizePoints.Height, nameof(pageSizePoints)); + RequireUsableSize(printableArea.Width, printableArea.Height, nameof(printableArea)); + + // Doubles throughout: a 200-inch page at actual size is 20000 hundredths of an inch, where + // single-precision rounding would already show in the position. + double pageWidth = pageSizePoints.Width; + double pageHeight = pageSizePoints.Height; + double areaWidth = printableArea.Width; + double areaHeight = printableArea.Height; + double width; + double height; + + switch (scale) + { + case ScaleMode.FitToPage: + // Units cancel out here: only the proportions of the page and the area matter. + double upright = Math.Min(areaWidth / pageWidth, areaHeight / pageHeight); + double turned = Math.Min(areaWidth / pageHeight, areaHeight / pageWidth); + rotate = turned > upright * (1 + TurnGainThreshold); + double factor = rotate ? turned : upright; + width = (rotate ? pageHeight : pageWidth) * factor; + height = (rotate ? pageWidth : pageHeight) * factor; + break; + + case ScaleMode.ActualSize: + double naturalWidth = pageWidth * HundredthsPerPoint; + double naturalHeight = pageHeight * HundredthsPerPoint; + + // Compare how much of the page lands inside the printable area each way round. + double uprightVisible = Math.Min(naturalWidth, areaWidth) * Math.Min(naturalHeight, areaHeight); + double turnedVisible = Math.Min(naturalHeight, areaWidth) * Math.Min(naturalWidth, areaHeight); + rotate = turnedVisible > uprightVisible * (1 + TurnGainThreshold); + width = rotate ? naturalHeight : naturalWidth; + height = rotate ? naturalWidth : naturalHeight; + break; + + default: + throw new ArgumentOutOfRangeException(nameof(scale), scale, "Unknown scale mode."); + } + + double x = printableArea.X + ((areaWidth - width) / 2); + double y = printableArea.Y + ((areaHeight - height) / 2); + return new RectangleF((float)x, (float)y, (float)width, (float)height); + } + + /// + /// Switches a sheet's to hundredths of an inch, the unit this class lays + /// pages out in, and returns the printable area in that unit. + /// + /// + /// A printer Graphics already measures in hundredths of an inch (its "display" unit), but a bitmap + /// Graphics measures in pixels; setting the unit explicitly makes both behave the same. The visible + /// clip bounds of a printer Graphics are the printable area: the part of the sheet the printer can + /// reach, with the origin at its top-left corner. + /// + /// The sheet to prepare. + /// The printable area, in hundredths of an inch. + internal static RectangleF PrepareSheet(Graphics graphics) + { + graphics.PageUnit = GraphicsUnit.Inch; + graphics.PageScale = 0.01f; + return graphics.VisibleClipBounds; + } + + /// + /// Draws one page onto a sheet, laid out by . The page goes straight + /// onto the sheet's device context, which keeps vector content sharp and spool files small. If the + /// engine reports that the device context refused the drawing, the page is rendered as a bitmap at + /// the printer's resolution (at most ) and drawn as an image instead. + /// + /// The open document. + /// Zero-based index of the page to draw. + /// The sheet, prepared with (hundredths of an inch). + /// The printable area, as returned it. + /// Fit to page or actual size. + /// The printer's resolution in dots per inch, for the bitmap fallback. + /// The device context refused the drawing and the page is + /// too large to render as a bitmap. + /// The page or the area has no usable size. + /// The engine could not draw the page either way. + internal static void Paint(IPdfDocument doc, int pageIndex, Graphics g, RectangleF printableArea, ScaleMode scale, int printerDpi) + { + SizeF pageSize = doc.GetPageSizePoints(pageIndex); + RectangleF destination = ComputeDestination(pageSize, printableArea, scale, out bool rotate); + int quarterTurns = rotate ? QuarterTurnsOnto(printableArea) : 0; + + if (!TryPaintOnDeviceContext(doc, pageIndex, g, destination, quarterTurns)) + { + PaintAsBitmap(doc, pageIndex, g, destination, pageSize, rotate, quarterTurns, printerDpi); + } + } + + /// + /// Which way a page is turned when it is turned. This is a chosen convention, applied the same way + /// to every page: a landscape page on a portrait sheet turns counter-clockwise (3), so its top edge + /// runs along the left edge of the sheet; a portrait page on a landscape sheet turns clockwise (1). + /// Either direction prints the same content; the choice only decides which edge the top faces. + /// + private static int QuarterTurnsOnto(RectangleF printableArea) => + printableArea.Width > printableArea.Height ? 1 : 3; + + /// + /// Draws the page straight onto the device context behind . Returns + /// when the engine reports that the device context refused the drawing, + /// so the caller can fall back to a bitmap. + /// + private static bool TryPaintOnDeviceContext(IPdfDocument doc, int pageIndex, Graphics g, RectangleF destination, int quarterTurns) + { + Rectangle pixels = ToDevicePixels(g, destination); + IntPtr hdc = g.GetHdc(); + try + { + doc.RenderToDeviceContext(pageIndex, hdc, pixels, forPrinting: true, quarterTurns); + return true; + } + catch (InvalidOperationException ex) when (ex is not ObjectDisposedException) + { + // The engine's documented signal that it could not draw on this device context. A disposed + // document is a different problem that a bitmap cannot solve, so it is not caught. + return false; + } + finally + { + g.ReleaseHdc(hdc); + } + } + + /// + /// The fallback: renders the page to a bitmap that gives the printer's resolution on paper (capped + /// at ) and draws it into the destination. + /// + private static void PaintAsBitmap(IPdfDocument doc, int pageIndex, Graphics g, RectangleF destination, SizeF pageSize, bool rotate, int quarterTurns, int printerDpi) + { + // The engine's dpi is relative to the page's own size. To get the wanted dots per inch on paper, + // scale it by how much the page is enlarged or shrunk on the sheet. The page's own width ends up + // as the destination's width, or as its height when the page is turned. + double printedWidth = rotate ? destination.Height : destination.Width; + double enlargement = printedWidth / (pageSize.Width * HundredthsPerPoint); + int dotsOnPaper = printerDpi > 0 ? Math.Min(printerDpi, MaxFallbackDpi) : MaxFallbackDpi; + + // At least 1: a huge page shrunk onto a small sheet can round down to 0, which the engine refuses. + int dpi = (int)Math.Clamp(Math.Round(dotsOnPaper * enlargement), 1, int.MaxValue); + + try + { + using Bitmap image = doc.RenderToBitmap(pageIndex, dpi, quarterTurns); + g.DrawImage(image, destination); + } + catch (Exception ex) when (ex is ArgumentException or OutOfMemoryException) + { + // How a bitmap that is too large shows up: the engine refuses the size + // (ArgumentOutOfRangeException), GDI+ refuses to create it ("Parameter is not valid", an + // ArgumentException) or memory runs out, notably in 32-bit processes. The page index and the + // quarter turns were already accepted by the calls above, so here these mean the page size. + throw new PageTooLargeException(pageIndex, ex); + } + } + + /// + /// Converts a rectangle from the sheet's units to device pixels, the coordinates of the device + /// context behind the Graphics. The Graphics' own transforms do the conversion, so the unit, the + /// resolution and any origin shift are all taken into account. + /// + private static Rectangle ToDevicePixels(Graphics g, RectangleF rectangle) + { + PointF[] corners = [new(rectangle.Left, rectangle.Top), new(rectangle.Right, rectangle.Bottom)]; + g.TransformPoints(CoordinateSpace.Device, CoordinateSpace.World, corners); + + int left = RoundToDevice(corners[0].X); + int top = RoundToDevice(corners[0].Y); + int right = RoundToDevice(corners[1].X); + int bottom = RoundToDevice(corners[1].Y); + + // Never less than one pixel: the engine refuses an empty rectangle, and a page that small prints + // as a dot either way. + return Rectangle.FromLTRB(left, top, Math.Max(right, left + 1), Math.Max(bottom, top + 1)); + } + + private static int RoundToDevice(float value) => + (int)Math.Clamp(Math.Round(value), -MaxDeviceCoordinate, MaxDeviceCoordinate); + + private static void RequireUsableSize(float width, float height, string parameterName) + { + // Written so that NaN fails too: every comparison with NaN is false. + if (!(width > 0 && height > 0 && float.IsFinite(width) && float.IsFinite(height))) + { + throw new ArgumentOutOfRangeException(parameterName, $"{width} x {height}", "A positive, finite width and height are required."); + } + } + + /// + /// Thrown by when a page had to go through the bitmap fallback and the bitmap is + /// too large to create. It carries the page, so the print job can name it in its message. + /// + internal sealed class PageTooLargeException : Exception + { + /// Creates the exception for a page. + /// The zero-based index of the page that was too large. + /// The allocation failure behind it. + internal PageTooLargeException(int pageIndex, Exception innerException) + : base($"Page {pageIndex + 1} is too large to render as a bitmap at the printer's resolution.", innerException) + { + PageIndex = pageIndex; + } + + /// The zero-based index of the page that was too large. + public int PageIndex { get; } + } +} diff --git a/src/PDFStream.NET/Printing/PrintJob.cs b/src/PDFStream.NET/Printing/PrintJob.cs new file mode 100644 index 0000000..89baa36 --- /dev/null +++ b/src/PDFStream.NET/Printing/PrintJob.cs @@ -0,0 +1,275 @@ +using System.Drawing; +using System.Drawing.Printing; +using System.Runtime.InteropServices; +using PDFStream.NET.Engine; + +namespace PDFStream.NET.Printing; + +/// +/// Prints chosen pages of an open PDF as one Windows print job, through +/// without a progress dialog. Every way the job can go wrong (a printer that cannot be opened, a page +/// that cannot be drawn, cancellation) comes back as a ; nothing is thrown. +/// +internal static class PrintJob +{ + /// The name shown in the print queue when the caller gives none. + internal const string DefaultDocumentName = "PDF document"; + + /// + /// Prints the pages, each one laid out on its own sheet by . + /// + /// The open document. The caller keeps ownership. + /// Zero-based page indexes, in print order; repeats are printed again. + /// Ready printer settings (see ). When the driver + /// cannot make the requested copies itself, the copy count is set to 1 for the job and restored + /// afterwards, and the document is repeated instead. + /// The name shown in the print queue; blank means . + /// How each page is sized onto the paper. + /// Checked between pages. When it fires, the page being drawn is finished and the + /// job ends there, so the pages counted as sent really print. + /// Runs the job. uses + /// , which prints without a progress dialog. Tests pass a fake + /// that prints onto bitmaps. + /// + /// only when every page was drawn and sent. Otherwise + /// (no pages), , + /// , or + /// . is then the exact + /// number of pages sent when a cancellation ended the job normally (those pages print), and 0 after + /// any failure or abort: the print system withdraws an unfinished job, so pages drawn before the + /// failure normally never come out. + /// + /// + /// Software copies (when the driver's is below the + /// request, as with Microsoft Print to PDF) repeat the whole document in the same job, in order, + /// so the copies come out collated and a print-to-file job still writes one file. + /// counts every page sent, across the repetitions; when the + /// driver makes the copies, each page is sent once. + /// + internal static PrintResult Run( + IPdfDocument doc, + IReadOnlyList pages, + PrinterSettings settings, + string documentName, + ScaleMode scale, + CancellationToken token, + PrintController? controller = null) + { + if (doc is null || pages is null || settings is null) + { + // The library's own callers always pass these, so this is a bug inside the library: + // reported like any other failure rather than thrown at the caller. + return PrintResult.Failure(PrintStatus.UnknownError, Messages.UnknownError("The print job was started without a document, a page list or printer settings.")); + } + + PageFeeder? feeder = null; + short? copiesToRestore = null; + try + { + if (pages.Count == 0) + { + // A print job without pages would still push one blank sheet out of the printer. + return PrintResult.Failure(PrintStatus.InvalidPageRange); + } + + int pageCount = doc.PageCount; + foreach (int page in pages) + { + if ((uint)page >= (uint)pageCount) + { + return PrintResult.Failure(PrintStatus.PageNotFound); + } + } + + if (token.IsCancellationRequested) + { + return PrintResult.Failure(PrintStatus.Cancelled); + } + + // Tell the document which pages this job draws, so that it prepares only those (for PDFium: looks for + // form fields among them and copies the ones that have fields in one go). Nothing is read here yet. + doc.PlanToDraw(pages); + + // Asking the driver for its maximum is slow on some printers, so only when it matters. + short requestedCopies = settings.Copies; + int driverMaximum = requestedCopies > 1 ? settings.MaximumCopies : 1; + (int repetitions, short driverCopies) = PlanCopies(requestedCopies, driverMaximum); + if (driverCopies != requestedCopies) + { + copiesToRestore = requestedCopies; + settings.Copies = driverCopies; + } + + feeder = new PageFeeder(doc, pages, repetitions, scale, token); + using var document = new PrintDocument + { + // PrinterSettings first: assigning it also adopts its page settings (colour, paper + // source) for the job. + PrinterSettings = settings, + DocumentName = string.IsNullOrWhiteSpace(documentName) ? DefaultDocumentName : documentName, + PrintController = controller ?? new StandardPrintController(), + }; + document.PrintPage += feeder.PrintPage; + document.Print(); + return feeder.Result(); + } + catch (Exception ex) + { + return feeder is null ? MapException(ex) : feeder.Failed(ex); + } + finally + { + // The settings belong to the caller; leave them as they came. + if (copiesToRestore is short copies) + { + settings.Copies = copies; + } + } + } + + /// + /// Decides who makes the copies. The driver does when it says it can make that many; otherwise the + /// document is repeated in software and the driver is asked for one copy. Never both: a driver + /// asked for 3 copies of a document already repeated 3 times would print 9. + /// + /// The copies the caller asked for. + /// The driver's . A value + /// below 1 (the driver could not say) means it cannot be trusted with copies. + /// How many times to send the document, and the copy count to give the driver. + internal static (int Repetitions, short DriverCopies) PlanCopies(short requestedCopies, int driverMaximum) + { + if (requestedCopies <= 1) + { + return (1, 1); + } + + return driverMaximum >= requestedCopies ? (1, requestedCopies) : (requestedCopies, (short)1); + } + + /// + /// Turns an exception from the print system into a result: the printer could not be opened or + /// refused the job (, or a Windows error such as a failing + /// StartDoc, EndPage or EndDoc, which arrives as an ), or anything + /// else. No pages are counted: a job the print system failed on is aborted or never finished, so + /// what was drawn before the failure is not known to print. + /// + private static PrintResult MapException(Exception ex) => ex switch + { + InvalidPrinterException or ExternalException => PrintResult.Failure(PrintStatus.PrinterUnavailable), + _ => PrintResult.Failure(PrintStatus.UnknownError, Messages.UnknownError(ex.Message)), + }; + + /// + /// Feeds the pages to the print document one sheet at a time and remembers why the job stopped + /// early, if it did. One instance serves one job. + /// + private sealed class PageFeeder(IPdfDocument doc, IReadOnlyList pages, int repetitions, ScaleMode scale, CancellationToken token) + { + private readonly long _total = (long)pages.Count * repetitions; + private long _next; + + // Why the job was aborted, if it was; such a result always counts 0 pages. + private PrintResult? _aborted; + + // Set when a cancellation ended the job normally after the page in progress. + private bool _cancelledBetweenPages; + + /// Pages drawn and handed to the print system so far, across all repetitions. + public int PagesSent { get; private set; } + + /// Handles the print document's page event: draws the next page and says whether more follow. + public void PrintPage(object? sender, PrintPageEventArgs e) + { + // The print system has already started a sheet for this event. A cancel that arrives before + // anything was drawn aborts the job: nothing has been sent yet, and ending normally would + // push that blank sheet out of the printer. + if (PagesSent == 0 && token.IsCancellationRequested) + { + Abort(e, PrintResult.Failure(PrintStatus.Cancelled)); + return; + } + + int pageIndex = pages[(int)(_next % pages.Count)]; + try + { + Graphics graphics = e.Graphics ?? throw new InvalidOperationException("The print system did not provide a drawing surface for the page."); + RectangleF printableArea = PagePainter.PrepareSheet(graphics); + if (printableArea.Width <= 0 || printableArea.Height <= 0) + { + // A printer that reports no printable area cannot print anything; the fault is the + // printer's, not the page's. + Abort(e, PrintResult.Failure(PrintStatus.PrinterUnavailable)); + return; + } + + int printerDpi = (int)Math.Round(Math.Max(graphics.DpiX, graphics.DpiY)); + PagePainter.Paint(doc, pageIndex, graphics, printableArea, scale, printerDpi); + } + catch (PagePainter.PageTooLargeException) + { + Abort(e, PrintResult.Failure(PrintStatus.UnknownError, Messages.PageTooLarge(pageIndex + 1))); + return; + } + catch (Exception ex) + { + Abort(e, PrintResult.Failure(PrintStatus.UnknownError, Messages.PageFailed(pageIndex + 1, ex.Message))); + return; + } + + PagesSent++; + _next++; + + // Cancellation is checked once a page is complete, never by leaving a started sheet blank. + // Stopping here ends the job normally, so every page counted as sent really prints. + if (_next < _total && token.IsCancellationRequested) + { + _cancelledBetweenPages = true; + e.HasMorePages = false; + return; + } + + e.HasMorePages = _next < _total; + } + + /// The result of a job the print system closed without an exception. + public PrintResult Result() + { + if (_aborted is not null) + { + return _aborted; + } + + if (_cancelledBetweenPages) + { + // The job was ended normally after the page in progress, so exactly these pages print. + return PrintResult.Failure(PrintStatus.Cancelled, pagesPrinted: PagesSent); + } + + // Fewer pages than asked for, with no reason recorded here, means the print system cancelled + // the job by itself (for example a Save As box closed without saving). It then aborts the job, + // so nothing is counted. That is never success. + return PagesSent == _total + ? PrintResult.Success(PagesSent) + : PrintResult.Failure(PrintStatus.Cancelled); + } + + /// + /// The result of a job the print system ended with an exception. A page's own reason for + /// aborting wins over whatever was thrown while closing the aborted job. A cancellation does not: + /// if closing the normally ended job fails, its pages may never print, so it is a failure. + /// + public PrintResult Failed(Exception ex) => _aborted ?? MapException(ex); + + /// + /// Stops the job because of a failure, or a cancellation before anything was drawn. The job is + /// aborted, so the print system withdraws it from the queue and the sheet started for this page + /// (blank or half drawn) never comes out. must count 0 pages. + /// + private void Abort(PrintPageEventArgs e, PrintResult why) + { + _aborted = why; + e.Cancel = true; + e.HasMorePages = false; + } + } +} diff --git a/src/PDFStream.NET/Printing/PrinterLocator.cs b/src/PDFStream.NET/Printing/PrinterLocator.cs new file mode 100644 index 0000000..6b6d544 --- /dev/null +++ b/src/PDFStream.NET/Printing/PrinterLocator.cs @@ -0,0 +1,370 @@ +using System.ComponentModel; +using System.Drawing.Printing; + +namespace PDFStream.NET.Printing; + +/// +/// Finds the requested printer and turns into a ready-to-use +/// (copies, duplex, colour, paper source, print to file). Nothing in +/// here prints, opens a dialog or writes a file; it only prepares and validates settings, and every +/// problem comes back as a status and a plain-language message instead of an exception. +/// +internal static class PrinterLocator +{ + /// The largest copy count Windows can store in a print job (a 16-bit number). + private const int MaxCopies = short.MaxValue; + + /// + /// Checks the options that need no printer to be judged: a printer name, a copy count Windows can + /// store, and enum values that are defined. The public print method calls it before it opens the + /// PDF, so a wrong option is reported without any file or printer work. + /// + /// The caller's print options; is not usable. + /// when the options can be used. + internal static bool AreOptionsUsable(PrintOptions? options) => + options is not null + && !string.IsNullOrWhiteSpace(options.PrinterName) + && options.Copies >= 1 + && options.Copies <= MaxCopies + && Enum.IsDefined(options.Duplex) + && Enum.IsDefined(options.Scale); + + /// + /// Prepares the settings for one print job on the real installed printers. + /// + /// The caller's print options. + /// The ready settings when the result is , otherwise . + /// A status; use the overload with a message when the text matters (the paper source text lists the available trays). + internal static PrintStatus TryCreateSettings(PrintOptions options, out PrinterSettings? settings) => + TryCreateSettings(options, SystemPrinterCatalog.Instance, WinspoolPrinterStatusProbe.Instance, out settings, out _); + + /// + /// Prepares the settings for one print job. + /// + /// The caller's print options. + /// Where the installed printer names come from. + /// The ready settings when the result is , otherwise . + /// The plain-language text for the result: it says what happened and what to do next. + /// + /// , (empty name, fewer than one + /// copy, unknown paper source, unusable output file), or + /// (the printer cannot be opened, cannot do what was + /// asked, or its queue is paused, set to "Use printer offline", not available or being deleted, or the + /// Print Spooler service is stopped; the message names the cause). The queue state is read with the real + /// Windows print spooler. An "offline" report alone does not refuse the printer (see + /// ). + /// + internal static PrintStatus TryCreateSettings( + PrintOptions options, + IPrinterCatalog catalog, + out PrinterSettings? settings, + out string message) => + TryCreateSettings(options, catalog, WinspoolPrinterStatusProbe.Instance, out settings, out message); + + /// + /// Prepares the settings for one print job, checking the printer queue's state with the given probe. + /// + /// The caller's print options. + /// Where the installed printer names come from. + /// Where the printer queue's state comes from (see ). + /// The ready settings when the result is , otherwise . + /// The plain-language text for the result: it says what happened and what to do next. + /// As for the overload without a probe. + internal static PrintStatus TryCreateSettings( + PrintOptions options, + IPrinterCatalog catalog, + IPrinterStatusProbe statusProbe, + out PrinterSettings? settings, + out string message) + { + settings = null; + + // Check the options before touching the print system: bad input should fail the same way + // on a machine with no printers at all. + if (!AreOptionsUsable(options)) + { + message = Messages.InvalidOptions(); + return PrintStatus.InvalidOptions; + } + + string? outputFile = null; + if (options.OutputFile is not null) + { + outputFile = ResolveOutputFile(options.OutputFile); + if (outputFile is null) + { + message = Messages.InvalidOutputFile(options.OutputFile); + return PrintStatus.InvalidOptions; + } + } + + string? installedName; + try + { + installedName = FindInstalledName(catalog, options.PrinterName); + } + catch (Exception ex) + { + // The print system itself cannot be read. With the Print Spooler service stopped, Windows answers + // RPC_S_SERVER_UNAVAILABLE; that, or a spooler check that finds the service stopped, gets the + // message that says so. Anything else keeps the general text, which also points at the spooler. + message = IsRpcServerUnavailable(ex) || IsSpoolerStopped(statusProbe) + ? Messages.SpoolerNotRunning() + : Messages.PrinterUnavailable(); + return PrintStatus.PrinterUnavailable; + } + + if (installedName is null) + { + // A stopped spooler can also hand back an empty list instead of failing, which would read as "not + // installed". Only a printer missing while the spooler answers is really not found. + if (IsSpoolerStopped(statusProbe)) + { + message = Messages.SpoolerNotRunning(); + return PrintStatus.PrinterUnavailable; + } + + message = Messages.PrinterNotFound(); + return PrintStatus.PrinterNotFound; + } + + PrinterSettings candidate; + try + { + candidate = new PrinterSettings { PrinterName = installedName }; + + // IsValid is false when Windows knows the name but cannot open the printer (it was + // deleted a moment ago, the spooler refuses access to this account, and so on). + if (!candidate.IsValid) + { + message = Messages.PrinterUnavailable(); + return PrintStatus.PrinterUnavailable; + } + + // A paused queue (or one set to "Use printer offline") would accept the job and hold it, and + // the caller would be told it printed. Checked here, where every print call gets its settings, so the job is never + // started; the check itself never throws and never blocks on a status it cannot read. + PrintStatus ready = PrinterStatusCheck.Check(statusProbe, installedName, out message); + if (ready != PrintStatus.Ok) + { + return ready; + } + + PrintStatus status = Apply(options, candidate, outputFile, out message); + if (status != PrintStatus.Ok) + { + return status; + } + } + catch (Exception) + { + // PrinterSettings reports a printer that misbehaves through several exception types + // (InvalidPrinterException, Win32Exception, ...). The public API must not leak them. + message = Messages.PrinterUnavailable(); + return PrintStatus.PrinterUnavailable; + } + + settings = candidate; + message = Messages.Ok(); + return PrintStatus.Ok; + } + + /// + /// Finds the installed printer the caller means and returns its name exactly as Windows lists + /// it. An exact match wins; otherwise the match ignores letter case (Windows printer names are + /// not case sensitive) and ignores spaces around the name, which a settings file easily adds. + /// Network names such as \\server\printer are ordinary names for this purpose. + /// + /// Where the installed printer names come from. + /// The name the caller asked for. + /// The installed name, or when no printer matches. + internal static string? FindInstalledName(IPrinterCatalog catalog, string requested) + { + IReadOnlyList installed = catalog.GetInstalledPrinterNames(); + string wanted = requested.Trim(); + + // Ordinal comparisons: culture rules (Turkish dotless i, for example) must never decide + // which printer receives a job. OrdinalIgnoreCase still folds accented letters such as + // e-acute and E-acute together. + foreach (string name in installed) + { + if (string.Equals(name, wanted, StringComparison.Ordinal)) + { + return name; + } + } + + foreach (string name in installed) + { + if (string.Equals(name, wanted, StringComparison.OrdinalIgnoreCase)) + { + return name; + } + } + + return null; + } + + /// + /// Whether an exception (or one it wraps) carries RPC_S_SERVER_UNAVAILABLE, Windows's answer while the Print + /// Spooler service is not running: as a Win32 error code, or as the HRESULT made from it. + /// + private static bool IsRpcServerUnavailable(Exception exception) + { + const int RpcServerUnavailableHResult = unchecked((int)0x800706BA); + for (Exception? current = exception; current is not null; current = current.InnerException) + { + if (current is Win32Exception { NativeErrorCode: WinspoolPrinterStatusProbe.RpcServerUnavailable } + || current.HResult == RpcServerUnavailableHResult) + { + return true; + } + } + + return false; + } + + /// Asks the probe whether the spooler is stopped; a probe that fails counts as "not stopped". + private static bool IsSpoolerStopped(IPrinterStatusProbe probe) + { + try + { + return probe.IsSpoolerStopped(); + } + catch (Exception) + { + // An unclear answer never turns "not found" into a spooler message. + return false; + } + } + + /// Maps the library's duplex choice to the one Windows Forms understands. + /// The duplex mode from the print options. + /// + /// The matching , or for + /// (meaning: change nothing). + /// + internal static Duplex ToSystemDuplex(DuplexMode mode) => mode switch + { + DuplexMode.None => Duplex.Simplex, + + // "Long edge" binding turns pages like a book, which Windows calls Vertical duplex; + // "short edge" turns them like a notepad, which is Horizontal. + DuplexMode.LongEdge => Duplex.Vertical, + DuplexMode.ShortEdge => Duplex.Horizontal, + _ => Duplex.Default, + }; + + /// Copies the options onto an opened printer's settings. + /// The caller's print options, already checked by . + /// Settings for the installed printer; changed in place. + /// The full output file path, or to print to the printer's port. + /// The plain-language text for the result. + /// , or the status of the option the printer cannot honour. + internal static PrintStatus Apply(PrintOptions options, PrinterSettings settings, string? outputFile, out string message) + { + message = Messages.Ok(); + + settings.Copies = (short)options.Copies; + + // No colour asked for: leave the printer's own setting alone, so it is not frozen to one choice. + if (options.Color is bool color) + { + settings.DefaultPageSettings.Color = color; + } + + // PrinterDefault changes nothing. Plain single-sided printing needs no support from the + // printer, so it is applied only where it can matter; a double-sided request that the + // printer cannot do fails here rather than quietly printing single-sided pages. + if (options.Duplex is DuplexMode.LongEdge or DuplexMode.ShortEdge) + { + if (!settings.CanDuplex) + { + message = Messages.PrinterUnavailable(); + return PrintStatus.PrinterUnavailable; + } + + settings.Duplex = ToSystemDuplex(options.Duplex); + } + else if (options.Duplex == DuplexMode.None && settings.CanDuplex) + { + settings.Duplex = Duplex.Simplex; + } + + if (!string.IsNullOrWhiteSpace(options.PaperSource)) + { + PaperSource? source = FindPaperSource(settings, options.PaperSource.Trim()); + if (source is null) + { + var available = new List(); + foreach (PaperSource candidate in settings.PaperSources) + { + available.Add(candidate.SourceName); + } + + message = Messages.UnknownPaperSource(options.PaperSource.Trim(), available); + return PrintStatus.InvalidOptions; + } + + settings.DefaultPageSettings.PaperSource = source; + } + + if (outputFile is not null) + { + // Print to file is what stops "Microsoft Print to PDF" from asking where to save. + settings.PrintToFile = true; + settings.PrintFileName = outputFile; + } + + return PrintStatus.Ok; + } + + /// Finds a paper source by name, ignoring letter case. + private static PaperSource? FindPaperSource(PrinterSettings settings, string name) + { + foreach (PaperSource source in settings.PaperSources) + { + if (string.Equals(source.SourceName, name, StringComparison.OrdinalIgnoreCase)) + { + return source; + } + } + + return null; + } + + /// + /// Turns the output file option into a full path, or returns when it + /// cannot be used. A relative path is anchored now because a Windows service's working folder + /// is not where anyone expects. The folder is not created: making folders as a side effect of + /// a print call would surprise people, and a missing folder is far better reported up front + /// than as a print driver error halfway through the job. + /// + private static string? ResolveOutputFile(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + + try + { + string full = Path.GetFullPath(path.Trim()); + string? folder = Path.GetDirectoryName(full); + string fileName = Path.GetFileName(full); + + // GetFullPath does not reject characters Windows forbids in a file name (such as | and ?), + // so check them here; the printer driver would otherwise fail on them mid-job. + bool usable = folder is not null + && fileName.Length > 0 + && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 + && Directory.Exists(folder) + && !Directory.Exists(full); + return usable ? full : null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException or IOException) + { + return null; + } + } +} diff --git a/src/PDFStream.NET/Printing/PrinterStatusCheck.cs b/src/PDFStream.NET/Printing/PrinterStatusCheck.cs new file mode 100644 index 0000000..90e04b6 --- /dev/null +++ b/src/PDFStream.NET/Printing/PrinterStatusCheck.cs @@ -0,0 +1,106 @@ +namespace PDFStream.NET.Printing; + +/// +/// The pre-flight check of a printer queue's state, made before any job is started. A queue that is +/// paused, set to "Use printer offline", not available or being deleted would accept the job and hold +/// it without printing, so the caller would be told "printed" while nothing comes out. Those states, +/// and a queue that cannot be opened at all (a stopped Print Spooler included), are refused with a +/// message naming the cause. +/// +/// +/// +/// Problems a person fixes at the printer (paper out, a jam, toner, an open door, "user intervention") +/// are deliberately not refused: the job waits in the queue and prints as soon as someone fixes it. +/// +/// +/// "Offline" and "print server offline" reports are not refused either. Network printers often report +/// offline through SNMP status while they print perfectly well, which is common in warehouses, and a +/// printer that really is switched off simply queues the job until it comes back. Refusing them would +/// break working printing. +/// +/// +/// A status that cannot be read never blocks printing. The check is a courtesy that turns a silent +/// hold into a clear message; it must not stop a working printer because Windows could not answer. +/// +/// +internal static class PrinterStatusCheck +{ + /// PRINTER_STATUS_PAUSED: the queue is paused. + internal const uint StatusPaused = 0x00000001; + + /// PRINTER_STATUS_PENDING_DELETION: the printer is being deleted. + internal const uint StatusPendingDeletion = 0x00000004; + + /// PRINTER_STATUS_NOT_AVAILABLE: the printer is not available for printing. + internal const uint StatusNotAvailable = 0x00001000; + + /// PRINTER_ATTRIBUTE_WORK_OFFLINE: the user chose "Use printer offline". + internal const uint AttributeWorkOffline = 0x00000400; + + /// + /// Reads the printer's queue state and says whether a job may be started. + /// + /// Where the state comes from. + /// The printer name exactly as Windows lists it. Only called for a printer + /// found in the installed list, so a queue that cannot be opened is a real problem with it. + /// The plain-language reason when the printer is refused; otherwise the standard Ok text. + /// , or for a blocking + /// state, a queue that cannot be opened, or a stopped Print Spooler. + internal static PrintStatus Check(IPrinterStatusProbe probe, string printerName, out string message) + { + PrinterStatusReadOutcome outcome; + uint status; + uint attributes; + try + { + outcome = probe.TryRead(printerName, out status, out attributes); + } + catch (Exception) + { + // An unreadable status is treated as a ready printer, whatever went wrong reading it. + message = Messages.Ok(); + return PrintStatus.Ok; + } + + string? refusal = outcome switch + { + PrinterStatusReadOutcome.SpoolerNotRunning => Messages.SpoolerNotRunning(), + PrinterStatusReadOutcome.CannotOpen => Messages.PrinterCannotBeOpened(printerName), + PrinterStatusReadOutcome.Read => DescribeBlockingState(status, attributes, printerName), + _ => null, + }; + + message = refusal ?? Messages.Ok(); + return refusal is null ? PrintStatus.Ok : PrintStatus.PrinterUnavailable; + } + + /// + /// Returns the message for the first blocking state found, or when none is + /// set. The order goes from the most permanent cause to the one a person is most likely to have set + /// on purpose, so the message points at what has to be fixed first. + /// + private static string? DescribeBlockingState(uint status, uint attributes, string printerName) + { + if ((status & StatusPendingDeletion) != 0) + { + return Messages.PrinterPendingDeletion(printerName); + } + + if ((status & StatusNotAvailable) != 0) + { + return Messages.PrinterNotAvailable(printerName); + } + + if ((attributes & AttributeWorkOffline) != 0) + { + return Messages.PrinterWorkOffline(printerName); + } + + if ((status & StatusPaused) != 0) + { + return Messages.PrinterPaused(printerName); + } + + return null; + } +} diff --git a/src/PDFStream.NET/Printing/SystemPrinterCatalog.cs b/src/PDFStream.NET/Printing/SystemPrinterCatalog.cs new file mode 100644 index 0000000..62b84e0 --- /dev/null +++ b/src/PDFStream.NET/Printing/SystemPrinterCatalog.cs @@ -0,0 +1,28 @@ +using System.Drawing.Printing; + +namespace PDFStream.NET.Printing; + +/// The real printer list, read from the Windows print system. +internal sealed class SystemPrinterCatalog : IPrinterCatalog +{ + /// The one shared instance; the class holds no state. + internal static readonly SystemPrinterCatalog Instance = new(); + + private SystemPrinterCatalog() + { + } + + /// + public IReadOnlyList GetInstalledPrinterNames() + { + // Copy into an array: the framework collection is a live view of the spooler and is not + // meant to be held on to. + var names = new List(PrinterSettings.InstalledPrinters.Count); + foreach (string name in PrinterSettings.InstalledPrinters) + { + names.Add(name); + } + + return names; + } +} diff --git a/src/PDFStream.NET/Printing/WinspoolPrinterStatusProbe.cs b/src/PDFStream.NET/Printing/WinspoolPrinterStatusProbe.cs new file mode 100644 index 0000000..c1cea0b --- /dev/null +++ b/src/PDFStream.NET/Printing/WinspoolPrinterStatusProbe.cs @@ -0,0 +1,181 @@ +using System.Runtime.InteropServices; + +namespace PDFStream.NET.Printing; + +/// +/// The real printer status, read from the Windows print spooler with OpenPrinter and GetPrinter +/// (PRINTER_INFO_2), and the spooler check (see ). It never throws for a printer problem: a queue that cannot be opened is reported +/// as or +/// , and a status that cannot be read from an open +/// queue as . +/// +/// +/// The declarations are written from the documented Win32 API (winspool.drv). They use the +/// platform's default calling convention, which is what winspool exports use on every architecture. +/// +internal sealed class WinspoolPrinterStatusProbe : IPrinterStatusProbe +{ + /// The one shared instance; the class holds no state. + internal static readonly WinspoolPrinterStatusProbe Instance = new(); + + /// + /// RPC_S_SERVER_UNAVAILABLE: how OpenPrinter (and the printer list behind + /// PrinterSettings.InstalledPrinters) fails when the Print Spooler service is not running, because + /// the spooler is the RPC server they talk to. + /// + internal const int RpcServerUnavailable = 1722; + + /// GetPrinter information level for PRINTER_INFO_2, the level that carries Status and Attributes. + private const int InfoLevel2 = 2; + + private WinspoolPrinterStatusProbe() + { + } + + /// + public PrinterStatusReadOutcome TryRead(string printerName, out uint status, out uint attributes) + { + status = 0; + attributes = 0; + + if (!OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero)) + { + return Marshal.GetLastPInvokeError() == RpcServerUnavailable + ? PrinterStatusReadOutcome.SpoolerNotRunning + : PrinterStatusReadOutcome.CannotOpen; + } + + try + { + // The first call only asks how large the variable-length PRINTER_INFO_2 block is; it fails + // with "insufficient buffer" by design, so its result is not checked. + GetPrinter(printer, InfoLevel2, IntPtr.Zero, 0, out int needed); + if (needed < Marshal.SizeOf()) + { + return PrinterStatusReadOutcome.Unreadable; + } + + IntPtr buffer = Marshal.AllocHGlobal(needed); + try + { + if (!GetPrinter(printer, InfoLevel2, buffer, needed, out _)) + { + return PrinterStatusReadOutcome.Unreadable; + } + + PrinterInfo2 info = Marshal.PtrToStructure(buffer); + status = info.Status; + attributes = info.Attributes; + return PrinterStatusReadOutcome.Read; + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + finally + { + ClosePrinter(printer); + } + } + + /// + /// + /// Opens the local print server itself (OpenPrinter with no printer name), which needs no printer and never + /// goes over the network, and closes it again at once. Only RPC_S_SERVER_UNAVAILABLE counts as "stopped": + /// any other refusal (for example a permission problem) says nothing certain about the service. + /// + public bool IsSpoolerStopped() + { + if (OpenPrinter(null, out IntPtr server, IntPtr.Zero)) + { + ClosePrinter(server); + return false; + } + + return Marshal.GetLastPInvokeError() == RpcServerUnavailable; + } + + /// OpenPrinterW. A name opens the local print server instead of a printer. + [DllImport("winspool.drv", EntryPoint = "OpenPrinterW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] + private static extern bool OpenPrinter(string? printerName, out IntPtr printer, IntPtr defaults); + + [DllImport("winspool.drv", EntryPoint = "GetPrinterW", ExactSpelling = true, SetLastError = true)] + private static extern bool GetPrinter(IntPtr printer, int level, IntPtr buffer, int bufferSize, out int needed); + + [DllImport("winspool.drv", ExactSpelling = true, SetLastError = true)] + private static extern bool ClosePrinter(IntPtr printer); + + /// + /// PRINTER_INFO_2W. The thirteen pointers come first, so the layout differs between 32-bit and + /// 64-bit processes; declaring them as with sequential layout makes the + /// marshaller place Attributes and Status correctly on both. The strings are not needed, so they + /// stay raw pointers into the native buffer and are never copied. + /// + [StructLayout(LayoutKind.Sequential)] + internal struct PrinterInfo2 + { + /// pServerName. + public IntPtr ServerName; + + /// pPrinterName. + public IntPtr PrinterName; + + /// pShareName. + public IntPtr ShareName; + + /// pPortName. + public IntPtr PortName; + + /// pDriverName. + public IntPtr DriverName; + + /// pComment. + public IntPtr Comment; + + /// pLocation. + public IntPtr Location; + + /// pDevMode. + public IntPtr DevMode; + + /// pSepFile. + public IntPtr SepFile; + + /// pPrintProcessor. + public IntPtr PrintProcessor; + + /// pDatatype. + public IntPtr Datatype; + + /// pParameters. + public IntPtr Parameters; + + /// pSecurityDescriptor. + public IntPtr SecurityDescriptor; + + /// PRINTER_ATTRIBUTE_* bits. + public uint Attributes; + + /// Priority. + public uint Priority; + + /// DefaultPriority. + public uint DefaultPriority; + + /// StartTime. + public uint StartTime; + + /// UntilTime. + public uint UntilTime; + + /// PRINTER_STATUS_* bits. + public uint Status; + + /// cJobs. + public uint Jobs; + + /// AveragePPM. + public uint AveragePpm; + } +} diff --git a/src/PDFStream.NET/ScaleMode.cs b/src/PDFStream.NET/ScaleMode.cs new file mode 100644 index 0000000..8b65ea8 --- /dev/null +++ b/src/PDFStream.NET/ScaleMode.cs @@ -0,0 +1,14 @@ +namespace PDFStream.NET; + +/// How each PDF page is sized onto the paper. +public enum ScaleMode +{ + /// Shrink or enlarge the page to fit the printable area, centred, rotating it to match the paper when that makes it fit better. + FitToPage, + + /// + /// Print at the page's own size (100%) with no scaling, centred, rotating it to match the paper when that keeps more of + /// it on the paper; anything outside the printable area is cut off. + /// + ActualSize, +} diff --git a/tests/PDFStream.NET.Tests/Acceptance/RealPrintTests.cs b/tests/PDFStream.NET.Tests/Acceptance/RealPrintTests.cs new file mode 100644 index 0000000..c5ae352 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Acceptance/RealPrintTests.cs @@ -0,0 +1,470 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Fixtures; +using Xunit; + +namespace PDFStream.NET.Tests.Acceptance; + +/// +/// Acceptance tests that print for real: through the Windows print system to the "Microsoft Print to +/// PDF" printer, written to a file with so no Save As box ever +/// opens. Each test then re-opens the produced PDF with the library's own engine and checks the page +/// count and that every page holds ink, because "printed" must mean pages were drawn, not only that a +/// status said so. +/// +/// +/// +/// Run only these with the xUnit trait filter: dotnet test --project tests/PDFStream.NET.Tests --filter-trait "Category=RealPrinter". +/// A machine without the printer skips every test with a visible reason instead of failing. +/// +/// +/// Safety: every real print runs under a hard . If a dialog ever did open, or the +/// spooler stopped answering, the test fails with a message instead of hanging the run. Output goes only +/// into a folder of its own per test, which is deleted afterwards. +/// +/// +[Trait("Category", "RealPrinter")] +public sealed class RealPrintTests : IDisposable +{ + /// The printer every test prints to. It ships with Windows 10 and 11 and writes a PDF file. + private const string PrinterName = "Microsoft Print to PDF"; + + /// The longest a single print may take before the test fails instead of waiting on a hidden dialog. + private static readonly TimeSpan PrintTimeout = TimeSpan.FromSeconds(60); + + /// + /// How long to wait, after the print call returned, for the output file to be complete and unlocked. Usually it + /// takes a second or two, but on a busy machine the driver once needed more than 30 seconds (a 32-bit run that + /// took over two minutes in all), so the wait is generous; a printer that never finishes still fails the test, + /// with the state of its queue in the message. + /// + private static readonly TimeSpan OutputFileTimeout = TimeSpan.FromSeconds(120); + + /// + /// The resolution the produced pages are rendered at when counting ink. 40 dpi keeps a page small and + /// fast to render while 36 point text still covers hundreds of pixels. + /// + private const int CheckDpi = 40; + + /// + /// The fewest non-white pixels a page must hold to count as printed. A blank page has none; the fixtures' + /// large text produces several hundred even at 40 dpi, so this is far from both extremes. + /// + private const int MinInkPixels = 50; + + private const string UserPassword = "open-sesame"; + + private readonly string _folder; + private readonly ITestOutputHelper _output; + + /// Creates the test class: a new empty temporary folder for this test's output. + public RealPrintTests(ITestOutputHelper output) + { + _output = output; + _folder = Path.Combine(Path.GetTempPath(), "PDFStream.NET-realprint-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_folder); + _output.WriteLine($"Process architecture: {RuntimeInformation.ProcessArchitecture}, runtime: {RuntimeInformation.FrameworkDescription}"); + } + + /// Deletes the temporary folder. A file still held by a stuck spooler job is left to the system's temp cleanup. + public void Dispose() + { + try + { + Directory.Delete(_folder, recursive: true); + } + catch (IOException) + { + // Best effort: failing to delete test output must not turn a passing test red. + } + catch (UnauthorizedAccessException) + { + // Same: the folder is under the temp path and is harmless if it stays. + } + } + + /// A three-page PDF prints to a file that has three pages, each with ink on it. + [Fact] + public void Prints_three_page_pdf_to_file_with_three_pages_and_non_blank_output() + { + RequirePrinter(); + string output = OutputPath("three.pdf"); + + PrintResult result = PrintWithTimeout(FixtureFactory.CreatePdf(3), new PrintOptions { PrinterName = PrinterName, OutputFile = output }); + + Assert.True(result.Succeeded, result.Message); + Assert.Equal(3, result.PagesPrinted); + AssertOutputPages(output, expectedPages: 3); + } + + /// Five pages of mixed sizes and orientations all come out, none blank. + [Fact] + public void Mixed_sizes_and_orientations_print_every_page() + { + RequirePrinter(); + string output = OutputPath("mixed.pdf"); + + PrintResult result = PrintWithTimeout(FixtureFactory.CreatePdf(5, mixedSizes: true), new PrintOptions { PrinterName = PrinterName, OutputFile = output }); + + Assert.True(result.Succeeded, result.Message); + AssertOutputPages(output, expectedPages: 5); + } + + /// A page range prints only the pages named, not the whole document. + [Fact] + public void Page_range_prints_only_selected_pages() + { + RequirePrinter(); + string output = OutputPath("range.pdf"); + + PrintResult result = PrintWithTimeout(FixtureFactory.CreatePdf(5), new PrintOptions { PrinterName = PrinterName, OutputFile = output, Pages = "2, 4-5" }); + + Assert.True(result.Succeeded, result.Message); + Assert.Equal(3, result.PagesPrinted); + AssertOutputPages(output, expectedPages: 3); + } + + /// + /// Two copies give a file with every page twice. Microsoft Print to PDF cannot make copies itself, so + /// this is the library's software copy path; a driver that does make copies is skipped, because its + /// file would hold the pages once. + /// + [Fact] + public void Copies_two_produces_doubled_pages() + { + RequirePrinter(); + int driverMaximum = new System.Drawing.Printing.PrinterSettings { PrinterName = PrinterName }.MaximumCopies; + Assert.SkipWhen(driverMaximum >= 2, $"This machine's '{PrinterName}' driver makes copies itself (it reports {driverMaximum}), so the output file would not hold the pages twice."); + string output = OutputPath("copies.pdf"); + + PrintResult result = PrintWithTimeout(FixtureFactory.CreatePdf(3), new PrintOptions { PrinterName = PrinterName, OutputFile = output, Copies = 2 }); + + Assert.True(result.Succeeded, result.Message); + Assert.Equal(6, result.PagesPrinted); + AssertOutputPages(output, expectedPages: 6); + } + + /// A PDF that needs a password prints when the right one is given. + [Fact] + public void Password_protected_pdf_prints_with_right_password() + { + RequirePrinter(); + string output = OutputPath("protected.pdf"); + + PrintResult result = PrintWithTimeout( + FixtureFactory.CreatePdf(2, userPassword: UserPassword), + new PrintOptions { PrinterName = PrinterName, OutputFile = output, Password = UserPassword }); + + Assert.True(result.Succeeded, result.Message); + AssertOutputPages(output, expectedPages: 2); + } + + /// A wrong password is refused with and no file is written. + [Fact] + public void Wrong_password_returns_PasswordInvalid_and_writes_nothing() + { + RequirePrinter(); + string output = OutputPath("wrong.pdf"); + + PrintResult result = PrintWithTimeout( + FixtureFactory.CreatePdf(2, userPassword: UserPassword), + new PrintOptions { PrinterName = PrinterName, OutputFile = output, Password = "not-the-password" }); + + Assert.Equal(PrintStatus.PasswordInvalid, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.False(File.Exists(output), "A refused job must not leave an output file."); + Assert.Empty(Directory.GetFileSystemEntries(_folder)); + } + + /// + /// Filled-in form fields reach the paper. The fixture page holds nothing but its fields (a filled text field + /// and a ticked checkbox marked for printing, and one screen-only field), so a blank output page means the + /// fields were lost on the way to the printer, which is what happened before PDFStream.NET flattened them. + /// + [Fact] + public void Filled_form_fields_print() + { + RequirePrinter(); + string output = OutputPath("form.pdf"); + + PrintResult result = PrintWithTimeout(FormFixtureFactory.Create(), new PrintOptions { PrinterName = PrinterName, OutputFile = output }); + + Assert.True(result.Succeeded, result.Message); + Assert.Equal(1, result.PagesPrinted); + AssertOutputPages(output, expectedPages: 1); + } + + /// + /// Print to PDF accepts the page as drawing commands on the printer's device context, so the bitmap + /// fallback is never used. The page painter has no public or internal switch that reports this, so the + /// check goes through the engine seam the facade already has: a wrapper around the real engine counts + /// which drawing calls the job makes. + /// + [Fact] + public void Print_to_pdf_uses_the_vector_path_not_the_bitmap_fallback() + { + RequirePrinter(); + string output = OutputPath("vector.pdf"); + var spy = new SpyEngine(new PdfiumEngine()); + var options = new PrintOptions { PrinterName = PrinterName, OutputFile = output }; + + PrintResult result = RunWithTimeout(() => PdfPrinter.Print( + FixtureFactory.CreatePdf(3), + options, + spy, + SystemPrinterCatalog.Instance, + (doc, pages, settings, name, scale, token) => PrintJob.Run(doc, pages, settings, name, scale, token))); + + _output.WriteLine($"Device context renders: {spy.DeviceContextRenders}, bitmap renders: {spy.BitmapRenders}"); + Assert.True(result.Succeeded, result.Message); + Assert.Equal(3, spy.DeviceContextRenders); + Assert.Equal(0, spy.BitmapRenders); + AssertOutputPages(output, expectedPages: 3); + } + + /// Skips the test, with the reason shown in the run, when this machine has no Print to PDF printer. + private static void RequirePrinter() + { + bool installed = false; + try + { + installed = PrinterLocator.FindInstalledName(SystemPrinterCatalog.Instance, PrinterName) is not null; + } + catch (Exception) + { + // An unreachable print system counts as "no printer" for the purpose of skipping. + } + + Assert.SkipUnless(installed, $"The printer '{PrinterName}' is not installed on this machine, so the real-print tests cannot run. Turn on the Windows feature 'Microsoft Print to PDF' and run them again."); + } + + private string OutputPath(string fileName) => Path.Combine(_folder, fileName); + + /// Prints a PDF held in memory through the public API, under the hard timeout. + private static PrintResult PrintWithTimeout(byte[] pdf, PrintOptions options) => + RunWithTimeout(() => PdfPrinter.Print(pdf, options)); + + /// + /// Runs a print on a worker thread and waits at most . A printer dialog + /// waiting for a click would otherwise block the test run forever; here it fails the test with a + /// clear reason. The abandoned worker is a thread-pool thread and does not keep the process alive. + /// + private static PrintResult RunWithTimeout(Func print) + { + Task job = Task.Run(print); + try + { + return job.WaitAsync(PrintTimeout).GetAwaiter().GetResult(); + } + catch (TimeoutException) + { + Assert.Fail($"The print did not finish within {PrintTimeout.TotalSeconds:0} seconds. A hidden Save As dialog or a stuck print spooler is the likely cause: close any open 'Save Print Output As' window and check the printer queue."); + throw; // Unreachable: Assert.Fail always throws. It satisfies the compiler's flow analysis. + } + } + + /// + /// Re-opens the produced file with the library's engine and checks it has the expected number of pages + /// and that every page holds ink. A blank page fails. + /// + private void AssertOutputPages(string path, int expectedPages) + { + byte[] bytes = WaitForOutputFile(path); + + PdfLoadStatus status = new PdfiumEngine().TryLoad(bytes, null, out IPdfDocument? document); + using (document) + { + Assert.Equal(PdfLoadStatus.Ok, status); + Assert.NotNull(document); + Assert.Equal(expectedPages, document.PageCount); + + for (int page = 0; page < document.PageCount; page++) + { + using Bitmap bitmap = document.RenderToBitmap(page, CheckDpi, quarterTurns: 0); + int ink = CountNonWhite(bitmap); + _output.WriteLine($"Output page {page + 1}: {bitmap.Width}x{bitmap.Height} px at {CheckDpi} dpi, {ink} non-white pixels"); + Assert.True(ink >= MinInkPixels, $"Output page {page + 1} is blank or nearly blank ({ink} non-white pixels)."); + } + } + } + + /// + /// Waits until the print system has finished writing the output file and returns its bytes. The print + /// call returns when the job has been handed to the spooler; Microsoft Print to PDF then writes and + /// closes the file on its own schedule, so a read straight after the call can find the file missing, + /// empty or still locked (seen in the 32-bit test host). Any real caller that wants to open the file + /// at once needs the same patience, which is why the wait is explicit here and bounded. + /// + private byte[] WaitForOutputFile(string path) + { + DateTime giveUp = DateTime.UtcNow + OutputFileTimeout; + Exception? lastProblem = null; + while (DateTime.UtcNow < giveUp) + { + try + { + // FileShare.None succeeds only once the writer has closed the file. + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None); + if (stream.Length > 0) + { + var bytes = new byte[stream.Length]; + stream.ReadExactly(bytes); + return bytes; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Not there yet, or still being written: try again shortly. + lastProblem = ex; + } + + Thread.Sleep(100); + } + + Assert.Fail($"The printer did not finish writing {path} within {OutputFileTimeout.TotalSeconds:0} seconds. Last problem: {lastProblem?.Message ?? "the file stayed empty or missing"}. Print queue '{PrinterName}': {DescribeQueue()}."); + throw new InvalidOperationException("Unreachable: Assert.Fail always throws."); + } + + /// + /// The state of the printer's queue as Windows reports it (its status and attribute bits and the number of jobs + /// in it), for a failure message: a paused, stuck or busy queue explains an output file that never appears. + /// Never throws. + /// + private static string DescribeQueue() + { + try + { + PrinterStatusReadOutcome outcome = WinspoolPrinterStatusProbe.Instance.TryRead(PrinterName, out uint status, out uint attributes); + string jobs = CountJobs(PrinterName) is int count ? $"{count} job(s) in the queue" : "the number of jobs could not be read"; + return outcome == PrinterStatusReadOutcome.Read + ? $"status 0x{status:X8}, attributes 0x{attributes:X8}, {jobs}" + : $"status not readable ({outcome}), {jobs}"; + } + catch (Exception ex) + { + return $"not readable ({ex.Message})"; + } + } + + /// The number of jobs in a printer's queue (PRINTER_INFO_2 cJobs), or when it cannot be read. + private static int? CountJobs(string printerName) + { + if (!OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero)) + { + return null; + } + + try + { + // The first call only asks for the size of the variable-length block, and fails by design. + GetPrinter(printer, 2, IntPtr.Zero, 0, out int needed); + if (needed < Marshal.SizeOf()) + { + return null; + } + + IntPtr buffer = Marshal.AllocHGlobal(needed); + try + { + return GetPrinter(printer, 2, buffer, needed, out _) + ? (int)Marshal.PtrToStructure(buffer).Jobs + : null; + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + finally + { + ClosePrinter(printer); + } + } + + /// OpenPrinterW, from the documented Win32 API. + [DllImport("winspool.drv", EntryPoint = "OpenPrinterW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] + private static extern bool OpenPrinter(string printerName, out IntPtr printer, IntPtr defaults); + + /// GetPrinterW, from the documented Win32 API. + [DllImport("winspool.drv", EntryPoint = "GetPrinterW", ExactSpelling = true, SetLastError = true)] + private static extern bool GetPrinter(IntPtr printer, int level, IntPtr buffer, int bufferSize, out int needed); + + /// ClosePrinter, from the documented Win32 API. + [DllImport("winspool.drv", ExactSpelling = true, SetLastError = true)] + private static extern bool ClosePrinter(IntPtr printer); + + /// Counts pixels that are not (nearly) white. Near-white is allowed for because anti-aliasing and compression soften the paper colour. + private static int CountNonWhite(Bitmap bitmap) + { + var area = new Rectangle(0, 0, bitmap.Width, bitmap.Height); + BitmapData data = bitmap.LockBits(area, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + try + { + int count = 0; + var row = new int[bitmap.Width]; + for (int y = 0; y < bitmap.Height; y++) + { + Marshal.Copy(data.Scan0 + (y * data.Stride), row, 0, row.Length); + foreach (int argb in row) + { + if (((argb >> 16) & 0xFF) < 245 || ((argb >> 8) & 0xFF) < 245 || (argb & 0xFF) < 245) + { + count++; + } + } + } + + return count; + } + finally + { + bitmap.UnlockBits(data); + } + } + + /// An engine that opens documents with the real engine and counts the drawing calls made on them. + private sealed class SpyEngine(IPdfEngine inner) : IPdfEngine + { + private int _deviceContextRenders; + private int _bitmapRenders; + + /// Pages sent to the printer's device context (the vector path). + public int DeviceContextRenders => Volatile.Read(ref _deviceContextRenders); + + /// Pages rendered to a bitmap (the fallback, which must not happen for Print to PDF). + public int BitmapRenders => Volatile.Read(ref _bitmapRenders); + + /// + public PdfLoadStatus TryLoad(byte[] pdf, string? password, out IPdfDocument? document) + { + PdfLoadStatus status = inner.TryLoad(pdf, password, out IPdfDocument? real); + document = real is null ? null : new SpyDocument(real, this); + return status; + } + + private sealed class SpyDocument(IPdfDocument real, SpyEngine owner) : IPdfDocument + { + public int PageCount => real.PageCount; + + public SizeF GetPageSizePoints(int pageIndex) => real.GetPageSizePoints(pageIndex); + + public void RenderToDeviceContext(int pageIndex, IntPtr hdc, Rectangle destinationPixels, bool forPrinting, int quarterTurns) + { + // Counted only when the engine accepted the drawing: a refusal throws and the painter falls back. + real.RenderToDeviceContext(pageIndex, hdc, destinationPixels, forPrinting, quarterTurns); + Interlocked.Increment(ref owner._deviceContextRenders); + } + + public Bitmap RenderToBitmap(int pageIndex, int dpi, int quarterTurns) + { + Interlocked.Increment(ref owner._bitmapRenders); + return real.RenderToBitmap(pageIndex, dpi, quarterTurns); + } + + public void Dispose() => real.Dispose(); + } + } +} diff --git a/tests/PDFStream.NET.Tests/Engine/FormFieldRenderingTests.cs b/tests/PDFStream.NET.Tests/Engine/FormFieldRenderingTests.cs new file mode 100644 index 0000000..74dde8b --- /dev/null +++ b/tests/PDFStream.NET.Tests/Engine/FormFieldRenderingTests.cs @@ -0,0 +1,1512 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Fixtures; +using PDFStream.NET.Tests.Printing; +using Xunit; + +namespace PDFStream.NET.Tests.Engine; + +/// +/// Filled-in PDF form fields must reach the paper. PDFium's two page-drawing calls never draw form-field +/// widgets on their own, so these tests render hand-made form PDFs (see ) +/// through both of PDFStream.NET's print paths and check the pixels: fields marked for printing are inked, +/// a field without the Print flag is not, and everything the page drew before (its own content and its +/// ordinary annotations, and what it draws through resources it inherits from the page tree) is still drawn, +/// at the same size and in the same place. Pages without form fields must come out exactly as PDFium draws +/// them, and in a document with several pages each page index keeps drawing its own page. +/// +public sealed class FormFieldRenderingTests +{ + /// 72 dpi makes one pixel one point, so the 400 x 300 point fixture page is 400 x 300 pixels. + private const int Dpi = 72; + + /// + /// The share of a field's inner rectangle that must be dark for the field to count as drawn. Its stored + /// appearance is solid black, so a drawn field is (nearly) 100% dark and a missing one 0%. + /// + private const double FullyInked = 0.95; + + private readonly PdfiumEngine _engine = new(); + private readonly ITestOutputHelper _output; + + /// Creates the test class with xUnit's per-test output sink. + public FormFieldRenderingTests(ITestOutputHelper output) + { + _output = output; + _output.WriteLine($"Process architecture: {RuntimeInformation.ProcessArchitecture}, runtime: {RuntimeInformation.FrameworkDescription}"); + } + + /// The two ways PDFStream.NET puts a page on paper. + public enum RenderPath + { + /// The bitmap fallback: . + Bitmap, + + /// The vector path printers normally get: . + DeviceContext, + } + + /// Variants of a form page whose layout must not change when its fields are drawn. + public static TheoryData LayoutVariants() + { + var data = new TheoryData(); + foreach (string variant in new[] { "content and markup", "inherited page attributes", "page resources", "inherited resources", "hidden layer", "crop box", "rotate 90", "everything at once" }) + { + data.Add(variant, RenderPath.Bitmap); + data.Add(variant, RenderPath.DeviceContext); + } + + return data; + } + + /// Pages without any form field, which must be drawn exactly as PDFium draws them. + public static TheoryData FormLessPages() + { + var data = new TheoryData(); + foreach (string page in new[] { "text page", "page with content and markup annotations", "page inheriting its resources" }) + { + data.Add(page, RenderPath.Bitmap); + data.Add(page, RenderPath.DeviceContext); + } + + return data; + } + + /// A filled text field and a ticked checkbox, both marked for printing, are drawn on both paths. + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Filled_text_field_and_ticked_checkbox_are_drawn(RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create()); + using Bitmap page = Render(document, path); + + AssertInked(page, FormFixtureFactory.TextField, "the filled text field"); + AssertInked(page, FormFixtureFactory.CheckBox, "the ticked checkbox"); + } + + /// A field without the Print flag is a screen-only field and stays off the paper. + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Field_without_the_print_flag_is_not_drawn(RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create()); + using Bitmap page = Render(document, path); + + int dark = Pixels.CountDarkIn(page, FormFixtureFactory.NonPrintingField.ToInnerPixels(Dpi)); + _output.WriteLine($"Dark pixels in the non-printing field: {dark}"); + Assert.Equal(0, dark); + } + + /// + /// Widget annotations on a page whose catalog has no /AcroForm (what page-extraction tools often leave) + /// are drawn too: the decision is made per page, from the annotations the page really has. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Fields_are_drawn_when_the_catalog_has_no_AcroForm(RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create(new FormFixtureOptions { WithAcroForm = false })); + using Bitmap page = Render(document, path); + + AssertInked(page, FormFixtureFactory.TextField, "the filled text field"); + AssertInked(page, FormFixtureFactory.CheckBox, "the ticked checkbox"); + } + + /// + /// A field that holds a value but no stored appearance, in a form that says /NeedAppearances true, is + /// drawn from its value: PDFium's form engine builds the appearance first. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Field_value_without_a_stored_appearance_is_drawn_when_the_form_asks_for_it(RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create(new FormFixtureOptions { NeedAppearances = true })); + using Bitmap page = Render(document, path); + + // The built appearance is the text HELLO in 24 point Helvetica, so only part of the field is inked. + int dark = Pixels.CountDarkIn(page, FormFixtureFactory.TextField.ToInnerPixels(Dpi)); + _output.WriteLine($"Dark pixels in the text field built from its value: {dark}"); + Assert.True(dark > 100, $"Expected the field's value to be drawn, found {dark} dark pixels in the field."); + } + + /// + /// A field that holds a value but no stored appearance is drawn from its value even when the form does not + /// say /NeedAppearances: PDFium's form engine builds the missing appearance. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Field_value_without_a_stored_appearance_is_drawn_even_when_the_form_does_not_ask_for_it(RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create(new FormFixtureOptions { TextFieldHasStoredAppearance = false })); + using Bitmap page = Render(document, path); + + int dark = Pixels.CountDarkIn(page, FormFixtureFactory.TextField.ToInnerPixels(Dpi)); + _output.WriteLine($"Dark pixels in the text field built from its value: {dark}"); + Assert.True(dark > 100, $"Expected the field's value to be drawn, found {dark} dark pixels in the field."); + AssertInked(page, FormFixtureFactory.CheckBox, "the ticked checkbox"); + } + + /// + /// Drawing the fields changes nothing else: the page keeps its size before and after a render, and every + /// pixel PDFium draws for the page without its fields (page content, ordinary annotations with and without + /// a stored appearance, marks drawn through the page's resources) is still dark, in the same place, while the + /// fields add their own ink. Covers inherited page attributes and inherited resources, a crop box and a + /// rotated page, where the boxes and the resources are easiest to disturb. + /// + [Theory] + [MemberData(nameof(LayoutVariants))] + public void Everything_else_on_a_form_page_is_still_drawn_in_the_same_place(string variant, RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(Variant(variant)); + SizeF expected = RawPdfium.PageSize(pdf); + + using IPdfDocument document = Load(pdf); + SizeF before = document.GetPageSizePoints(0); + using Bitmap ours = Render(document, path); + SizeF after = document.GetPageSizePoints(0); + using Bitmap reference = Reference(pdf, path, ours.Size); + + Assert.Equal(expected, before); + Assert.Equal(expected, after); + + (int lost, int gained) = CompareInk(reference, ours); + + // Both fields lie inside the crop box, so all of their area must turn up as new ink. + int fieldArea = FieldArea; + _output.WriteLine($"{variant}, {path}: page {ours.Width} x {ours.Height}, reference ink {Pixels.CountDark(reference)}, lost {lost}, gained {gained} (field area {fieldArea})"); + Assert.Equal(0, lost); + AssertFieldsAddTheirAreaAndNothingElse(gained, fieldArea); + } + + /// A page without any form field is drawn exactly, pixel for pixel, as PDFium alone draws it. + [Theory] + [MemberData(nameof(FormLessPages))] + public void Form_less_page_is_drawn_exactly_as_PDFium_draws_it(string page, RenderPath path) + { + byte[] pdf = page switch + { + "text page" => FixtureFactory.CreatePdf(1), + "page with content and markup annotations" => FormFixtureFactory.Create(new FormFixtureOptions { WithFields = false, WithPageContent = true, WithMarkupAnnotations = true }), + "page inheriting its resources" => FormFixtureFactory.Create(new FormFixtureOptions { WithFields = false, WithPageContent = true, WithResourceMarks = true, InheritPageAttributes = true }), + _ => throw new ArgumentOutOfRangeException(nameof(page), page, "Unknown page."), + }; + + using IPdfDocument document = Load(pdf); + using Bitmap ours = Render(document, path); + using Bitmap reference = Reference(pdf, path, ours.Size); + + Assert.True(Pixels.CountDark(reference) > 100, "The reference rendering should hold the page's ink."); + AssertSamePixels(reference, ours); + } + + /// + /// Marks a form page draws through named entries of its /Resources (a form XObject, an image and a glyph of + /// a Type3 font) are still drawn next to its fields, whether the page has its own /Resources or inherits + /// them from the page tree. Flattening the fields into the page itself gave a page that inherits its + /// resources an empty /Resources of its own, which hid the inherited ones: the XObject and the image + /// vanished and the glyph fell back to a Helvetica letter, while the print still reported success. + /// + [Theory] + [InlineData(true, RenderPath.Bitmap)] + [InlineData(true, RenderPath.DeviceContext)] + [InlineData(false, RenderPath.Bitmap)] + [InlineData(false, RenderPath.DeviceContext)] + public void Marks_drawn_through_the_page_resources_are_drawn_next_to_the_fields(bool inherited, RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create(new FormFixtureOptions { WithResourceMarks = true, InheritPageAttributes = inherited })); + using Bitmap page = Render(document, path); + + AssertAllInked(page, ResourceMarksAndFields(inherited ? "inherited" : "own")); + } + + /// + /// A form page with a layer the PDF switches off keeps that layer off the paper while its fields print. A + /// copy of the page would show the layer (its layer objects are copies, which the document's layer settings + /// do not name), so this page has its fields flattened into the page itself. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void A_layer_the_pdf_switches_off_stays_off_the_paper_on_a_form_page(RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(new FormFixtureOptions { WithPageContent = true, WithResourceMarks = true, WithHiddenLayer = true }); + Rectangle hidden = FormFixtureFactory.HiddenLayerMark.ToInnerPixels(Dpi); + + using IPdfDocument document = Load(pdf); + using Bitmap ours = Render(document, path); + using Bitmap reference = Reference(pdf, path, ours.Size); + + Assert.Equal(0, Pixels.CountDarkIn(reference, hidden)); + int darkInHiddenLayer = Pixels.CountDarkIn(ours, hidden); + _output.WriteLine($"Dark pixels in the switched-off layer's square: {darkInHiddenLayer}"); + Assert.Equal(0, darkInHiddenLayer); + AssertAllInked(ours, ResourceMarksAndFields("own")); + + (int lost, int gained) = CompareInk(reference, ours); + _output.WriteLine($"{path}: lost {lost}, gained {gained}"); + Assert.Equal(0, lost); + AssertFieldsAddTheirAreaAndNothingElse(gained, FieldArea); + } + + /// + /// A password-protected (AES-256) form PDF prints its fields and everything else on the page, the same as + /// plain PDFium draws the page plus the fields. PDFsharp, which encrypts the fixture, writes the inherited + /// attributes onto the page (and adds a transparency group), so this covers the copy of an encrypted page, + /// not inheritance. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void A_password_protected_form_page_prints_its_fields_and_everything_else(RenderPath path) + { + const string Password = "secret"; + byte[] pdf = FixtureFactory.Encrypt(FormFixtureFactory.Create(Variant("inherited resources")), Password); + Assert.Equal(PdfLoadStatus.PasswordRequired, _engine.TryLoad(pdf, null, out _)); + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(pdf, Password, out IPdfDocument? document)); + + using (document) + using (Bitmap ours = Render(document!, path)) + using (Bitmap reference = path == RenderPath.Bitmap + ? RawPdfium.RenderBitmap(pdf, ours.Width, ours.Height, password: Password) + : RawPdfium.RenderOnDeviceContext(pdf, ours.Width, ours.Height, password: Password)) + { + AssertAllInked(ours, ResourceMarksAndFields("encrypted")); + (int lost, int gained) = CompareInk(reference, ours); + _output.WriteLine($"{path}: lost {lost}, gained {gained}"); + Assert.Equal(0, lost); + AssertFieldsAddTheirAreaAndNothingElse(gained, FieldArea); + } + } + + /// + /// In a document whose second page is a form page (inheriting its attributes and resources) and whose first + /// page is a plain page of another size, each page index keeps drawing its own page, in any order and again: + /// the plain page exactly as PDFium draws it, the form page with its fields and everything else it draws. + /// The page count and the page sizes stay those of the PDF, and no index past the last page becomes usable + /// once the form page has been drawn. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Each_page_of_a_document_with_a_form_page_draws_its_own_page(RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(new FormFixtureOptions { WithLeadingPlainPage = true, InheritPageAttributes = true, WithPageContent = true, WithResourceMarks = true }); + SizeF plainSize = RawPdfium.PageSize(pdf, 0); + SizeF formSize = RawPdfium.PageSize(pdf, 1); + Assert.NotEqual(plainSize, formSize); + + using IPdfDocument document = Load(pdf); + Assert.Equal(2, document.PageCount); + + // The form page first, so whatever is done to prepare it is done before the plain page is drawn. + using Bitmap form = Render(document, path, pageIndex: 1); + using Bitmap plain = Render(document, path, pageIndex: 0); + using Bitmap formAgain = Render(document, path, pageIndex: 1); + using Bitmap plainReference = Reference(pdf, path, plain.Size, pageIndex: 0); + using Bitmap formReference = Reference(pdf, path, form.Size, pageIndex: 1); + + AssertSamePixels(plainReference, plain); + AssertInked(plain, FormFixtureFactory.LeadingPageMark.ToInnerPixels(Dpi, FormFixtureFactory.LeadingPageHeightPoints), "the plain page's black square"); + + (int lost, int gained) = CompareInk(formReference, form); + _output.WriteLine($"Form page, {path}: lost {lost}, gained {gained}"); + Assert.Equal(0, lost); + AssertFieldsAddTheirAreaAndNothingElse(gained, FieldArea); + AssertAllInked(form, ResourceMarksAndFields("inherited")); + AssertSamePixels(form, formAgain); + + Assert.Equal(2, document.PageCount); + Assert.Equal(plainSize, document.GetPageSizePoints(0)); + Assert.Equal(formSize, document.GetPageSizePoints(1)); + Assert.Throws(() => document.GetPageSizePoints(2)); + Assert.Throws(() => document.RenderToBitmap(2, Dpi, quarterTurns: 0)); + } + + /// + /// One form document drawn from two threads at the same moment, one thread on each print path, starting + /// before its form page has ever been drawn (so both threads race to prepare it): every picture is the one a + /// single thread draws, fields and resource marks included. + /// + [Fact] + public async Task One_form_document_drawn_from_two_threads_at_once_gives_the_same_pictures() + { + const int Rounds = 5; + byte[] pdf = FormFixtureFactory.Create(Variant("inherited resources")); + + // What one thread alone draws, each from a document of its own. + using IPdfDocument bitmapDocument = Load(pdf); + using IPdfDocument deviceContextDocument = Load(pdf); + using Bitmap expectedBitmap = Render(bitmapDocument, RenderPath.Bitmap); + using Bitmap expectedDeviceContext = Render(deviceContextDocument, RenderPath.DeviceContext); + AssertAllInked(expectedBitmap, ResourceMarksAndFields("inherited")); + AssertAllInked(expectedDeviceContext, ResourceMarksAndFields("inherited")); + + using IPdfDocument shared = Load(pdf); + using var barrier = new Barrier(2); + + int DrawRepeatedly(RenderPath path, Bitmap expected) + { + if (!barrier.SignalAndWait(TimeSpan.FromSeconds(30))) + { + throw new TimeoutException("The other thread never started."); + } + + for (int round = 0; round < Rounds; round++) + { + using Bitmap page = Render(shared, path); + AssertSamePixels(expected, page); + } + + return Rounds; + } + + Task bitmaps = Task.Factory.StartNew(() => DrawRepeatedly(RenderPath.Bitmap, expectedBitmap), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task deviceContexts = Task.Factory.StartNew(() => DrawRepeatedly(RenderPath.DeviceContext, expectedDeviceContext), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + int[] results = await Task.WhenAll(bitmaps, deviceContexts).WaitAsync(TimeSpan.FromMinutes(2), TestContext.Current.CancellationToken); + + Assert.Equal([Rounds, Rounds], results); + } + + /// + /// The size of the pictures drawn to compare a form page with its copy stays within a fixed budget whatever the + /// page size: neither side above pixels and the area within + /// . A page too extreme to compare is not compared at all. + /// + [Theory] + [InlineData(612f, 792f)] + [InlineData(400f, 300f)] + [InlineData(14400f, 14400f)] + [InlineData(1_000_000f, 1_000_000f)] + [InlineData(14400f, 100f)] + [InlineData(100_000_000f, 1f)] + [InlineData(1f, 100_000_000f)] + [InlineData(1e12f, 1f)] + [InlineData(float.MaxValue, float.MaxValue)] + [InlineData(float.MaxValue, 1f)] + public void The_comparison_never_draws_more_than_its_budget(float widthPoints, float heightPoints) + { + if (PdfiumDocument.TryGetComparisonSize(widthPoints, heightPoints, out int width, out int height)) + { + _output.WriteLine($"{widthPoints} x {heightPoints} points: compared at {width} x {height} pixels"); + AssertWithinComparisonBudget(width, height); + } + else + { + _output.WriteLine($"{widthPoints} x {heightPoints} points: not compared"); + } + } + + /// An ordinary page is compared at one pixel per point, and a very large one within the budget. + [Fact] + public void Ordinary_and_very_large_pages_are_compared() + { + Assert.True(PdfiumDocument.TryGetComparisonSize(612f, 792f, out int width, out int height)); + Assert.Equal((612, 792), (width, height)); + + Assert.True(PdfiumDocument.TryGetComparisonSize(1_000_000f, 1_000_000f, out width, out height)); + AssertWithinComparisonBudget(width, height); + Assert.Equal(width, height); + } + + /// + /// A page size that is not a real size (not a number, infinite, zero or negative), or so small or so long and + /// thin that a side would be under one pixel, is not compared: the page takes the fallback for a copy that + /// cannot be verified. + /// + [Theory] + [InlineData(float.NaN, 300f)] + [InlineData(400f, float.NaN)] + [InlineData(float.PositiveInfinity, 300f)] + [InlineData(400f, float.NegativeInfinity)] + [InlineData(0f, 300f)] + [InlineData(400f, 0f)] + [InlineData(-400f, 300f)] + [InlineData(0.5f, 0.5f)] + [InlineData(100_000_000f, 1f)] + [InlineData(1e12f, 1f)] + public void Pages_too_odd_to_compare_are_not_compared(float widthPoints, float heightPoints) + { + Assert.False(PdfiumDocument.TryGetComparisonSize(widthPoints, heightPoints, out _, out _)); + } + + /// + /// Pages of extreme sizes and shapes print without an exception, and every picture drawn to compare a form page + /// with its copy stays within the budget (checked on the sizes handed to the comparison render). + /// + [Theory] + [InlineData("very wide and thin form page")] + [InlineData("very large form page")] + [InlineData("tiny form page")] + [InlineData("extremely wide form page")] + [InlineData("very wide and thin page without fields")] + public void Pages_of_extreme_size_print_and_their_comparison_stays_within_budget(string shape) + { + FormFixtureOptions options = shape switch + { + "very wide and thin form page" => new FormFixtureOptions { MediaBox = new PdfRect(0, 0, 100_000_000, 1) }, + "very large form page" => new FormFixtureOptions { MediaBox = new PdfRect(0, 0, 1_000_000, 1_000_000) }, + "tiny form page" => new FormFixtureOptions { MediaBox = new PdfRect(0, 0, 0.5f, 0.5f) }, + "extremely wide form page" => new FormFixtureOptions { MediaBox = new PdfRect(0, 0, 1e12f, 1) }, + "very wide and thin page without fields" => new FormFixtureOptions { WithFields = false, WithPageContent = true, MediaBox = new PdfRect(0, 0, 100_000_000, 1) }, + _ => throw new ArgumentOutOfRangeException(nameof(shape), shape, "Unknown shape."), + }; + + using IPdfDocument document = Load(FormFixtureFactory.Create(options)); + var sizes = new List<(int Width, int Height)>(); + ((PdfiumDocument)document).ComparisonRendered = (width, height) => sizes.Add((width, height)); + + using var controller = new FakePrintController(); + PrintResult result = PrintJob.Run(document, [0], TestPrinters.Settings(), "Extreme page", ScaleMode.FitToPage, CancellationToken.None, controller); + + _output.WriteLine($"{shape}: page {document.GetPageSizePoints(0)}, comparison renders: {string.Join(", ", sizes)}, result {result.Status}"); + Assert.True(result.Succeeded, result.Message); + Assert.Equal(1, result.PagesPrinted); + foreach ((int width, int height) in sizes) + { + AssertWithinComparisonBudget(width, height); + } + } + + /// Rendering the same form page again (as copies do) gives the same picture, fields included. + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Rendering_a_form_page_twice_gives_the_same_picture(RenderPath path) + { + using IPdfDocument document = Load(FormFixtureFactory.Create(new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true })); + using Bitmap first = Render(document, path); + using Bitmap second = Render(document, path); + + AssertInked(second, FormFixtureFactory.TextField, "the filled text field on the second render"); + AssertSamePixels(first, second); + } + + /// A form document that has been rendered closes cleanly, also when disposed twice. + [Fact] + public void Disposing_a_rendered_form_document_is_safe() + { + IPdfDocument document = Load(FormFixtureFactory.Create(new FormFixtureOptions { NeedAppearances = true })); + using (Render(document, RenderPath.Bitmap)) + { + } + + document.Dispose(); + document.Dispose(); + Assert.Throws(() => document.GetPageSizePoints(0)); + } + + /// + /// Two threads loading and rendering form documents at the same moment both get their fields drawn: the + /// form handling runs under the same process-wide lock as every other PDFium call. + /// + [Fact] + public async Task Two_threads_rendering_form_documents_at_once_both_draw_the_fields() + { + const int Rounds = 5; + byte[] pdf = FormFixtureFactory.Create(new FormFixtureOptions { NeedAppearances = true, WithMarkupAnnotations = true }); + using var barrier = new Barrier(2); + + int RenderRepeatedly() + { + if (!barrier.SignalAndWait(TimeSpan.FromSeconds(30))) + { + throw new TimeoutException("The second thread never started."); + } + + int pagesWithFields = 0; + for (int round = 0; round < Rounds; round++) + { + using IPdfDocument document = Load(pdf); + using Bitmap page = Render(document, RenderPath.Bitmap); + if (Pixels.CountDarkIn(page, FormFixtureFactory.TextField.ToInnerPixels(Dpi)) > 100) + { + pagesWithFields++; + } + } + + return pagesWithFields; + } + + Task first = Task.Factory.StartNew(RenderRepeatedly, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task second = Task.Factory.StartNew(RenderRepeatedly, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + int[] results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromMinutes(2), TestContext.Current.CancellationToken); + + Assert.Equal(Rounds, results[0]); + Assert.Equal(Rounds, results[1]); + } + + /// + /// A page whose fields cannot be flattened (PDFium reports failure, or the call throws, as a pdfium.dll + /// without the function would) is drawn exactly as PDFium draws it without any form handling: the fields + /// stay blank, as before, and nothing else changes. + /// + [Theory] + [InlineData("reports failure", RenderPath.Bitmap)] + [InlineData("reports failure", RenderPath.DeviceContext)] + [InlineData("throws", RenderPath.Bitmap)] + [InlineData("throws", RenderPath.DeviceContext)] + public void A_page_that_cannot_be_flattened_is_drawn_as_it_is(string failure, RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(Variant("inherited resources")); + var engine = new PdfiumEngine(FailingFlattener(failure)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + using (Bitmap ours = Render(document!, path)) + using (Bitmap reference = path == RenderPath.Bitmap + ? RawPdfium.RenderBitmap(pdf, ours.Width, ours.Height) + : RawPdfium.RenderOnDeviceContext(pdf, ours.Width, ours.Height)) + { + AssertInked(ours, FormFixtureFactory.PageMark, "the page's own black square"); + AssertSamePixels(reference, ours); + } + } + + /// + /// A page that cannot be copied (PDFium reports failure, or the call throws, as a pdfium.dll without the + /// function would) has its fields flattened into the page itself, as before the copy was introduced: the + /// fields print, and the page is flattened exactly once. A page with its own resources loses nothing. A page + /// that takes its resources from the page tree loses what it draws through them, which is the documented + /// limitation of that fallback (an empty /Resources of its own then hides the inherited one). + /// + [Theory] + [InlineData("reports failure", RenderPath.Bitmap, false)] + [InlineData("reports failure", RenderPath.DeviceContext, false)] + [InlineData("throws", RenderPath.Bitmap, false)] + [InlineData("throws", RenderPath.DeviceContext, false)] + [InlineData("reports failure", RenderPath.Bitmap, true)] + [InlineData("reports failure", RenderPath.DeviceContext, true)] + [InlineData("throws", RenderPath.Bitmap, true)] + [InlineData("throws", RenderPath.DeviceContext, true)] + public void A_page_that_cannot_be_copied_has_its_fields_drawn_into_the_page_itself(string failure, RenderPath path, bool inherited) + { + byte[] pdf = FormFixtureFactory.Create(Variant(inherited ? "inherited resources" : "page resources")); + int flattened = 0; + var engine = new PdfiumEngine(CountingFlattener(() => Interlocked.Increment(ref flattened)), FailingCopier(failure)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + using (Bitmap ours = Render(document!, path)) + using (Bitmap reference = Reference(pdf, path, ours.Size)) + { + AssertFieldsDrawnIntoThePageItself(ours, reference, inherited, path); + } + + Assert.Equal(1, flattened); + } + + /// + /// A copy that does not come out exactly the size of the page is not used (whatever it printed would land + /// in the wrong place) and is never flattened: the fields are flattened into the page itself instead, once, + /// with the documented loss for a page that takes its resources from the page tree. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void A_copy_that_is_not_the_size_of_the_page_is_not_used(RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(Variant("inherited resources")); + int flattened = 0; + var engine = new PdfiumEngine( + CountingFlattener(() => Interlocked.Increment(ref flattened)), + (document, pageIndices, insertAt) => + { + // A real copy, then made 100 points narrower, as a misbehaving copy might be. + bool copied = PdfiumNative.FPDF_ImportPagesByIndex(document, document, pageIndices, (uint)pageIndices.Length, insertAt) != 0; + IntPtr copy = PdfiumNative.FPDF_LoadPage(document, insertAt); + Assert.NotEqual(IntPtr.Zero, copy); + PdfiumNative.FPDFPage_SetMediaBox(copy, 0, 0, FormFixtureFactory.PageWidthPoints - 100, FormFixtureFactory.PageHeightPoints); + PdfiumNative.FPDF_ClosePage(copy); + return copied; + }); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + using (Bitmap ours = Render(document!, path)) + using (Bitmap reference = Reference(pdf, path, ours.Size)) + { + Assert.Equal(new SizeF(FormFixtureFactory.PageWidthPoints, FormFixtureFactory.PageHeightPoints), document!.GetPageSizePoints(0)); + AssertFieldsDrawnIntoThePageItself(ours, reference, inherited: true, path); + } + + Assert.Equal(1, flattened); + } + + /// + /// A copy whose fields cannot be flattened (the first flatten, on the copy, fails) is not used: the fields are + /// flattened into the page itself instead, so they still print. + /// + [Theory] + [InlineData("reports failure", RenderPath.Bitmap)] + [InlineData("reports failure", RenderPath.DeviceContext)] + [InlineData("throws", RenderPath.Bitmap)] + [InlineData("throws", RenderPath.DeviceContext)] + public void A_copy_whose_fields_cannot_be_flattened_has_them_drawn_into_the_page_itself(string failure, RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(Variant("page resources")); + int calls = 0; + PageFlattener failFirst = FailingFlattener(failure); + var engine = new PdfiumEngine((page, usage) => Interlocked.Increment(ref calls) == 1 ? failFirst(page, usage) : PdfiumNative.FPDFPage_Flatten(page, usage)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + using (Bitmap ours = Render(document!, path)) + using (Bitmap reference = Reference(pdf, path, ours.Size)) + { + AssertFieldsDrawnIntoThePageItself(ours, reference, inherited: false, path); + } + + Assert.Equal(2, calls); + } + + /// + /// A page whose annotation list also names an object the file does not contain (a damaged reference) still + /// prints its fields, and everything else on it, on both paths. PDFium's page copy drops the whole annotation + /// list because of that one entry, so the copy has no fields at all, and drawing it would leave them blank + /// (the pixel check cannot see this, because it is drawn without the fields). Such a copy must not be used: + /// the fields are drawn into the page itself. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void A_damaged_reference_in_the_annotation_list_does_not_leave_the_fields_blank(RenderPath path) + { + byte[] pdf = FormFixtureFactory.Create(new FormFixtureOptions { WithPageContent = true, WithDanglingAnnotationReference = true }); + + using IPdfDocument document = Load(pdf); + using Bitmap ours = Render(document, path); + using Bitmap reference = Reference(pdf, path, ours.Size); + + AssertInked(ours, FormFixtureFactory.TextField, "the filled text field"); + AssertInked(ours, FormFixtureFactory.CheckBox, "the ticked checkbox"); + AssertInked(ours, FormFixtureFactory.PageMark, "the page's own black square"); + (int lost, int gained) = CompareInk(reference, ours); + _output.WriteLine($"{path}: lost {lost}, gained {gained}"); + Assert.Equal(0, lost); + AssertFieldsAddTheirAreaAndNothingElse(gained, FieldArea); + } + + /// A print job over a page that cannot be copied still succeeds and prints the page. + [Theory] + [InlineData("reports failure")] + [InlineData("throws")] + public void A_print_job_whose_page_cannot_be_copied_still_prints(string failure) + { + var engine = new PdfiumEngine(flattenPage: null, FailingCopier(failure)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(FormFixtureFactory.Create(new FormFixtureOptions { WithPageContent = true }), null, out IPdfDocument? document)); + + using (document) + using (var controller = new FakePrintController()) + { + PrintResult result = PrintJob.Run(document!, [0], TestPrinters.Settings(), "Form", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.True(result.Succeeded, result.Message); + Assert.Equal(1, result.PagesPrinted); + Assert.True(Pixels.CountDark(controller.Pages[0]) > 100, "Expected the page content on the sheet."); + } + } + + /// A print job over a page that cannot be flattened still succeeds and prints the page. + [Theory] + [InlineData("reports failure")] + [InlineData("throws")] + public void A_print_job_whose_page_cannot_be_flattened_still_prints(string failure) + { + var engine = new PdfiumEngine(FailingFlattener(failure)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(FormFixtureFactory.Create(new FormFixtureOptions { WithPageContent = true }), null, out IPdfDocument? document)); + + using (document) + using (var controller = new FakePrintController()) + { + PrintResult result = PrintJob.Run(document!, [0], TestPrinters.Settings(), "Form", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.True(result.Succeeded, result.Message); + Assert.Equal(1, result.PagesPrinted); + Assert.True(Pixels.CountDark(controller.Pages[0]) > 100, "Expected the page content on the sheet."); + } + } + + /// A page without form fields is never copied or flattened, however often it is drawn. + [Fact] + public void A_page_without_form_fields_is_never_flattened() + { + int calls = 0; + var engine = new PdfiumEngine( + (page, usage) => + { + Interlocked.Increment(ref calls); + return PdfiumNative.FPDFPage_Flatten(page, usage); + }, + (document, pageIndices, insertAt) => + { + Interlocked.Increment(ref calls); + return PdfiumNative.FPDF_ImportPagesByIndex(document, document, pageIndices, (uint)pageIndices.Length, insertAt) != 0; + }); + byte[] pdf = FormFixtureFactory.Create(new FormFixtureOptions { WithFields = false, WithPageContent = true, WithMarkupAnnotations = true }); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + { + Render(document!, RenderPath.Bitmap).Dispose(); + Render(document!, RenderPath.DeviceContext).Dispose(); + } + + Assert.Equal(0, calls); + } + + /// + /// A form page is copied once, to the end of the document, and the copy flattened once, for printing, however + /// often and by whichever path the page is drawn. + /// + [Fact] + public void A_form_page_is_flattened_once_for_printing() + { + var usages = new List(); + var copies = new List<(int[] Pages, int InsertAt)>(); + var engine = new PdfiumEngine( + (page, usage) => + { + lock (usages) + { + usages.Add(usage); + } + + return PdfiumNative.FPDFPage_Flatten(page, usage); + }, + (document, pageIndices, insertAt) => + { + lock (copies) + { + copies.Add((pageIndices, insertAt)); + } + + return PdfiumNative.FPDF_ImportPagesByIndex(document, document, pageIndices, (uint)pageIndices.Length, insertAt) != 0; + }); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(FormFixtureFactory.Create(), null, out IPdfDocument? document)); + + using (document) + { + Render(document!, RenderPath.DeviceContext).Dispose(); + Render(document!, RenderPath.Bitmap).Dispose(); + using Bitmap third = Render(document!, RenderPath.DeviceContext); + AssertInked(third, FormFixtureFactory.TextField, "the filled text field on the third render"); + } + + Assert.Equal([PdfiumNative.FlattenForPrint], usages); + (int[] pages, int insertAt) = Assert.Single(copies); + Assert.Equal([0], pages); + Assert.Equal(1, insertAt); + } + + /// + /// The pages with form fields are copied in one PDFium call, whichever path draws them and in whatever order, + /// so an object they share (here one resource dictionary with its images, inherited from the page tree or + /// named by every page) is copied once, not once per page. Copying page by page made memory grow with the + /// number of form pages times the size of what they share. Every page still shows its image and its field. + /// + [Theory] + [InlineData(SharedResources.Inherited)] + [InlineData(SharedResources.Indirect)] + public void All_form_pages_are_copied_in_one_go(SharedResources resources) + { + const int Pages = 12; + byte[] pdf = SharedResourceFixtureFactory.Create(Pages, images: 2, withFields: true, resources); + var copies = new List<(int[] Pages, int InsertAt)>(); + var engine = new PdfiumEngine(flattenPage: null, RecordingCopier(copies)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + { + foreach (int page in new[] { 5, 0, 11, 1, 2, 3, 4, 6, 7, 8, 9, 10, 5 }) + { + using Bitmap picture = Render(document!, page % 2 == 0 ? RenderPath.Bitmap : RenderPath.DeviceContext, page); + AssertSharedResourcePage(picture, page); + } + } + + (int[] pages, int insertAt) = Assert.Single(copies); + Assert.Equal(Enumerable.Range(0, Pages), pages); + Assert.Equal(Pages, insertAt); + } + + /// + /// When the pages share one resource dictionary, each page still draws only its own field, also when a page + /// is drawn again after the others. Flattening a copy adds its fields to the copy's resources under a new + /// name (FFT0, FFT1, ...); with copies that share one dictionary every flatten adds to the same one, so a page + /// that drew another page's name would print that page's fields. + /// + [Theory] + [InlineData(SharedResources.Inherited, RenderPath.Bitmap)] + [InlineData(SharedResources.Inherited, RenderPath.DeviceContext)] + [InlineData(SharedResources.Indirect, RenderPath.Bitmap)] + [InlineData(SharedResources.Indirect, RenderPath.DeviceContext)] + public void Each_page_draws_only_its_own_field_when_the_pages_share_their_resources(SharedResources resources, RenderPath path) + { + byte[] pdf = SharedResourceFixtureFactory.Create(4, images: 1, withFields: true, resources); + + using IPdfDocument document = Load(pdf); + using Bitmap first = Render(document, path, pageIndex: 0); + for (int page = 0; page < 4; page++) + { + using Bitmap picture = Render(document, path, page); + AssertSharedResourcePage(picture, page); + } + + using Bitmap firstAgain = Render(document, path, pageIndex: 0); + AssertSamePixels(first, firstAgain); + } + + /// + /// Two pages that share one content array and one resource dictionary each print only their own field, also + /// when the first is drawn again after the second. Their copies, made in one go, share those objects too, and + /// flattening the first copy appends its fields to the shared array: without the comparison of the second + /// page, that page would print the first page's fields as well (with inherited resources, each copy has its + /// own dictionary, so the appended name finds nothing on the other page). + /// + [Theory] + [InlineData(SharedResources.Inherited, RenderPath.Bitmap)] + [InlineData(SharedResources.Inherited, RenderPath.DeviceContext)] + [InlineData(SharedResources.Indirect, RenderPath.Bitmap)] + [InlineData(SharedResources.Indirect, RenderPath.DeviceContext)] + public void Pages_that_share_their_content_array_each_print_only_their_own_field(SharedResources resources, RenderPath path) + { + byte[] pdf = SharedResourceFixtureFactory.Create(2, images: 1, withFields: true, resources, sharedContentArray: true); + + using IPdfDocument document = Load(pdf); + using Bitmap first = Render(document, path, pageIndex: 0); + AssertSharedResourcePage(first, 0); + using Bitmap second = Render(document, path, pageIndex: 1); + AssertSharedResourcePage(second, 1); + using Bitmap firstAgain = Render(document, path, pageIndex: 0); + AssertSharedResourcePage(firstAgain, 0); + AssertSamePixels(first, firstAgain); + } + + /// + /// KNOWN LIMITATION, pinned as it behaves today. This is a characterization test: it records documented + /// behaviour that a future fix is expected to change, so whoever fixes it must update this test AND the + /// limitation text in docs/usage.md, docs/troubleshooting.md, SECURITY.md, CHANGELOG.md and the design doc. + /// When four form pages share one indirect /Contents array and one indirect /Resources dictionary, the + /// copies share the cloned content array, and PDFium's flatten appends to that array in place. The pixel + /// comparison rejects the second page's copy (it shows the first page's field), but the fallback then flattens + /// the original page, whose content array is also shared, so the third page's original and copy differ as well + /// and it too goes in place and keeps the second page's drawing: later pages also print the fields of earlier + /// ones. The print still reports Ok and nothing throws. Nothing here depends on timing: the pages are drawn one + /// after the other and the ink is counted in fixed rectangles. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void Known_limitation_pages_sharing_one_content_array_also_print_the_fields_of_earlier_pages(RenderPath path) + { + const int Pages = 4; + byte[] pdf = SharedResourceFixtureFactory.Create(Pages, images: 1, withFields: true, SharedResources.Indirect, sharedContentArray: true); + float height = SharedResourceFixtureFactory.PageHeightPoints; + var prepared = new List<(int Page, PagePreparation How, CopyRejection Why)>(); + + using IPdfDocument document = Load(pdf); + ((PdfiumDocument)document).PagePrepared = (page, how, why) => prepared.Add((page, how, why)); + + // Drawn in page order, as a print job does. The fields are 80 x 50 points at four different places, so the + // ink in page q's field rectangle on page p says whether page q's field was drawn on page p. + for (int page = 0; page < Pages; page++) + { + using Bitmap picture = Render(document, path, page); + AssertInked(picture, SharedResourceFixtureFactory.FieldOn(page).ToInnerPixels(Dpi, height), $"page {page + 1}'s own field"); + for (int other = 0; other < Pages; other++) + { + if (other == page) + { + continue; + } + + Rectangle area = SharedResourceFixtureFactory.FieldOn(other).ToInnerPixels(Dpi, height); + int dark = Pixels.CountDarkIn(picture, area); + _output.WriteLine($"Page {page + 1}: {dark} dark pixels where page {other + 1}'s field lies ({area.Width * area.Height} in the rectangle)"); + + // Today: pages 1 and 2 are clean; page 3 also shows page 2's field; page 4 also shows pages 2 and 3. + bool leaks = page >= 2 && other >= 1 && other < page; + if (leaks) + { + Assert.True(dark >= area.Width * area.Height * FullyInked, $"Documented limitation: page {page + 1} should also show page {other + 1}'s field, but only {dark} pixels are dark. If this was fixed, update this test and the docs."); + } + else + { + Assert.True(dark == 0, $"Page {page + 1} has {dark} dark pixels where page {other + 1}'s field lies, which is not the documented behaviour."); + } + } + } + + // The page itself was never given up: every page was flattened, none was drawn without its fields. + Assert.Equal(Pages, prepared.Count); + Assert.DoesNotContain(prepared, entry => entry.How == PagePreparation.DrawnAsItIs); + + // And a whole print job over the same kind of PDF still ends with status Ok. + using IPdfDocument jobDocument = Load(pdf); + using var controller = new FakePrintController(); + PrintResult result = PrintJob.Run(jobDocument, [0, 1, 2, 3], TestPrinters.Settings(), "Shared content array", ScaleMode.FitToPage, CancellationToken.None, controller); + Assert.True(result.Succeeded, result.Message); + Assert.Equal(Pages, result.PagesPrinted); + } + + /// + /// A print job looks for form fields only among the pages it prints, and copies those pages (each once, in the + /// order of the job) in one go. + /// + [Fact] + public void A_print_job_copies_only_the_form_pages_it_prints() + { + byte[] pdf = SharedResourceFixtureFactory.Create(6, images: 1, withFields: true, SharedResources.Inherited); + var copies = new List<(int[] Pages, int InsertAt)>(); + var engine = new PdfiumEngine(flattenPage: null, RecordingCopier(copies)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + using (var controller = new FakePrintController()) + { + PrintResult result = PrintJob.Run(document!, [4, 1, 4], TestPrinters.Settings(), "Planned pages", ScaleMode.FitToPage, CancellationToken.None, controller); + Assert.True(result.Succeeded, result.Message); + Assert.Equal(3, result.PagesPrinted); + } + + (int[] pages, int insertAt) = Assert.Single(copies); + Assert.Equal([4, 1], pages); + Assert.Equal(6, insertAt); + } + + /// + /// A page drawn although it was not among the pages planned for drawing gets no copy of its own (the one copy + /// of the document has been made); its fields are flattened into the page itself, so they still print. + /// + [Theory] + [InlineData(RenderPath.Bitmap)] + [InlineData(RenderPath.DeviceContext)] + public void A_page_drawn_outside_the_planned_pages_still_prints_its_fields(RenderPath path) + { + byte[] pdf = SharedResourceFixtureFactory.Create(3, images: 1, withFields: true, SharedResources.Indirect); + var copies = new List<(int[] Pages, int InsertAt)>(); + var engine = new PdfiumEngine(flattenPage: null, RecordingCopier(copies)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + { + document!.PlanToDraw([0]); + using Bitmap planned = Render(document, path, pageIndex: 0); + AssertSharedResourcePage(planned, 0); + using Bitmap unplanned = Render(document, path, pageIndex: 2); + AssertSharedResourcePage(unplanned, 2); + } + + (int[] pages, _) = Assert.Single(copies); + Assert.Equal([0], pages); + } + + /// + /// A PDF larger than the copy budget gets no copy at all: the fields of every page are flattened into the page + /// itself, and they all print. A page that carries its resources itself loses nothing; a page that inherits + /// them from the page tree loses its image, which is the documented limitation of that fallback (asserted, so + /// that a change is noticed). No error is reported. + /// + [Theory] + [InlineData(SharedResources.Inherited, RenderPath.Bitmap)] + [InlineData(SharedResources.Inherited, RenderPath.DeviceContext)] + [InlineData(SharedResources.Indirect, RenderPath.Bitmap)] + [InlineData(SharedResources.Indirect, RenderPath.DeviceContext)] + public void A_pdf_over_the_copy_budget_has_its_fields_drawn_into_the_pages_themselves(SharedResources resources, RenderPath path) + { + byte[] pdf = SharedResourceFixtureFactory.Create(4, images: 1, withFields: true, resources); + var copies = new List<(int[] Pages, int InsertAt)>(); + var engine = new PdfiumEngine(flattenPage: null, RecordingCopier(copies)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + { + ((PdfiumDocument)document!).CopyBudgetBytes = pdf.Length - 1; + for (int page = 0; page < 4; page++) + { + using Bitmap picture = Render(document, path, page); + AssertSharedResourcePage(picture, page, imageDrawn: resources == SharedResources.Indirect); + } + } + + Assert.Empty(copies); + } + + /// A PDF exactly the size of the copy budget is still copied, and every page shows its image and field. + [Fact] + public void A_pdf_exactly_at_the_copy_budget_is_copied() + { + byte[] pdf = SharedResourceFixtureFactory.Create(4, images: 1, withFields: true, SharedResources.Inherited); + var copies = new List<(int[] Pages, int InsertAt)>(); + var engine = new PdfiumEngine(flattenPage: null, RecordingCopier(copies)); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + { + ((PdfiumDocument)document!).CopyBudgetBytes = pdf.Length; + for (int page = 0; page < 4; page++) + { + using Bitmap picture = Render(document, RenderPath.Bitmap, page); + AssertSharedResourcePage(picture, page); + } + } + + Assert.Single(copies); + } + + /// The copy budget is 64 MB, the number the documentation states. + [Fact] + public void The_copy_budget_is_64_MB() + { + Assert.Equal(64L * 1024 * 1024, PdfiumDocument.DefaultCopyBudgetBytes); + using IPdfDocument document = Load(FormFixtureFactory.Create()); + Assert.Equal(PdfiumDocument.DefaultCopyBudgetBytes, ((PdfiumDocument)document).CopyBudgetBytes); + } + + /// The key cases of form-page preparation, each with how its page must be prepared and why. + public static TheoryData PreparationCases() + { + var data = new TheoryData(); + foreach (string name in new[] + { + "plain form page", "inherited resources", "page without fields", "damaged annotation reference", "hidden layer", + "copy function missing", "copy refused", "copy of another size", "copy cannot be flattened", + "nothing can be flattened", "over the copy budget", + }) + { + data.Add(name, RenderPath.Bitmap); + data.Add(name, RenderPath.DeviceContext); + } + + return data; + } + + /// + /// Every key case reports, through the document's preparation hook, which branch its page took and why: the + /// copy for an ordinary form page and for one that inherits its resources; the page itself (in place) when the + /// copy is missing, refused, lost annotations, draws differently, has another size or cannot be flattened, or + /// when the PDF is over the copy budget; drawn as it is only when nothing can be flattened. A PDFium update + /// that made every copy fail would show here directly, not only as a loss of ink on some pages. + /// + [Theory] + [MemberData(nameof(PreparationCases))] + public void Each_key_case_reports_how_its_page_was_prepared(string name, RenderPath path) + { + (byte[] pdf, PdfiumEngine engine, PagePreparation expectedHow, CopyRejection expectedWhy, long? budget) = name switch + { + "plain form page" => (FormFixtureFactory.Create(), new PdfiumEngine(), PagePreparation.Copy, CopyRejection.None, (long?)null), + "inherited resources" => (FormFixtureFactory.Create(Variant("inherited resources")), new PdfiumEngine(), PagePreparation.Copy, CopyRejection.None, null), + "page without fields" => (FormFixtureFactory.Create(new FormFixtureOptions { WithFields = false, WithPageContent = true }), new PdfiumEngine(), PagePreparation.NoFormFields, CopyRejection.None, null), + "damaged annotation reference" => (FormFixtureFactory.Create(new FormFixtureOptions { WithPageContent = true, WithDanglingAnnotationReference = true }), new PdfiumEngine(), PagePreparation.InPlace, CopyRejection.AnnotationsLost, null), + "hidden layer" => (FormFixtureFactory.Create(Variant("hidden layer")), new PdfiumEngine(), PagePreparation.InPlace, CopyRejection.LooksDifferent, null), + "copy function missing" => (FormFixtureFactory.Create(Variant("page resources")), new PdfiumEngine(flattenPage: null, FailingCopier("throws")), PagePreparation.InPlace, CopyRejection.CopyFailed, null), + "copy refused" => (FormFixtureFactory.Create(Variant("page resources")), new PdfiumEngine(flattenPage: null, FailingCopier("reports failure")), PagePreparation.InPlace, CopyRejection.CopyFailed, null), + "copy of another size" => (FormFixtureFactory.Create(Variant("page resources")), new PdfiumEngine(flattenPage: null, NarrowingCopier()), PagePreparation.InPlace, CopyRejection.SizeDiffers, null), + "copy cannot be flattened" => (FormFixtureFactory.Create(Variant("page resources")), new PdfiumEngine(FailingFirstFlattener()), PagePreparation.InPlace, CopyRejection.FlattenFailed, null), + "nothing can be flattened" => (FormFixtureFactory.Create(Variant("page resources")), new PdfiumEngine(FailingFlattener("reports failure")), PagePreparation.DrawnAsItIs, CopyRejection.FlattenFailed, null), + "over the copy budget" => (FormFixtureFactory.Create(Variant("inherited resources")), new PdfiumEngine(), PagePreparation.InPlace, CopyRejection.OverBudget, 1L), + _ => throw new ArgumentOutOfRangeException(nameof(name), name, "Unknown case."), + }; + + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + var prepared = new List<(int Page, PagePreparation How, CopyRejection Why)>(); + using (document) + { + var pdfium = (PdfiumDocument)document!; + if (budget is long bytes) + { + pdfium.CopyBudgetBytes = bytes; + } + + pdfium.PagePrepared = (page, how, why) => prepared.Add((page, how, why)); + Render(document!, path).Dispose(); + Render(document!, path).Dispose(); + } + + _output.WriteLine($"{name}, {path}: {string.Join(", ", prepared)}"); + Assert.Equal([(0, expectedHow, expectedWhy)], prepared); + } + + /// + /// Many pages sharing one resource dictionary: under the copy budget every page prints from its copy; over + /// it, every page has its fields flattened into itself and says that the budget was the reason. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Every_page_of_a_document_reports_the_copy_budget_decision(bool overBudget) + { + const int Pages = 6; + byte[] pdf = SharedResourceFixtureFactory.Create(Pages, images: 1, withFields: true, SharedResources.Inherited); + var prepared = new List<(int Page, PagePreparation How, CopyRejection Why)>(); + using (IPdfDocument document = Load(pdf)) + { + var pdfium = (PdfiumDocument)document; + pdfium.CopyBudgetBytes = overBudget ? pdf.Length - 1 : pdf.Length; + pdfium.PagePrepared = (page, how, why) => prepared.Add((page, how, why)); + for (int page = 0; page < Pages; page++) + { + using Bitmap picture = Render(document, RenderPath.Bitmap, page); + AssertSharedResourcePage(picture, page, imageDrawn: !overBudget); + } + } + + (PagePreparation how, CopyRejection why) expected = overBudget ? (PagePreparation.InPlace, CopyRejection.OverBudget) : (PagePreparation.Copy, CopyRejection.None); + Assert.Equal(Enumerable.Range(0, Pages).Select(page => (page, expected.how, expected.why)), prepared); + } + + /// + /// The pages that share one content array: with inherited resources both print from their copies; with one + /// shared resource dictionary the second page's copy shows the first page's fields, so the comparison sends it + /// to the fallback, and that is what it reports. + /// + [Theory] + [InlineData(SharedResources.Inherited)] + [InlineData(SharedResources.Indirect)] + public void Pages_that_share_their_content_array_report_how_they_were_prepared(SharedResources resources) + { + byte[] pdf = SharedResourceFixtureFactory.Create(2, images: 1, withFields: true, resources, sharedContentArray: true); + var prepared = new List<(int Page, PagePreparation How, CopyRejection Why)>(); + using (IPdfDocument document = Load(pdf)) + { + ((PdfiumDocument)document).PagePrepared = (page, how, why) => prepared.Add((page, how, why)); + Render(document, RenderPath.Bitmap, pageIndex: 0).Dispose(); + Render(document, RenderPath.Bitmap, pageIndex: 1).Dispose(); + } + + (PagePreparation, CopyRejection) second = resources == SharedResources.Indirect ? (PagePreparation.InPlace, CopyRejection.LooksDifferent) : (PagePreparation.Copy, CopyRejection.None); + Assert.Equal([(0, PagePreparation.Copy, CopyRejection.None), (1, second.Item1, second.Item2)], prepared); + } + + /// A page drawn outside the planned pages reports that it was not planned. + [Fact] + public void A_page_drawn_outside_the_planned_pages_reports_it() + { + byte[] pdf = SharedResourceFixtureFactory.Create(3, images: 1, withFields: true, SharedResources.Indirect); + var prepared = new List<(int Page, PagePreparation How, CopyRejection Why)>(); + using (IPdfDocument document = Load(pdf)) + { + ((PdfiumDocument)document).PagePrepared = (page, how, why) => prepared.Add((page, how, why)); + document.PlanToDraw([0]); + Render(document, RenderPath.Bitmap, pageIndex: 0).Dispose(); + Render(document, RenderPath.Bitmap, pageIndex: 2).Dispose(); + } + + Assert.Equal([(0, PagePreparation.Copy, CopyRejection.None), (2, PagePreparation.InPlace, CopyRejection.NotPlanned)], prepared); + } + + /// A real copy of the requested pages, each then made 100 points narrower, as a misbehaving copy might be. + private static PageCopier NarrowingCopier() => (document, pageIndices, insertAt) => + { + bool copied = PdfiumNative.FPDF_ImportPagesByIndex(document, document, pageIndices, (uint)pageIndices.Length, insertAt) != 0; + for (int k = 0; copied && k < pageIndices.Length; k++) + { + IntPtr copy = PdfiumNative.FPDF_LoadPage(document, insertAt + k); + Assert.NotEqual(IntPtr.Zero, copy); + PdfiumNative.FPDFPage_SetMediaBox(copy, 0, 0, FormFixtureFactory.PageWidthPoints - 100, FormFixtureFactory.PageHeightPoints); + PdfiumNative.FPDF_ClosePage(copy); + } + + return copied; + }; + + /// PDFium's own flattener, except that the first call (the one on the copy) reports failure. + private static PageFlattener FailingFirstFlattener() + { + int calls = 0; + return (page, usage) => Interlocked.Increment(ref calls) == 1 ? 0 : PdfiumNative.FPDFPage_Flatten(page, usage); + } + + /// PDFium's page copy, recording each call (the pages and where their copies go) in . + private static PageCopier RecordingCopier(List<(int[] Pages, int InsertAt)> calls) => (document, pageIndices, insertAt) => + { + lock (calls) + { + calls.Add(([.. pageIndices], insertAt)); + } + + return PdfiumNative.FPDF_ImportPagesByIndex(document, document, pageIndices, (uint)pageIndices.Length, insertAt) != 0; + }; + + /// + /// Fails unless a page of a PDF shows its own field, none of the + /// other pages' fields, and its image (or, when is , does + /// not show the image: the documented loss of a page that inherits its resources and has its fields flattened + /// into itself). + /// + private void AssertSharedResourcePage(Bitmap picture, int page, bool imageDrawn = true) + { + float height = SharedResourceFixtureFactory.PageHeightPoints; + AssertInked(picture, SharedResourceFixtureFactory.FieldOn(page).ToInnerPixels(Dpi, height), $"page {page + 1}'s own field"); + for (int other = 1; other < 4; other++) + { + int dark = Pixels.CountDarkIn(picture, SharedResourceFixtureFactory.FieldOn(page + other).ToInnerPixels(Dpi, height)); + Assert.True(dark == 0, $"Page {page + 1} has {dark} dark pixels where another page's field lies: that page's field was drawn on it."); + } + + Rectangle image = SharedResourceFixtureFactory.ImageMark.ToInnerPixels(Dpi, height); + if (imageDrawn) + { + AssertInked(picture, image, $"page {page + 1}'s image, drawn through the shared resources"); + } + else + { + int dark = Pixels.CountDarkIn(picture, image); + _output.WriteLine($"Page {page + 1}: {dark} dark pixels where the image drawn through inherited resources lies (documented limitation: expected missing)"); + Assert.True(dark <= image.Width * image.Height * 0.05, $"Expected page {page + 1}'s image to be missing (documented limitation), found {dark} dark pixels."); + } + } + + /// A flattener that fails the way names, without touching the page. + private static PageFlattener FailingFlattener(string failure) => failure switch + { + "reports failure" => (_, _) => 0, + "throws" => (_, _) => throw new EntryPointNotFoundException("Unable to find an entry point named 'FPDFPage_Flatten' in DLL 'pdfium'."), + _ => throw new ArgumentOutOfRangeException(nameof(failure), failure, "Unknown failure."), + }; + + /// PDFium's own flattener, which also calls every time it is used. + private static PageFlattener CountingFlattener(Action counted) => (page, usage) => + { + counted(); + return PdfiumNative.FPDFPage_Flatten(page, usage); + }; + + /// A page copier that fails the way names, without copying anything. + private static PageCopier FailingCopier(string failure) => failure switch + { + "reports failure" => (_, _, _) => false, + "throws" => (_, _, _) => throw new EntryPointNotFoundException("Unable to find an entry point named 'FPDF_ImportPagesByIndex' in DLL 'pdfium'."), + _ => throw new ArgumentOutOfRangeException(nameof(failure), failure, "Unknown failure."), + }; + + /// The fixture options behind each named layout variant. + private static FormFixtureOptions Variant(string name) => name switch + { + "content and markup" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true }, + "inherited page attributes" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, InheritPageAttributes = true }, + "page resources" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, WithResourceMarks = true }, + "inherited resources" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, WithResourceMarks = true, InheritPageAttributes = true }, + "hidden layer" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, WithResourceMarks = true, WithHiddenLayer = true }, + "crop box" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, WithCropBox = true }, + "rotate 90" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, Rotate = 90 }, + "everything at once" => new FormFixtureOptions { WithPageContent = true, WithMarkupAnnotations = true, WithResourceMarks = true, InheritPageAttributes = true, WithCropBox = true, Rotate = 90 }, + _ => throw new ArgumentOutOfRangeException(nameof(name), name, "Unknown variant."), + }; + + /// Opens a PDF with the real engine and fails the test if it does not open. + private IPdfDocument Load(byte[] pdf) + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(pdf, null, out IPdfDocument? document)); + return document!; + } + + /// + /// Renders a page (page 1 by default) at through the chosen path: as a bitmap, or onto the + /// device context of a white bitmap of the page's size (24 bits per pixel, see ). + /// + private static Bitmap Render(IPdfDocument document, RenderPath path, int pageIndex = 0) + { + if (path == RenderPath.Bitmap) + { + return document.RenderToBitmap(pageIndex, Dpi, quarterTurns: 0); + } + + SizeF size = document.GetPageSizePoints(pageIndex); + var target = new Bitmap((int)Math.Round(size.Width), (int)Math.Round(size.Height), PixelFormat.Format24bppRgb); + using Graphics graphics = Graphics.FromImage(target); + graphics.Clear(Color.White); + IntPtr hdc = graphics.GetHdc(); + try + { + document.RenderToDeviceContext(pageIndex, hdc, new Rectangle(0, 0, target.Width, target.Height), forPrinting: true, quarterTurns: 0); + } + finally + { + graphics.ReleaseHdc(hdc); + } + + return target; + } + + /// Fails unless a comparison picture of this size is within the budget the engine promises. + private static void AssertWithinComparisonBudget(int width, int height) + { + Assert.InRange(width, 1, PdfiumDocument.ComparisonMaxSide); + Assert.InRange(height, 1, PdfiumDocument.ComparisonMaxSide); + Assert.True((long)width * height <= PdfiumDocument.ComparisonMaxPixels, $"A {width} x {height} comparison picture is over the pixel budget."); + } + + /// The area, in pixels at , of the two printable fields (the text field and the checkbox). + private static int FieldArea => (int)((FormFixtureFactory.TextField.Width * FormFixtureFactory.TextField.Height) + (FormFixtureFactory.CheckBox.Width * FormFixtureFactory.CheckBox.Height)); + + /// + /// Fails unless the new ink is about the area of the fields: at least 90% of it (the fields are drawn) and at + /// most 1% more (nothing else is drawn that plain PDFium does not draw, such as a layer the PDF switches off; + /// the margin covers anti-aliased field edges). + /// + private static void AssertFieldsAddTheirAreaAndNothingElse(int gained, int fieldArea) + { + Assert.True(gained >= fieldArea * 0.9, $"Expected the fields to add about {fieldArea} dark pixels, found {gained}."); + Assert.True(gained <= fieldArea * 1.01, $"Expected the fields to add about {fieldArea} dark pixels and nothing else, found {gained}: something not drawn by PDFium alone was added."); + } + + /// The reference picture of a page: plain PDFium on the same path, at the same pixel size. + private static Bitmap Reference(byte[] pdf, RenderPath path, Size size, int pageIndex = 0) => path == RenderPath.Bitmap + ? RawPdfium.RenderBitmap(pdf, size.Width, size.Height, pageIndex) + : RawPdfium.RenderOnDeviceContext(pdf, size.Width, size.Height, pageIndex); + + /// + /// Compares the ink of two pictures of the same size pixel by pixel: how many pixels dark in + /// are not dark in (lost), and the other way round (gained). + /// + private static (int Lost, int Gained) CompareInk(Bitmap reference, Bitmap ours) + { + Assert.Equal(reference.Size, ours.Size); + bool[] ourInk = Pixels.DarkMask(ours); + bool[] referenceInk = Pixels.DarkMask(reference); + int lost = 0; + int gained = 0; + for (int i = 0; i < ourInk.Length; i++) + { + lost += referenceInk[i] && !ourInk[i] ? 1 : 0; + gained += ourInk[i] && !referenceInk[i] ? 1 : 0; + } + + return (lost, gained); + } + + /// The three resource marks and the two printable fields of an unrotated, uncropped fixture page. + /// How the page gets its resources ("own" or "inherited"), for the failure messages. + private static (PdfRect Area, string What)[] ResourceMarksAndFields(string resources) => + [ + (FormFixtureFactory.ResourceXObject, $"the form XObject drawn through the page's {resources} resources"), + (FormFixtureFactory.ResourceImage, $"the image drawn through the page's {resources} resources"), + (FormFixtureFactory.ResourceFontGlyph, $"the Type3 glyph drawn through the page's {resources} resources"), + (FormFixtureFactory.TextField, "the filled text field"), + (FormFixtureFactory.CheckBox, "the ticked checkbox"), + ]; + + /// + /// Fails unless (nearly) the whole inner area of every rectangle is dark; the failure lists every rectangle + /// that is not, so one run shows everything that is missing. + /// + private void AssertAllInked(Bitmap page, (PdfRect Area, string What)[] marks) + { + var missing = new List(); + foreach ((PdfRect area, string what) in marks) + { + Rectangle inner = area.ToInnerPixels(Dpi); + int dark = Pixels.CountDarkIn(page, inner); + int total = inner.Width * inner.Height; + _output.WriteLine($"Dark pixels in {what}: {dark} of {total}"); + if (dark < total * FullyInked) + { + missing.Add($"{what}: only {dark} of its {total} pixels are dark"); + } + } + + Assert.True(missing.Count == 0, "Expected these to be drawn: " + string.Join("; ", missing) + "."); + } + + /// + /// Fails unless a fixture page whose fields were flattened into the page itself (the fallback when its copy + /// cannot be used) shows both printable fields and its own content. With its own resources, nothing PDFium + /// draws is lost. With resources taken from the page tree, the form XObject and the image drawn through them + /// are missing: that is the documented limitation of the fallback, asserted here so that a change in it is + /// noticed (if it is ever solved, this branch of the check must change with the docs). + /// + private void AssertFieldsDrawnIntoThePageItself(Bitmap ours, Bitmap reference, bool inherited, RenderPath path) + { + AssertInked(ours, FormFixtureFactory.TextField, "the filled text field"); + AssertInked(ours, FormFixtureFactory.CheckBox, "the ticked checkbox"); + AssertInked(ours, FormFixtureFactory.PageMark, "the page's own black square"); + (int lost, int gained) = CompareInk(reference, ours); + _output.WriteLine($"{path}, {(inherited ? "inherited" : "own")} resources: lost {lost}, gained {gained}"); + if (inherited) + { + AssertNotInked(ours, FormFixtureFactory.ResourceXObject, "the form XObject drawn through the inherited resources (documented limitation)"); + AssertNotInked(ours, FormFixtureFactory.ResourceImage, "the image drawn through the inherited resources (documented limitation)"); + } + else + { + Assert.Equal(0, lost); + AssertFieldsAddTheirAreaAndNothingElse(gained, FieldArea); + } + } + + /// Fails unless (nearly) none of the inner area of is dark. + private void AssertNotInked(Bitmap page, PdfRect area, string what) + { + Rectangle inner = area.ToInnerPixels(Dpi); + int dark = Pixels.CountDarkIn(page, inner); + int total = inner.Width * inner.Height; + _output.WriteLine($"Dark pixels in {what}: {dark} of {total}"); + Assert.True(dark <= total * 0.05, $"Expected {what} to be missing: {dark} of its {total} pixels are dark."); + } + + /// Fails unless (nearly) the whole inner area of is dark. + private void AssertInked(Bitmap page, PdfRect field, string what) => AssertInked(page, field.ToInnerPixels(Dpi), what); + + /// Fails unless (nearly) the whole of , in pixels, is dark. + private void AssertInked(Bitmap page, Rectangle area, string what) + { + int dark = Pixels.CountDarkIn(page, area); + int total = area.Width * area.Height; + _output.WriteLine($"Dark pixels in {what}: {dark} of {total}"); + Assert.True(dark >= total * FullyInked, $"Expected {what} to be drawn: only {dark} of its {total} pixels are dark."); + } + + /// Fails unless the two bitmaps have the same size and the same colour in every pixel. + private static void AssertSamePixels(Bitmap expected, Bitmap actual) + { + Assert.Equal(expected.Size, actual.Size); + int[] want = ReadPixels(expected); + int[] got = ReadPixels(actual); + int differences = 0; + int first = -1; + for (int i = 0; i < want.Length; i++) + { + if (want[i] != got[i]) + { + differences++; + first = first < 0 ? i : first; + } + } + + Assert.True(differences == 0, $"{differences} pixels differ; the first at x {first % expected.Width}, y {first / expected.Width}."); + } + + /// Reads every pixel as a 32-bit ARGB value with opaque alpha, so a 24-bit and a 32-bit bitmap compare alike. + private static int[] ReadPixels(Bitmap bitmap) + { + var pixels = new int[bitmap.Width * bitmap.Height]; + BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + try + { + for (int y = 0; y < bitmap.Height; y++) + { + Marshal.Copy(data.Scan0 + (y * data.Stride), pixels, y * bitmap.Width, bitmap.Width); + } + } + finally + { + bitmap.UnlockBits(data); + } + + for (int i = 0; i < pixels.Length; i++) + { + pixels[i] |= unchecked((int)0xFF000000); + } + + return pixels; + } +} diff --git a/tests/PDFStream.NET.Tests/Engine/FormMemoryTests.cs b/tests/PDFStream.NET.Tests/Engine/FormMemoryTests.cs new file mode 100644 index 0000000..322cd99 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Engine/FormMemoryTests.cs @@ -0,0 +1,166 @@ +using System.Diagnostics; +using System.Drawing; +using System.Runtime.InteropServices; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Fixtures; +using PDFStream.NET.Tests.Printing; +using Xunit; + +namespace PDFStream.NET.Tests.Engine; + +/// +/// The collection of tests that measure the memory of the whole test process. It runs on its own, after the +/// tests that may run in parallel, so other tests' allocations do not blur the numbers. +/// +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class MemoryMeasurementCollection +{ + /// The collection's name. + public const string Name = "Memory measurements, run alone"; +} + +/// +/// Printing many form pages that share one big resource dictionary must cost about one copy of what they share, +/// not one copy per form page. Copying form pages one by one (each with its own PDFium import) cloned every +/// image of a shared dictionary again for every page: drawing 40 such pages sharing 8 MB of images took about +/// 290 MB more than without the copies. Printing 500 of them in a 32-bit process did not finish: the test +/// process ended with exit code 0x4000001F and no test result (most likely PDFium running out of address +/// space), and in another run the print failed part way with a misleading "page could not be drawn" message. +/// +/// +/// The numbers are the private memory of the test process (managed and native), read after a full garbage +/// collection. They are logged for every run, so the cost can be compared over time; the assertions only use a +/// generous ceiling that the multiplied cost exceeds several times over. +/// +[Collection(MemoryMeasurementCollection.Name)] +public sealed class FormMemoryTests +{ + /// How many one-megabyte images the pages share. + private const int SharedImages = 8; + + /// 72 dpi makes one pixel one point. + private const int Dpi = 72; + + /// + /// The most the private memory may grow, in megabytes, while 40 pages sharing 8 MB of images are drawn. Drawing + /// them without any copy grew it by about 6 to 8 MB; one copy of the shared images adds about 8 MB more. + /// Copying page by page grew it by about 300 MB, far over this ceiling. + /// + private const long GrowthCeilingMegabytes = 64; + + private readonly ITestOutputHelper _output; + + /// Creates the test class with xUnit's per-test output sink. + public FormMemoryTests(ITestOutputHelper output) + { + _output = output; + _output.WriteLine($"Process architecture: {RuntimeInformation.ProcessArchitecture}, runtime: {RuntimeInformation.FrameworkDescription}"); + } + + /// + /// Drawing 40 pages that share 8 MB of images, inherited from the page tree or named by every page as one + /// indirect dictionary, with a form field on every page (and, for comparison, without any field): every page + /// shows its field (if it has one) and its image, and the private memory grows by no more than the ceiling. + /// + [Theory] + [InlineData(SharedResources.Inherited, true)] + [InlineData(SharedResources.Indirect, true)] + [InlineData(SharedResources.Inherited, false)] + public void Forty_pages_that_share_8_MB_of_images_cost_about_one_copy_of_them(SharedResources resources, bool withFields) + { + const int Pages = 40; + byte[] pdf = SharedResourceFixtureFactory.Create(Pages, SharedImages, withFields, resources); + var engine = new PdfiumEngine(); + + long before = PrivateMegabytes(); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + long loaded; + long drawn; + var missing = new List(); + var stopwatch = Stopwatch.StartNew(); + using (document) + { + loaded = PrivateMegabytes(); + for (int page = 0; page < Pages; page++) + { + using Bitmap picture = document!.RenderToBitmap(page, Dpi, quarterTurns: 0); + if (!FullyDark(picture, SharedResourceFixtureFactory.ImageMark)) + { + missing.Add($"page {page + 1}: image"); + } + + if (withFields && !FullyDark(picture, SharedResourceFixtureFactory.FieldOn(page))) + { + missing.Add($"page {page + 1}: field"); + } + } + + stopwatch.Stop(); + drawn = PrivateMegabytes(); + } + + long closed = PrivateMegabytes(); + _output.WriteLine($"{Pages} pages, {resources} resources, fields {withFields}, PDF {pdf.Length / (1024 * 1024)} MB: private memory {before} MB before loading, {loaded} MB loaded, {drawn} MB after drawing every page (+{drawn - loaded} MB), {closed} MB after closing; drawing took {stopwatch.ElapsedMilliseconds} ms"); + Assert.True(missing.Count == 0, "Not drawn: " + string.Join(", ", missing)); + Assert.True(drawn - loaded <= GrowthCeilingMegabytes, $"Drawing the pages grew the private memory by {drawn - loaded} MB, more than the {GrowthCeilingMegabytes} MB ceiling."); + } + + /// + /// A print job of 500 form pages that share 8 MB of images inherited from the page tree prints every page. + /// It matters most in a 32-bit process (run the tests with --arch x86), where copying page by page made the + /// print fail part way or end the process (see the class summary); it runs, and must pass, in a 64-bit + /// process too. + /// + [Fact] + public void Five_hundred_form_pages_that_share_8_MB_of_images_print_in_one_job() + { + const int Pages = 500; + byte[] pdf = SharedResourceFixtureFactory.Create(Pages, SharedImages, withFields: true, SharedResources.Inherited); + var engine = new PdfiumEngine(); + + long before = PrivateMegabytes(); + Assert.Equal(PdfLoadStatus.Ok, engine.TryLoad(pdf, null, out IPdfDocument? document)); + PrintResult result; + int sheets; + long printed; + var prepared = new List<(int Page, PagePreparation How, CopyRejection Why)>(); + var stopwatch = Stopwatch.StartNew(); + using (document) + { + ((PdfiumDocument)document!).PagePrepared = (page, how, why) => prepared.Add((page, how, why)); + // Small sheets at a low resolution: what is measured is the preparation of the pages, not the sheets. + using var controller = new FakePrintController(sheetWidth: 100, sheetHeight: 100, dpi: 10); + result = PrintJob.Run(document!, Enumerable.Range(0, Pages).ToArray(), TestPrinters.Settings(), "Shared resources", ScaleMode.FitToPage, CancellationToken.None, controller); + sheets = controller.Pages.Count; + stopwatch.Stop(); + printed = PrivateMegabytes(); + } + + _output.WriteLine($"{Pages} form pages, PDF {pdf.Length / (1024 * 1024)} MB: {result.Status}, {result.PagesPrinted} pages, {sheets} sheets in {stopwatch.ElapsedMilliseconds} ms; private memory {before} MB before, {printed} MB after printing (+{printed - before} MB). {result.Message}"); + Assert.True(result.Succeeded, result.Message); + Assert.Equal(Pages, result.PagesPrinted); + Assert.Equal(Pages, sheets); + + // Ok alone would also be the result of flattening every page into itself, which loses the inherited images: + // every page must have printed from its copy. + Assert.Equal(Enumerable.Range(0, Pages).Select(page => (page, PagePreparation.Copy, CopyRejection.None)), prepared); + } + + /// Whether (nearly) the whole inner area of a rectangle of a fixture page is dark. + private static bool FullyDark(Bitmap picture, PdfRect area) + { + Rectangle inner = area.ToInnerPixels(Dpi, SharedResourceFixtureFactory.PageHeightPoints); + return Pixels.CountDarkIn(picture, inner) >= inner.Width * inner.Height * 0.95; + } + + /// The private memory of this process in megabytes, after a full garbage collection. + private static long PrivateMegabytes() + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + using Process process = Process.GetCurrentProcess(); + return process.PrivateMemorySize64 / (1024 * 1024); + } +} diff --git a/tests/PDFStream.NET.Tests/Engine/PdfiumEngineTests.cs b/tests/PDFStream.NET.Tests/Engine/PdfiumEngineTests.cs new file mode 100644 index 0000000..98065da --- /dev/null +++ b/tests/PDFStream.NET.Tests/Engine/PdfiumEngineTests.cs @@ -0,0 +1,457 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using System.Text; +using PDFStream.NET.Engine; +using PDFStream.NET.Tests.Fixtures; +using Xunit; + +namespace PDFStream.NET.Tests.Engine; + +/// +/// Tests against the real PDFium binary: loading, the three password +/// outcomes, rendering to a bitmap and to a device context, and two threads at once. +/// +public sealed class PdfiumEngineTests +{ + private const string UserPassword = "open-sesame"; + private const string OwnerPassword = "owner-secret"; + + private readonly PdfiumEngine _engine = new(); + private readonly ITestOutputHelper _output; + + /// Creates the test class with xUnit's per-test output sink. + public PdfiumEngineTests(ITestOutputHelper output) + { + _output = output; + + // Recorded in every test's output so a run on the x86 test host can be told apart + // from an x64 run by evidence rather than by assumption. + _output.WriteLine($"Process architecture: {RuntimeInformation.ProcessArchitecture}, runtime: {RuntimeInformation.FrameworkDescription}"); + } + + /// A valid three-page PDF loads and reports three pages. + [Fact] + public void Loads_valid_pdf_and_reports_page_count() + { + byte[] pdf = FixtureFactory.CreatePdf(3); + + PdfLoadStatus status = _engine.TryLoad(pdf, null, out IPdfDocument? document); + + using (document) + { + Assert.Equal(PdfLoadStatus.Ok, status); + Assert.NotNull(document); + Assert.Equal(3, document.PageCount); + } + } + + /// Bytes that are not a PDF are reported as invalid, with no document. + [Fact] + public void Garbage_bytes_return_Invalid() + { + byte[] garbage = Encoding.ASCII.GetBytes("This is plain text pretending to be a PDF file."); + + PdfLoadStatus status = _engine.TryLoad(garbage, null, out IPdfDocument? document); + + Assert.Equal(PdfLoadStatus.Invalid, status); + Assert.Null(document); + } + + /// An empty array is rejected before PDFium is called. + [Fact] + public void Empty_bytes_return_Invalid() + { + PdfLoadStatus status = _engine.TryLoad([], null, out IPdfDocument? document); + + Assert.Equal(PdfLoadStatus.Invalid, status); + Assert.Null(document); + } + + /// A PDF that needs a password, opened without one, asks for it. + [Fact] + public void User_password_pdf_without_password_returns_PasswordRequired() + { + byte[] pdf = FixtureFactory.CreatePdf(1, UserPassword, OwnerPassword); + + PdfLoadStatus withNull = _engine.TryLoad(pdf, null, out IPdfDocument? first); + + // The first real user passes an empty string, not null, when it has no password, + // so both must mean "no password given". + PdfLoadStatus withEmpty = _engine.TryLoad(pdf, string.Empty, out IPdfDocument? second); + + Assert.Equal(PdfLoadStatus.PasswordRequired, withNull); + Assert.Null(first); + Assert.Equal(PdfLoadStatus.PasswordRequired, withEmpty); + Assert.Null(second); + } + + /// A PDF that needs a password, opened with the wrong one, says the password is wrong. + [Fact] + public void User_password_pdf_with_wrong_password_returns_PasswordInvalid() + { + byte[] pdf = FixtureFactory.CreatePdf(1, UserPassword, OwnerPassword); + + PdfLoadStatus status = _engine.TryLoad(pdf, "not-the-password", out IPdfDocument? document); + + Assert.Equal(PdfLoadStatus.PasswordInvalid, status); + Assert.Null(document); + } + + /// A PDF that needs a password opens with the right one. + [Fact] + public void User_password_pdf_with_right_password_loads() + { + byte[] pdf = FixtureFactory.CreatePdf(2, UserPassword, OwnerPassword); + + PdfLoadStatus status = _engine.TryLoad(pdf, UserPassword, out IPdfDocument? document); + + using (document) + { + Assert.Equal(PdfLoadStatus.Ok, status); + Assert.NotNull(document); + Assert.Equal(2, document.PageCount); + } + } + + /// + /// A PDF protected only by an owner password (restrictions, no open password) opens without + /// any password, as every PDF reader does. + /// + [Fact] + public void Owner_only_password_pdf_loads_without_password() + { + byte[] pdf = FixtureFactory.CreatePdf(2, userPassword: null, ownerPassword: OwnerPassword); + + PdfLoadStatus status = _engine.TryLoad(pdf, null, out IPdfDocument? document); + + using (document) + { + Assert.Equal(PdfLoadStatus.Ok, status); + Assert.NotNull(document); + Assert.Equal(2, document.PageCount); + } + } + + /// + /// A PDF with only an owner password opens without a password, so an unrelated password the + /// caller happens to supply must not turn that into a "wrong password" failure. + /// + [Fact] + public void Owner_only_password_pdf_loads_with_an_unrelated_password() + { + byte[] pdf = FixtureFactory.CreatePdf(2, userPassword: null, ownerPassword: OwnerPassword); + + PdfLoadStatus status = _engine.TryLoad(pdf, "not-the-owner-password", out IPdfDocument? document); + + using (document) + { + Assert.Equal(PdfLoadStatus.Ok, status); + Assert.NotNull(document); + Assert.Equal(2, document.PageCount); + } + } + + /// Disposing a document twice is harmless. + [Fact] + public void Disposing_a_document_twice_is_safe() + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1), null, out IPdfDocument? document)); + + document!.Dispose(); + document.Dispose(); + } + + /// A document that has been disposed refuses further use with ObjectDisposedException. + [Fact] + public void Using_a_document_after_dispose_throws_ObjectDisposedException() + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1), null, out IPdfDocument? document)); + document!.Dispose(); + + Assert.Throws(() => document.GetPageSizePoints(0)); + Assert.Throws(() => document.RenderToBitmap(0, 72, 0)); + } + + /// A page index outside the document is rejected for both page-level calls. + [Theory] + [InlineData(-1)] + [InlineData(2)] + [InlineData(int.MaxValue)] + public void Out_of_range_page_index_throws_ArgumentOutOfRangeException(int pageIndex) + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(2), null, out IPdfDocument? document)); + + using (document) + { + Assert.Throws(() => document!.GetPageSizePoints(pageIndex)); + Assert.Throws(() => document!.RenderToBitmap(pageIndex, 72, 0)); + } + } + + /// Page sizes come back in points, page by page, as each page is displayed. + [Fact] + public void Page_sizes_are_reported_in_points_for_each_page() + { + byte[] pdf = FixtureFactory.CreatePdf(2, mixedSizes: true); + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + { + SizeF a4Portrait = document!.GetPageSizePoints(0); + SizeF letterLandscape = document.GetPageSizePoints(1); + + // A4 is 210 x 297 mm, which is 595.28 x 841.89 points. + Assert.Equal(595.28f, a4Portrait.Width, 0.5f); + Assert.Equal(841.89f, a4Portrait.Height, 0.5f); + Assert.Equal((float)FixtureFactory.LetterHeightPoints, letterLandscape.Width, 0.5f); + Assert.Equal((float)FixtureFactory.LetterWidthPoints, letterLandscape.Height, 0.5f); + } + } + + /// A page with text renders to a bitmap that has ink on a white background. + [Fact] + public void RenderToBitmap_of_page_with_text_has_non_white_pixels() + { + byte[] pdf = FixtureFactory.CreatePdf(1); + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(pdf, null, out IPdfDocument? document)); + + using (document) + using (Bitmap bitmap = document!.RenderToBitmap(0, 72, 0)) + { + // At 72 dpi one pixel is one point, so an A4 page is about 595 x 842 pixels. + Assert.InRange(bitmap.Width, 594, 596); + Assert.InRange(bitmap.Height, 841, 843); + + // The corner holds no text, so it must be paper-white. This proves the bitmap was + // filled white before rendering; a zeroed (transparent black) buffer would otherwise + // count as "ink" everywhere and let a blank render pass the check below. + Assert.Equal(Color.White.ToArgb(), bitmap.GetPixel(2, 2).ToArgb()); + + int darkPixels = Pixels.CountDark(bitmap); + _output.WriteLine($"Dark pixels at 72 dpi: {darkPixels}"); + Assert.True(darkPixels > 100, $"Expected the text to leave ink on the page, found {darkPixels} dark pixels."); + } + } + + /// + /// The device-context path, the one printing uses, draws the page. Rendering onto a memory + /// device context exercises the exact native signature without needing a printer. + /// + [Fact] + public void RenderToDeviceContext_draws_the_page_onto_a_device_context() + { + byte[] pdf = FixtureFactory.CreatePdf(1); + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(pdf, null, out IPdfDocument? document)); + + // 24 bits per pixel on purpose: GDI leaves the alpha byte of 32-bit pixels at zero, which + // would make every pixel GDI touches look transparent instead of black. + using (document) + using (var target = new Bitmap(298, 421, PixelFormat.Format24bppRgb)) + { + using (Graphics graphics = Graphics.FromImage(target)) + { + graphics.Clear(Color.White); + IntPtr hdc = graphics.GetHdc(); + try + { + document!.RenderToDeviceContext(0, hdc, new Rectangle(0, 0, target.Width, target.Height), forPrinting: true, quarterTurns: 0); + } + finally + { + graphics.ReleaseHdc(hdc); + } + } + + int darkPixels = Pixels.CountDark(target); + _output.WriteLine($"Dark pixels on the device context: {darkPixels}"); + Assert.True(darkPixels > 50, $"Expected the page text on the device context, found {darkPixels} dark pixels."); + } + } + + /// + /// A page stored with /Rotate 90 reports its size as displayed: the A4 portrait page comes back + /// as landscape, width and height swapped. + /// + [Fact] + public void Page_with_Rotate_90_reports_its_displayed_size_with_width_and_height_swapped() + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1, rotation: 90), null, out IPdfDocument? document)); + + using (document) + { + SizeF size = document!.GetPageSizePoints(0); + + Assert.Equal(841.89f, size.Width, 0.5f); + Assert.Equal(595.28f, size.Height, 0.5f); + } + } + + /// + /// Bitmap rendering applies the page's own /Rotate and then the extra clockwise quarter turns. + /// The fixture's line of text sits near the top-left of the unturned A4 page, so after a net turn + /// it must be found where that turn puts it, with the bitmap's width and height to match. + /// + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(0, 2)] + [InlineData(0, 3)] + [InlineData(90, 0)] + [InlineData(90, 1)] + [InlineData(90, 3)] + public void RenderToBitmap_applies_the_page_rotation_and_the_extra_quarter_turns(int pageRotation, int quarterTurns) + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1, rotation: pageRotation), null, out IPdfDocument? document)); + + using (document) + using (Bitmap bitmap = document!.RenderToBitmap(0, 72, quarterTurns)) + { + int netTurns = ((pageRotation / 90) + quarterTurns) % 4; + AssertTextWhereTheTurnPutsIt(bitmap, netTurns); + } + } + + /// The device-context path turns the page by the requested quarter turns too. + [Theory] + [InlineData(1)] + [InlineData(3)] + public void RenderToDeviceContext_turns_the_page_by_the_quarter_turns(int quarterTurns) + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1), null, out IPdfDocument? document)); + + // A landscape-shaped target, half size, for the turned portrait page. + using (document) + using (var target = new Bitmap(421, 298, PixelFormat.Format24bppRgb)) + { + using (Graphics graphics = Graphics.FromImage(target)) + { + graphics.Clear(Color.White); + IntPtr hdc = graphics.GetHdc(); + try + { + document!.RenderToDeviceContext(0, hdc, new Rectangle(0, 0, target.Width, target.Height), forPrinting: true, quarterTurns); + } + finally + { + graphics.ReleaseHdc(hdc); + } + } + + AssertTextWhereTheTurnPutsIt(target, quarterTurns); + } + } + + /// Quarter turns outside 0 to 3 are refused by both render methods. + [Theory] + [InlineData(-1)] + [InlineData(4)] + public void Quarter_turns_outside_0_to_3_throw_ArgumentOutOfRangeException(int quarterTurns) + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1), null, out IPdfDocument? document)); + + using (document) + using (var target = new Bitmap(10, 10, PixelFormat.Format24bppRgb)) + using (Graphics graphics = Graphics.FromImage(target)) + { + Assert.Throws(() => document!.RenderToBitmap(0, 72, quarterTurns)); + IntPtr hdc = graphics.GetHdc(); + try + { + Assert.Throws(() => document!.RenderToDeviceContext(0, hdc, new Rectangle(0, 0, 10, 10), forPrinting: true, quarterTurns)); + } + finally + { + graphics.ReleaseHdc(hdc); + } + } + } + + /// + /// Two threads loading and rendering at the same moment both succeed. PDFium is not + /// thread-safe, so this only passes if the engine serialises every native call. + /// + [Fact] + public async Task Two_threads_loading_and_rendering_at_once_both_succeed() + { + const int Rounds = 5; + const int PagesPerDocument = 3; + byte[] pdf = FixtureFactory.CreatePdf(PagesPerDocument); + + // The barrier releases both threads together so their PDFium work really overlaps. + using var barrier = new Barrier(2); + + int RenderRepeatedly() + { + if (!barrier.SignalAndWait(TimeSpan.FromSeconds(30))) + { + throw new TimeoutException("The second thread never started."); + } + + int pagesWithInk = 0; + for (int round = 0; round < Rounds; round++) + { + PdfLoadStatus status = _engine.TryLoad(pdf, null, out IPdfDocument? document); + Assert.Equal(PdfLoadStatus.Ok, status); + + using (document) + { + for (int page = 0; page < document!.PageCount; page++) + { + using Bitmap bitmap = document.RenderToBitmap(page, 60, 0); + if (Pixels.CountDark(bitmap) > 0) + { + pagesWithInk++; + } + } + } + } + + return pagesWithInk; + } + + // LongRunning gives each worker its own thread, so the barrier cannot wait on a pool thread + // that never gets scheduled. + Task first = Task.Factory.StartNew(RenderRepeatedly, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task second = Task.Factory.StartNew(RenderRepeatedly, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + + int[] results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromMinutes(2), TestContext.Current.CancellationToken); + + Assert.Equal(Rounds * PagesPerDocument, results[0]); + Assert.Equal(Rounds * PagesPerDocument, results[1]); + } + + /// + /// Checks that the fixture's text ended up where a net clockwise turn puts it. Unturned, the text + /// is one line near the top-left of a portrait page. A quarter turn clockwise moves it to the + /// top-right running down (landscape bitmap), a half turn to the lower right upside down + /// (portrait), three quarters to the lower left running up (landscape). + /// + private static void AssertTextWhereTheTurnPutsIt(Bitmap bitmap, int netTurns) + { + Rectangle ink = Pixels.InkBounds(bitmap); + Assert.False(ink.IsEmpty, "Expected the page's text in the rendering."); + bool landscape = bitmap.Width > bitmap.Height; + string where = $"net turns {netTurns}, bitmap {bitmap.Width} x {bitmap.Height}, ink {ink}"; + + switch (netTurns) + { + case 0: + Assert.False(landscape, where); + Assert.True(ink.Width > ink.Height && ink.Left < bitmap.Width / 4 && ink.Top < bitmap.Height / 4, where); + break; + case 1: + Assert.True(landscape, where); + Assert.True(ink.Height > ink.Width && ink.Left > bitmap.Width * 3 / 4 && ink.Top < bitmap.Height / 2, where); + break; + case 2: + Assert.False(landscape, where); + Assert.True(ink.Width > ink.Height && ink.Right > bitmap.Width / 2 && ink.Top > bitmap.Height * 3 / 4, where); + break; + default: + Assert.True(landscape, where); + Assert.True(ink.Height > ink.Width && ink.Right < bitmap.Width / 4 && ink.Bottom > bitmap.Height / 2, where); + break; + } + } +} diff --git a/tests/PDFStream.NET.Tests/Fixtures/FixtureFactory.cs b/tests/PDFStream.NET.Tests/Fixtures/FixtureFactory.cs new file mode 100644 index 0000000..e418495 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Fixtures/FixtureFactory.cs @@ -0,0 +1,144 @@ +using PdfSharp; +using PdfSharp.Drawing; +using PdfSharp.Fonts; +using PdfSharp.Pdf; +using PdfSharp.Pdf.IO; + +namespace PDFStream.NET.Tests.Fixtures; + +/// +/// Builds small PDFs in memory for the tests, so the repository holds no binary fixture files +/// and every test states exactly what kind of PDF it needs. +/// +/// +/// PDFsharp (MIT, pinned to exactly 6.2.4 in the project file; 6.5.0 and later are AGPL-3.0-only) +/// does the writing. +/// It is used only here and never ships with PDFStream.NET. +/// +public static class FixtureFactory +{ + /// US Letter width in points (8.5 inches at 72 points per inch). + public const double LetterWidthPoints = 612; + + /// US Letter height in points (11 inches at 72 points per inch). + public const double LetterHeightPoints = 792; + + // PDFsharp keeps process-wide font state. Tests in different classes may run in parallel, + // so building one fixture at a time keeps the generator out of the picture when a + // concurrency test fails. + private static readonly object Gate = new(); + + static FixtureFactory() + { + // The cross-platform PDFsharp 6 build no longer reads the Windows font folder unless asked + // to. PDFStream.NET and its tests are Windows-only, so turning it on is the simplest way to get + // a real font (Arial) embedded in the fixtures. + GlobalFontSettings.UseWindowsFontsUnderWindows = true; + } + + /// + /// Creates a PDF whose pages each carry the line "Page N of M" in large black text near the + /// top-left corner, leaving the page margins white. + /// + /// Number of pages; must be at least 1 (PDFsharp cannot save an empty document). + /// + /// Password needed to open the PDF, or for none. + /// + /// + /// Password that grants full rights, or for none. Setting only this one + /// produces an encrypted PDF that still opens without any password. + /// + /// + /// When , odd pages (first, third, ...) are A4 portrait and even pages + /// are US Letter landscape; otherwise every page is A4 portrait. + /// + /// + /// A /Rotate value (0, 90, 180 or 270) written on every page after its content is drawn, so the + /// content itself stays as described above and only the way viewers display the page turns, + /// clockwise. 90 makes an A4 portrait page display as landscape with its text running down the + /// right-hand side. + /// + /// The complete PDF file as bytes. + public static byte[] CreatePdf(int pages, string? userPassword = null, string? ownerPassword = null, bool mixedSizes = false, int rotation = 0) + { + ArgumentOutOfRangeException.ThrowIfLessThan(pages, 1); + + lock (Gate) + { + using var document = new PdfDocument(); + document.Info.Title = "PDFStream.NET test fixture"; + var font = new XFont("Arial", 36); + + for (int i = 0; i < pages; i++) + { + PdfPage page = document.AddPage(); + if (mixedSizes && i % 2 == 1) + { + // Landscape is expressed by the page box itself (wider than tall) rather than + // by a /Rotate entry, which is how most generators write landscape pages. + page.Width = XUnit.FromPoint(LetterHeightPoints); + page.Height = XUnit.FromPoint(LetterWidthPoints); + } + else + { + page.Size = PageSize.A4; + } + + using (XGraphics gfx = XGraphics.FromPdfPage(page)) + { + gfx.DrawString($"Page {i + 1} of {pages}", font, XBrushes.Black, new XPoint(72, 144)); + } + + // Set after drawing, so the drawing is not adjusted for it: the content stays where + // it was written and only the displayed page turns. + if (rotation != 0) + { + page.Rotate = rotation; + } + } + + if (userPassword is not null || ownerPassword is not null) + { + if (userPassword is not null) + { + document.SecuritySettings.UserPassword = userPassword; + } + + if (ownerPassword is not null) + { + document.SecuritySettings.OwnerPassword = ownerPassword; + } + + // AES-256 is what current PDF tools produce by default, so it is the case that + // matters most; PDFium also reads the older RC4 and AES-128 schemes. + document.SecurityHandler.SetEncryptionToV5(); + } + + using var stream = new MemoryStream(); + document.Save(stream, false); + return stream.ToArray(); + } + } + + /// + /// Returns a copy of that needs to open, encrypted with + /// AES-256 by PDFsharp (which reads the file and writes it again; it may restructure the page tree). + /// + /// Any PDF PDFsharp can open, for example one from . + /// The password needed to open the result. + /// The encrypted PDF as bytes. + public static byte[] Encrypt(byte[] pdf, string userPassword) + { + lock (Gate) + { + using var input = new MemoryStream(pdf); + using PdfDocument document = PdfReader.Open(input, PdfDocumentOpenMode.Modify); + document.SecuritySettings.UserPassword = userPassword; + document.SecurityHandler.SetEncryptionToV5(); + + using var output = new MemoryStream(); + document.Save(output, false); + return output.ToArray(); + } + } +} diff --git a/tests/PDFStream.NET.Tests/Fixtures/FormFixtureFactory.cs b/tests/PDFStream.NET.Tests/Fixtures/FormFixtureFactory.cs new file mode 100644 index 0000000..bf7ab09 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Fixtures/FormFixtureFactory.cs @@ -0,0 +1,373 @@ +using System.Drawing; +using System.Text; + +namespace PDFStream.NET.Tests.Fixtures; + +/// +/// What goes into a PDF built by . The defaults give one page holding three +/// form fields (a filled text field, a ticked checkbox and a field that is not meant to be printed) and +/// nothing else, so any ink on the page can only come from the fields. +/// +public sealed record FormFixtureOptions +{ + /// + /// (the default) puts the three form fields on the page; + /// leaves them out and also drops the /AcroForm entry, which gives a page without any form. + /// + public bool WithFields { get; init; } = true; + + /// + /// (the default) lists the fields in the catalog's /AcroForm dictionary, as a + /// form-filling program writes them. leaves the widget annotations on the page + /// but removes /AcroForm, which is what page-extraction tools often produce. + /// + public bool WithAcroForm { get; init; } = true; + + /// + /// When , the text field carries only its value and no stored appearance, and the + /// form says /NeedAppearances true: the viewer (here PDFium's form engine) must build the appearance. + /// + public bool NeedAppearances { get; init; } + + /// + /// (the default) gives the text field its stored appearance (a black box). + /// leaves it with only its value, without the form saying /NeedAppearances. + /// + public bool TextFieldHasStoredAppearance { get; init; } = true; + + /// + /// When , the page's MediaBox, CropBox, Resources and Rotate are written on the + /// parent /Pages node instead of the page, so the page inherits them. + /// + public bool InheritPageAttributes { get; init; } + + /// When , the page has a CropBox 10 points inside its MediaBox on every side. + public bool WithCropBox { get; init; } + + /// The page's /Rotate value: 0, 90, 180 or 270. + public int Rotate { get; init; } + + /// + /// When , the page content itself draws a black square () + /// and a line of text in Helvetica (), so a test can check that + /// the page's own drawing survives whatever is done to its fields. + /// + public bool WithPageContent { get; init; } + + /// + /// When , the page also carries two ordinary (non-form) Square annotations marked + /// for printing: one with a stored appearance () and + /// one without (), which PDFium draws from its + /// colours. + /// + public bool WithMarkupAnnotations { get; init; } + + /// + /// When , the page content also draws three black squares through named entries of the + /// page's /Resources: a form XObject (), an image + /// () and the one glyph of a Type3 font + /// (). With those + /// resources are inherited from the /Pages node like the rest. + /// + /// + /// Each square shows whether its resource was found when the page was drawn: PDFium skips an XObject or an + /// image it cannot find, and replaces a font it cannot find with Helvetica, whose letter A covers only a + /// small part of the square. (A missing Helvetica, the font of the page's own text, falls back to Helvetica + /// and so looks the same, which is why these marks are needed.) + /// + public bool WithResourceMarks { get; init; } + + /// + /// When , the document starts with an extra page without form fields, of a different + /// size ( x + /// ), that draws one black square + /// (). The form page becomes page 2 (index 1). The extra page + /// carries all its own attributes, so it inherits nothing from the /Pages node. + /// + public bool WithLeadingPlainPage { get; init; } + + /// + /// When , the page content also draws a black square () + /// inside an optional-content layer that the document's layer settings switch off (/OCProperties /D /OFF), + /// so a correct rendering leaves that square white. The layer is named through the page's /Resources + /// (/Properties), inherited with the rest under . + /// + public bool WithHiddenLayer { get; init; } + + /// + /// The page's MediaBox, in place of the default 400 x 300 points (for pages of extreme sizes and shapes). The + /// fields and marks keep their positions, so on a small page they may lie outside it; the page still has its + /// form fields. (the default) keeps 400 x 300. + /// + public PdfRect? MediaBox { get; init; } + + /// + /// When , the page's /Annots array also names object 99, which the file does not + /// contain: a damaged reference, of the kind hand edits and some generators leave behind. PDF readers skip + /// such an entry; PDFium's page copy drops the whole /Annots array because of it. + /// + public bool WithDanglingAnnotationReference { get; init; } +} + +/// +/// A rectangle in PDF user space, in points, with the origin at the bottom-left corner of the page. +/// +/// Left edge. +/// Bottom edge. +/// Right edge. +/// Top edge. +public readonly record struct PdfRect(float Left, float Bottom, float Right, float Top) +{ + /// Width in points. + public float Width => Right - Left; + + /// Height in points. + public float Height => Top - Bottom; + + /// The rectangle as written in a PDF array. + public string ToPdfArray() => $"[{Number(Left)} {Number(Bottom)} {Number(Right)} {Number(Top)}]"; + + /// + /// A number as PDF syntax allows it: plain decimal digits, never exponent notation (which .NET uses for very + /// large or small floats and which PDF readers do not accept). + /// + private static string Number(float value) => ((double)value).ToString("0.#########", System.Globalization.CultureInfo.InvariantCulture); + + /// + /// Where the rectangle lands in a rendering of an unrotated, uncropped fixture page at + /// , with two pixels trimmed off every side (where anti-aliasing softens the + /// edge), so that a fully inked rectangle counts as fully dark. + /// + /// The resolution of the rendering. + public Rectangle ToInnerPixels(int dpi) => ToInnerPixels(dpi, FormFixtureFactory.PageHeightPoints); + + /// + /// As , for an unrotated, uncropped page + /// tall (the leading plain page is not as tall as the form page). + /// + /// The resolution of the rendering. + /// The height of the page the rectangle is on, in points. + public Rectangle ToInnerPixels(int dpi, float pageHeightPoints) + { + double scale = dpi / 72.0; + int left = (int)Math.Round(Left * scale) + 2; + int top = (int)Math.Round((pageHeightPoints - Top) * scale) + 2; + int right = (int)Math.Round(Right * scale) - 2; + int bottom = (int)Math.Round((pageHeightPoints - Bottom) * scale) - 2; + return Rectangle.FromLTRB(left, top, right, bottom); + } +} + +/// +/// Builds small PDFs with interactive form fields by writing the PDF objects by hand. PDFsharp 6.2.4 (the +/// test project's generator) cannot create form fields with appearance streams, and writing the objects +/// directly states exactly what each test relies on: which field has which appearance, which flags, and +/// where everything sits on the page. +/// +/// +/// The page is 400 x 300 points. Every appearance is a solid black rectangle filling its annotation, so a +/// field that is drawn shows up as a fully dark rectangle and one that is not leaves white paper. +/// +public static class FormFixtureFactory +{ + /// Page width in points. + public const int PageWidthPoints = 400; + + /// Page height in points. + public const int PageHeightPoints = 300; + + /// The filled text field (value "HELLO"), printable. Its stored appearance is a black box. + public static readonly PdfRect TextField = new(20, 200, 220, 260); + + /// The ticked checkbox (state /On), printable. Its "On" appearance is a black square. + public static readonly PdfRect CheckBox = new(300, 200, 340, 240); + + /// A filled text field without the Print flag: shown on screen, never printed. + public static readonly PdfRect NonPrintingField = new(20, 20, 120, 80); + + /// A Square annotation with a stored black appearance (only with ). + public static readonly PdfRect MarkupWithAppearance = new(160, 20, 220, 80); + + /// A Square annotation filled black but without a stored appearance (only with ). + public static readonly PdfRect MarkupWithoutAppearance = new(260, 20, 320, 80); + + /// The black square the page content draws (only with ). + public static readonly PdfRect PageMark = new(350, 250, 390, 290); + + /// Roughly where the page content's line of text sits (only with ). + public static readonly PdfRect PageText = new(130, 130, 260, 170); + + /// The crop box used with . + public static readonly PdfRect CropBox = new(10, 10, 390, 290); + + /// The square a form XObject of the page's resources draws (only with ). + public static readonly PdfRect ResourceXObject = new(330, 100, 380, 150); + + /// The square an image of the page's resources fills (only with ). + public static readonly PdfRect ResourceImage = new(20, 100, 70, 150); + + /// The square the Type3 font of the page's resources draws as its letter A (only with ). + public static readonly PdfRect ResourceFontGlyph = new(270, 100, 320, 150); + + /// Width in points of the extra first page (only with ). + public const int LeadingPageWidthPoints = 300; + + /// Height in points of the extra first page (only with ). + public const int LeadingPageHeightPoints = 200; + + /// The black square on the extra first page, in that page's own coordinates (only with ). + public static readonly PdfRect LeadingPageMark = new(20, 20, 80, 80); + + /// The square drawn in the switched-off layer, which must stay white (only with ). + public static readonly PdfRect HiddenLayerMark = new(240, 200, 290, 240); + + /// Builds the PDF described by (the defaults when it is ). + /// The complete PDF file as bytes. + public static byte[] Create(FormFixtureOptions? options = null) + { + FormFixtureOptions o = options ?? new FormFixtureOptions(); + bool acroForm = o.WithFields && o.WithAcroForm; + + // Attributes a page may inherit from its parent. Written on the page or on /Pages, never both. + string mediaBox = "/MediaBox " + (o.MediaBox ?? new PdfRect(0, 0, PageWidthPoints, PageHeightPoints)).ToPdfArray(); + string cropBox = o.WithCropBox ? " /CropBox " + CropBox.ToPdfArray() : string.Empty; + string rotate = o.Rotate != 0 ? FormattableString.Invariant($" /Rotate {o.Rotate}") : string.Empty; + string fonts = "/F1 16 0 R" + (o.WithResourceMarks ? " /F3 19 0 R" : string.Empty); + string xObjects = o.WithResourceMarks ? " /XObject << /X1 17 0 R /Im1 18 0 R >>" : string.Empty; + string properties = o.WithHiddenLayer ? " /Properties << /MC0 23 0 R >>" : string.Empty; + string resources = " /Resources << /Font << " + fonts + " >>" + xObjects + properties + " >>"; + string pageAttributes = mediaBox + cropBox + rotate + resources; + + var annotations = new List(); + if (o.WithFields) + { + annotations.AddRange(["6 0 R", "8 0 R", "11 0 R"]); + } + + if (o.WithMarkupAnnotations) + { + annotations.AddRange(["13 0 R", "15 0 R"]); + } + + if (o.WithDanglingAnnotationReference) + { + // Object 99 is never written (the file has 24 objects), so this entry cannot be resolved. + annotations.Add("99 0 R"); + } + + var content = new StringBuilder(); + if (o.WithPageContent) + { + content.Append(FormattableString.Invariant($"0 0 0 rg {PageMark.Left} {PageMark.Bottom} {PageMark.Width} {PageMark.Height} re f\n")); + content.Append(FormattableString.Invariant($"BT /F1 36 Tf 0 0 0 rg {PageText.Left} {PageText.Bottom + 10} Td (WWWW) Tj ET\n")); + } + + if (o.WithResourceMarks) + { + // The XObject is drawn at its own size, the 2 x 2 image is stretched over its square, and the Type3 + // glyph is 1000 x 1000 glyph units (one em), so at this font size it fills its square exactly. + content.Append(FormattableString.Invariant($"q 1 0 0 1 {ResourceXObject.Left} {ResourceXObject.Bottom} cm /X1 Do Q\n")); + content.Append(FormattableString.Invariant($"q {ResourceImage.Width} 0 0 {ResourceImage.Height} {ResourceImage.Left} {ResourceImage.Bottom} cm /Im1 Do Q\n")); + content.Append(FormattableString.Invariant($"BT /F3 {ResourceFontGlyph.Height} Tf 0 0 0 rg {ResourceFontGlyph.Left} {ResourceFontGlyph.Bottom} Td (A) Tj ET\n")); + } + + if (o.WithHiddenLayer) + { + // Marked content tied to the layer /MC0 names in the page's /Properties; the layer is switched off. + content.Append(FormattableString.Invariant($"/OC /MC0 BDC 0 0 0 rg {HiddenLayerMark.Left} {HiddenLayerMark.Bottom} {HiddenLayerMark.Width} {HiddenLayerMark.Height} re f EMC\n")); + } + + // Fixed object numbers keep the cross-references readable; objects a variant does not use stay in the + // file unreferenced, which is valid PDF and invisible to a reader. + var objects = new string[24]; + string layers = o.WithHiddenLayer ? " /OCProperties << /OCGs [23 0 R] /D << /OFF [23 0 R] >> >>" : string.Empty; + objects[1] = "<< /Type /Catalog /Pages 2 0 R" + (acroForm ? " /AcroForm 3 0 R" : string.Empty) + layers + " >>"; + string kids = o.WithLeadingPlainPage ? "/Kids [21 0 R 4 0 R] /Count 2" : "/Kids [4 0 R] /Count 1"; + objects[2] = "<< /Type /Pages " + kids + (o.InheritPageAttributes ? " " + pageAttributes : string.Empty) + " >>"; + objects[3] = "<< /Fields [6 0 R 8 0 R 11 0 R]" + (o.NeedAppearances ? " /NeedAppearances true" : string.Empty) + + " /DR << /Font << /Helv 16 0 R >> >> /DA (/Helv 0 Tf 0 g) >>"; + objects[4] = "<< /Type /Page /Parent 2 0 R" + (o.InheritPageAttributes ? string.Empty : " " + pageAttributes) + + " /Contents 5 0 R /Annots [" + string.Join(' ', annotations) + "] >>"; + objects[5] = Stream(string.Empty, content.ToString()); + + // /F 4 is the Print flag. The text field's value is HELLO; its stored appearance is a black box. + objects[6] = "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (HELLO) /DA (/Helv 24 Tf 0 g) /Rect " + TextField.ToPdfArray() + + " /F 4 /P 4 0 R" + (o.NeedAppearances || !o.TextFieldHasStoredAppearance ? string.Empty : " /AP << /N 7 0 R >>") + " >>"; + objects[7] = BlackBox(TextField); + + // A checkbox in its "On" state: /AS picks the "On" appearance (a black square) out of the two. + objects[8] = "<< /Type /Annot /Subtype /Widget /FT /Btn /T (agree) /V /On /AS /On /Rect " + CheckBox.ToPdfArray() + + " /F 4 /P 4 0 R /AP << /N << /On 9 0 R /Off 10 0 R >> >> >>"; + objects[9] = BlackBox(CheckBox); + objects[10] = Stream(FormattableString.Invariant($"/Type /XObject /Subtype /Form /BBox [0 0 {CheckBox.Width} {CheckBox.Height}]"), string.Empty); + + // /F 0: no Print flag, so this field is on screen only and must never reach paper. + objects[11] = "<< /Type /Annot /Subtype /Widget /FT /Tx /T (internal) /V (X) /Rect " + NonPrintingField.ToPdfArray() + + " /F 0 /P 4 0 R /AP << /N 12 0 R >> >>"; + objects[12] = BlackBox(NonPrintingField); + + objects[13] = "<< /Type /Annot /Subtype /Square /Rect " + MarkupWithAppearance.ToPdfArray() + " /F 4 /P 4 0 R /AP << /N 14 0 R >> >>"; + objects[14] = BlackBox(MarkupWithAppearance); + + // No /AP: PDFium generates the appearance from the border and interior colours (/C and /IC). + objects[15] = "<< /Type /Annot /Subtype /Square /Rect " + MarkupWithoutAppearance.ToPdfArray() + + " /F 4 /C [0 0 0] /IC [0 0 0] /BS << /W 2 >> /P 4 0 R >>"; + objects[16] = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"; + + // The resources behind WithResourceMarks: a black form XObject, a 2 x 2 black greyscale image (written + // in hexadecimal so the file stays ASCII) and a Type3 font whose letter A is a filled em square. + objects[17] = BlackBox(ResourceXObject); + objects[18] = Stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "00000000>"); + objects[19] = "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0]" + + " /CharProcs << /square 20 0 R >> /Encoding << /Type /Encoding /Differences [65 /square] >>" + + " /FirstChar 65 /LastChar 65 /Widths [1000] /Resources << >> >>"; + + // d1 declares an uncoloured glyph (it is filled with the text colour) 1000 units wide. + objects[20] = Stream(string.Empty, "1000 0 0 0 1000 1000 d1 0 0 1000 1000 re f"); + + // The extra first page states every inheritable attribute itself, so nothing on /Pages reaches it. + PdfRect leadingBox = new(0, 0, LeadingPageWidthPoints, LeadingPageHeightPoints); + objects[21] = "<< /Type /Page /Parent 2 0 R /MediaBox " + leadingBox.ToPdfArray() + " /CropBox " + leadingBox.ToPdfArray() + + " /Rotate 0 /Resources << >> /Contents 22 0 R >>"; + objects[22] = Stream(string.Empty, FormattableString.Invariant($"0 0 0 rg {LeadingPageMark.Left} {LeadingPageMark.Bottom} {LeadingPageMark.Width} {LeadingPageMark.Height} re f")); + + // The optional-content group behind WithHiddenLayer, listed as off in the catalog's layer settings. + objects[23] = "<< /Type /OCG /Name (Hidden) >>"; + + return Assemble(objects); + } + + /// A form XObject that fills its whole bounding box with black, sized for . + private static string BlackBox(PdfRect rect) => Stream( + FormattableString.Invariant($"/Type /XObject /Subtype /Form /BBox [0 0 {rect.Width} {rect.Height}]"), + FormattableString.Invariant($"0 0 0 rg 0 0 {rect.Width} {rect.Height} re f")); + + /// A stream object: its dictionary (with the exact /Length) followed by its data. + private static string Stream(string dictionary, string data) => + $"<< {dictionary} /Length {Encoding.ASCII.GetByteCount(data)} >>\nstream\n{data}\nendstream"; + + /// + /// Writes the header, the numbered objects, the cross-reference table and the trailer. Everything is + /// ASCII, so a character count is a byte offset. + /// + private static byte[] Assemble(string[] objects) + { + var pdf = new StringBuilder("%PDF-1.7\n"); + var offsets = new int[objects.Length]; + for (int number = 1; number < objects.Length; number++) + { + offsets[number] = pdf.Length; + pdf.Append(FormattableString.Invariant($"{number} 0 obj\n{objects[number]}\nendobj\n")); + } + + int crossReference = pdf.Length; + pdf.Append(FormattableString.Invariant($"xref\n0 {objects.Length}\n0000000000 65535 f \n")); + for (int number = 1; number < objects.Length; number++) + { + pdf.Append(FormattableString.Invariant($"{offsets[number]:D10} 00000 n \n")); + } + + pdf.Append(FormattableString.Invariant($"trailer\n<< /Size {objects.Length} /Root 1 0 R >>\nstartxref\n{crossReference}\n%%EOF\n")); + return Encoding.ASCII.GetBytes(pdf.ToString()); + } +} diff --git a/tests/PDFStream.NET.Tests/Fixtures/Pixels.cs b/tests/PDFStream.NET.Tests/Fixtures/Pixels.cs new file mode 100644 index 0000000..4ac992b --- /dev/null +++ b/tests/PDFStream.NET.Tests/Fixtures/Pixels.cs @@ -0,0 +1,99 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; + +namespace PDFStream.NET.Tests.Fixtures; + +/// +/// Reads rendered output back as evidence: how much ink a bitmap holds and where it is. "Printed" +/// must mean pages were really drawn, so tests check pixels rather than trusting a status. +/// +public static class Pixels +{ + /// + /// Counts pixels darker than mid-grey. Text in the fixtures is black, so rendered text shows up + /// here while white paper does not. + /// + public static int CountDark(Bitmap bitmap) + { + int dark = 0; + ForEachDarkPixel(bitmap, (_, _) => dark++); + return dark; + } + + /// Counts the dark pixels (as defines them) inside . + public static int CountDarkIn(Bitmap bitmap, Rectangle area) + { + int dark = 0; + ForEachDarkPixel(bitmap, (x, y) => + { + if (area.Contains(x, y)) + { + dark++; + } + }); + return dark; + } + + /// + /// Which pixels are dark, row by row (index y * width + x). Two renderings of the same page can be + /// compared with it pixel for pixel. + /// + public static bool[] DarkMask(Bitmap bitmap) + { + var mask = new bool[bitmap.Width * bitmap.Height]; + int width = bitmap.Width; + ForEachDarkPixel(bitmap, (x, y) => mask[(y * width) + x] = true); + return mask; + } + + /// + /// The smallest rectangle holding every dark pixel, or when the + /// bitmap has none. Its position shows where a page landed on the sheet; its shape shows whether + /// a line of text runs across (wider than tall) or was turned (taller than wide). + /// + public static Rectangle InkBounds(Bitmap bitmap) + { + int left = int.MaxValue, top = int.MaxValue, right = -1, bottom = -1; + ForEachDarkPixel(bitmap, (x, y) => + { + left = Math.Min(left, x); + top = Math.Min(top, y); + right = Math.Max(right, x); + bottom = Math.Max(bottom, y); + }); + + return right < 0 ? Rectangle.Empty : Rectangle.FromLTRB(left, top, right + 1, bottom + 1); + } + + private static void ForEachDarkPixel(Bitmap bitmap, Action onDark) + { + var area = new Rectangle(0, 0, bitmap.Width, bitmap.Height); + + // Locking as 32-bit ARGB converts 24-bit sheets too, so one reader serves both formats. + BitmapData data = bitmap.LockBits(area, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + try + { + var row = new int[bitmap.Width]; + for (int y = 0; y < bitmap.Height; y++) + { + Marshal.Copy(data.Scan0 + (y * data.Stride), row, 0, row.Length); + for (int x = 0; x < row.Length; x++) + { + int argb = row[x]; + int red = (argb >> 16) & 0xFF; + int green = (argb >> 8) & 0xFF; + int blue = argb & 0xFF; + if (red + green + blue < 3 * 128) + { + onDark(x, y); + } + } + } + } + finally + { + bitmap.UnlockBits(data); + } + } +} diff --git a/tests/PDFStream.NET.Tests/Fixtures/RawPdfium.cs b/tests/PDFStream.NET.Tests/Fixtures/RawPdfium.cs new file mode 100644 index 0000000..d7daee8 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Fixtures/RawPdfium.cs @@ -0,0 +1,101 @@ +using System.Drawing; +using System.Drawing.Imaging; +using PDFStream.NET.Engine; +using Xunit; + +namespace PDFStream.NET.Tests.Fixtures; + +/// +/// Renders a page of a PDF straight through PDFium's own drawing calls, with exactly the flags PDFStream.NET +/// prints with and nothing else: no form handling, no flattening, no layout. It is the reference the +/// engine's output is compared with, so a test can show what PDFStream.NET adds (form fields) and prove that it +/// changes nothing else. +/// +internal static class RawPdfium +{ + /// The flags PDFStream.NET renders with: annotations, for printing. + private const int PrintFlags = PdfiumNative.RenderAnnotations | PdfiumNative.RenderForPrinting; + + /// The size of a page (page 1 by default) in points, as displayed, from a fresh, untouched copy of the PDF. + public static SizeF PageSize(byte[] pdf, int pageIndex = 0) => WithPage(pdf, pageIndex, null, (document, _) => + { + Assert.NotEqual(0, PdfiumNative.FPDF_GetPageSizeByIndexF(document, pageIndex, out PdfiumNative.FsSizeF size)); + return new SizeF(size.Width, size.Height); + }); + + /// Renders a page (page 1 by default) into a white 32-bit bitmap of the given pixel size with FPDF_RenderPageBitmap. + public static Bitmap RenderBitmap(byte[] pdf, int width, int height, int pageIndex = 0, string? password = null) => WithPage(pdf, pageIndex, password, (_, page) => + { + var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + BitmapData pixels = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + IntPtr pdfBitmap = PdfiumNative.FPDFBitmap_CreateEx(width, height, PdfiumNative.BitmapFormatBgra, pixels.Scan0, pixels.Stride); + Assert.NotEqual(IntPtr.Zero, pdfBitmap); + try + { + PdfiumNative.FPDFBitmap_FillRect(pdfBitmap, 0, 0, width, height, PdfiumNative.ColorWhite); + PdfiumNative.FPDF_RenderPageBitmap(pdfBitmap, page, 0, 0, width, height, 0, PrintFlags); + } + finally + { + PdfiumNative.FPDFBitmap_Destroy(pdfBitmap); + } + } + finally + { + bitmap.UnlockBits(pixels); + } + + return bitmap; + }); + + /// + /// Renders a page (page 1 by default) onto the device context of a white 24-bit bitmap of the given pixel + /// size with FPDF_RenderPage, the call PDFStream.NET uses on a printer. + /// + public static Bitmap RenderOnDeviceContext(byte[] pdf, int width, int height, int pageIndex = 0, string? password = null) => WithPage(pdf, pageIndex, password, (_, page) => + { + // 24 bits per pixel: GDI leaves the alpha byte of 32-bit pixels at zero (see PdfiumEngineTests). + var target = new Bitmap(width, height, PixelFormat.Format24bppRgb); + using Graphics graphics = Graphics.FromImage(target); + graphics.Clear(Color.White); + IntPtr hdc = graphics.GetHdc(); + try + { + Assert.NotEqual(0, PdfiumNative.FPDF_RenderPage(hdc, page, 0, 0, width, height, 0, PrintFlags)); + } + finally + { + graphics.ReleaseHdc(hdc); + } + + return target; + }); + + /// + /// Opens a private copy of the PDF, loads the page at and runs + /// with the document and page pointers, all under the process-wide PDFium lock, then + /// closes everything again. opens a password-protected PDF. + /// + private static T WithPage(byte[] pdf, int pageIndex, string? password, Func use) + { + lock (PdfiumLibrary.Sync) + { + PdfiumLibrary.EnsureInitialized(); + using PdfiumDocumentHandle handle = PdfiumDocumentHandle.Open(pdf, password, out int error) + ?? throw new InvalidOperationException($"PDFium could not open the reference copy (error {error})."); + IntPtr document = handle.DangerousGetHandle(); + IntPtr page = PdfiumNative.FPDF_LoadPage(document, pageIndex); + Assert.NotEqual(IntPtr.Zero, page); + try + { + return use(document, page); + } + finally + { + PdfiumNative.FPDF_ClosePage(page); + } + } + } +} diff --git a/tests/PDFStream.NET.Tests/Fixtures/SharedResourceFixtureFactory.cs b/tests/PDFStream.NET.Tests/Fixtures/SharedResourceFixtureFactory.cs new file mode 100644 index 0000000..1d31754 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Fixtures/SharedResourceFixtureFactory.cs @@ -0,0 +1,168 @@ +using System.Text; + +namespace PDFStream.NET.Tests.Fixtures; + +/// How the pages of a PDF get their one shared /Resources dictionary. +public enum SharedResources +{ + /// The dictionary is written once, inline, on the /Pages node, and every page inherits it. + Inherited, + + /// The dictionary is one indirect object that every page names as its own /Resources. + Indirect, +} + +/// +/// Builds PDFs of many pages that all share one /Resources dictionary holding several large images, each page +/// drawing one of them and (optionally) carrying one filled text field. Generators do write PDFs like this, with +/// one dictionary for the whole document. It is the shape that made copying form pages one by one multiply +/// memory: every copy cloned everything the dictionary holds, so the cost grew with the number of form pages +/// times the size of the shared images. +/// +/// +/// Pages are x points. The images are +/// x 8-bit grey pixels, stored uncompressed (one megabyte each), all +/// black, and each page draws its image over . A page whose image is missing on paper +/// therefore shows a white square there. The field of page p lies at (p): four +/// different places, so a test can tell whose field landed on which page. +/// +public static class SharedResourceFixtureFactory +{ + /// Page width in points. + public const int PageWidthPoints = 400; + + /// Page height in points. + public const int PageHeightPoints = 300; + + /// Width and height, in pixels, of every shared image (one byte per pixel, so one megabyte each). + public const int ImageSide = 1000; + + /// The square each page fills with its shared image. + public static readonly PdfRect ImageMark = new(20, 20, 120, 120); + + /// Where the filled text field of page lies (one of four places). + /// The zero-based page index. + public static PdfRect FieldOn(int pageIndex) + { + float left = 20 + (90 * (pageIndex % 4)); + return new PdfRect(left, 200, left + 80, 250); + } + + /// Builds the PDF. + /// How many pages. + /// How many one-megabyte images the shared dictionary holds; page p draws image p % images. + /// Whether every page carries a filled, printable text field (and the catalog an /AcroForm). + /// How the pages get the shared dictionary. + /// + /// When , every page names one and the same indirect /Contents array (holding one content + /// stream that draws the first image), as a generator that writes identical pages once might. Flattening + /// appends to a page's content array, so pages that share one must not end up drawing each other's fields. + /// + /// The complete PDF file as bytes. + public static byte[] Create(int pages, int images, bool withFields, SharedResources resources, bool sharedContentArray = false) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pages); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(images); + + // Object numbers: 1 catalog, 2 /Pages, 3 /AcroForm, 4 the shared /Resources (used when indirect), then + // the images, then four objects per page (page, content, widget, widget appearance), then the shared + // content stream and the shared content array (used with sharedContentArray). + const int Catalog = 1, PageTree = 2, AcroForm = 3, SharedDictionary = 4; + int firstImage = 5; + int firstPage = firstImage + images; + int sharedContentStream = firstPage + (4 * pages); + int sharedContents = sharedContentStream + 1; + int objectCount = sharedContents + 1; + var bodies = new byte[objectCount][]; + + var xObjects = new StringBuilder(); + for (int i = 0; i < images; i++) + { + xObjects.Append(FormattableString.Invariant($"/Im{i} {firstImage + i} 0 R ")); + } + + string sharedDictionary = "<< /XObject << " + xObjects + ">> >>"; + var kids = new StringBuilder(); + var fields = new StringBuilder(); + for (int p = 0; p < pages; p++) + { + int page = firstPage + (4 * p); + kids.Append(FormattableString.Invariant($"{page} 0 R ")); + if (withFields) + { + fields.Append(FormattableString.Invariant($"{page + 2} 0 R ")); + } + } + + string inheritedResources = resources == SharedResources.Inherited ? " /Resources " + sharedDictionary : string.Empty; + bodies[Catalog] = Ascii("<< /Type /Catalog /Pages 2 0 R" + (withFields ? " /AcroForm 3 0 R" : string.Empty) + " >>"); + bodies[PageTree] = Ascii(FormattableString.Invariant($"<< /Type /Pages /Kids [{kids}] /Count {pages} /MediaBox [0 0 {PageWidthPoints} {PageHeightPoints}]{inheritedResources} >>")); + bodies[AcroForm] = Ascii("<< /Fields [" + fields + "] >>"); + bodies[SharedDictionary] = Ascii(sharedDictionary); + + // All zero bytes: black in DeviceGray. The same buffer serves every image; only the PDF holds copies. + byte[] imageData = new byte[ImageSide * ImageSide]; + for (int i = 0; i < images; i++) + { + bodies[firstImage + i] = Stream(FormattableString.Invariant($"/Type /XObject /Subtype /Image /Width {ImageSide} /Height {ImageSide} /ColorSpace /DeviceGray /BitsPerComponent 8"), imageData); + } + + for (int p = 0; p < pages; p++) + { + int page = firstPage + (4 * p); + PdfRect field = FieldOn(p); + string ownResources = resources == SharedResources.Indirect ? " /Resources 4 0 R" : string.Empty; + string annotations = withFields ? FormattableString.Invariant($" /Annots [{page + 2} 0 R]") : string.Empty; + int contents = sharedContentArray ? sharedContents : page + 1; + bodies[page] = Ascii(FormattableString.Invariant($"<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R{ownResources}{annotations} >>")); + bodies[page + 1] = Stream(string.Empty, Ascii(FormattableString.Invariant($"q {ImageMark.Width} 0 0 {ImageMark.Height} {ImageMark.Left} {ImageMark.Bottom} cm /Im{p % images} Do Q"))); + + // /F 4 is the Print flag; the stored appearance is a black box the size of the field. + bodies[page + 2] = Ascii(FormattableString.Invariant($"<< /Type /Annot /Subtype /Widget /FT /Tx /T (field{p}) /V (x) /Rect {field.ToPdfArray()} /F 4 /P {page} 0 R /AP << /N {page + 3} 0 R >> >>")); + bodies[page + 3] = Stream(FormattableString.Invariant($"/Type /XObject /Subtype /Form /BBox [0 0 {field.Width} {field.Height}]"), Ascii(FormattableString.Invariant($"0 0 0 rg 0 0 {field.Width} {field.Height} re f"))); + } + + // Always written (a valid PDF may hold objects nothing refers to); only used with sharedContentArray. + bodies[sharedContentStream] = Stream(string.Empty, Ascii(FormattableString.Invariant($"q {ImageMark.Width} 0 0 {ImageMark.Height} {ImageMark.Left} {ImageMark.Bottom} cm /Im0 Do Q"))); + bodies[sharedContents] = Ascii(FormattableString.Invariant($"[{sharedContentStream} 0 R]")); + return Assemble(bodies); + } + + /// The bytes of an ASCII string. + private static byte[] Ascii(string text) => Encoding.ASCII.GetBytes(text); + + /// A stream object: its dictionary (with the exact /Length) followed by its raw data. + private static byte[] Stream(string dictionary, byte[] data) + { + using var stream = new MemoryStream(); + stream.Write(Ascii(FormattableString.Invariant($"<< {dictionary} /Length {data.Length} >>\nstream\n"))); + stream.Write(data); + stream.Write(Ascii("\nendstream")); + return stream.ToArray(); + } + + /// Writes the header, the numbered objects, the cross-reference table and the trailer. + private static byte[] Assemble(byte[][] bodies) + { + using var pdf = new MemoryStream(); + pdf.Write(Ascii("%PDF-1.7\n")); + var offsets = new long[bodies.Length]; + for (int number = 1; number < bodies.Length; number++) + { + offsets[number] = pdf.Position; + pdf.Write(Ascii(FormattableString.Invariant($"{number} 0 obj\n"))); + pdf.Write(bodies[number]); + pdf.Write(Ascii("\nendobj\n")); + } + + long crossReference = pdf.Position; + pdf.Write(Ascii(FormattableString.Invariant($"xref\n0 {bodies.Length}\n0000000000 65535 f \n"))); + for (int number = 1; number < bodies.Length; number++) + { + pdf.Write(Ascii(FormattableString.Invariant($"{offsets[number]:D10} 00000 n \n"))); + } + + pdf.Write(Ascii(FormattableString.Invariant($"trailer\n<< /Size {bodies.Length} /Root 1 0 R >>\nstartxref\n{crossReference}\n%%EOF\n"))); + return pdf.ToArray(); + } +} diff --git a/tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj b/tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj new file mode 100644 index 0000000..494eba0 --- /dev/null +++ b/tests/PDFStream.NET.Tests/PDFStream.NET.Tests.csproj @@ -0,0 +1,74 @@ + + + + + PDFStream.NET.Tests + PDFStream.NET.Tests + + Exe + false + true + + false + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PDFStream.NET.Tests/PageRangeParserTests.cs b/tests/PDFStream.NET.Tests/PageRangeParserTests.cs new file mode 100644 index 0000000..c575547 --- /dev/null +++ b/tests/PDFStream.NET.Tests/PageRangeParserTests.cs @@ -0,0 +1,172 @@ +using Xunit; + +namespace PDFStream.NET.Tests; + +/// Tests : the 1-based page-range text becomes zero-based page indexes. +public sealed class PageRangeParserTests +{ + /// Null, empty and blank text all mean "print every page". + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Empty_means_all_pages(string? spec) + { + bool ok = PageRangeParser.TryParse(spec, 4, out IReadOnlyList pages, out PrintStatus error); + + Assert.True(ok); + Assert.Equal(PrintStatus.Ok, error); + Assert.Equal(new[] { 0, 1, 2, 3 }, pages); + } + + /// The example from the public documentation: ranges and single pages, in the order written. + [Fact] + public void Parses_1_to_5_8_10_to_12_in_order() + { + bool ok = PageRangeParser.TryParse("1-5, 8, 10-12", 12, out IReadOnlyList pages, out PrintStatus error); + + Assert.True(ok); + Assert.Equal(PrintStatus.Ok, error); + Assert.Equal(new[] { 0, 1, 2, 3, 4, 7, 9, 10, 11 }, pages); + } + + /// The order and the repeats written by the caller are kept, so "3, 1, 3" prints page 3, 1, 3. + [Fact] + public void Keeps_order_and_duplicates_as_written() + { + bool ok = PageRangeParser.TryParse("3, 1, 3, 2-3", 5, out IReadOnlyList pages, out _); + + Assert.True(ok); + Assert.Equal(new[] { 2, 0, 2, 1, 2 }, pages); + } + + /// Spaces around numbers, commas and dashes are ignored; a single-page range is allowed. + [Fact] + public void Tolerates_spaces_and_single_page_ranges() + { + bool ok = PageRangeParser.TryParse(" 2 - 2 ,4 ", 5, out IReadOnlyList pages, out _); + + Assert.True(ok); + Assert.Equal(new[] { 1, 3 }, pages); + } + + /// A range that runs backwards is a typing mistake, not "pages 2 to 5 in reverse". + [Fact] + public void Reversed_range_5_to_2_is_InvalidPageRange() + { + bool ok = PageRangeParser.TryParse("5-2", 10, out IReadOnlyList pages, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.InvalidPageRange, error); + Assert.Empty(pages); + } + + /// Pages are numbered from 1, so 0 and negative numbers cannot be pages. + [Theory] + [InlineData("0")] + [InlineData("-1")] + [InlineData("0-3")] + [InlineData("2, 0")] + public void Zero_or_negative_is_InvalidPageRange(string spec) + { + bool ok = PageRangeParser.TryParse(spec, 10, out IReadOnlyList pages, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.InvalidPageRange, error); + Assert.Empty(pages); + } + + /// A well-formed page that the document does not have is reported as PageNotFound. + [Theory] + [InlineData("4", 3)] + [InlineData("1-4", 3)] + [InlineData("1, 2, 99", 3)] + [InlineData("1-2000000000", 3)] + [InlineData("99999999999", 3)] + [InlineData("1", 0)] + public void Page_beyond_count_is_PageNotFound(string spec, int pageCount) + { + bool ok = PageRangeParser.TryParse(spec, pageCount, out IReadOnlyList pages, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.PageNotFound, error); + Assert.Empty(pages); + } + + /// The last page itself is fine. + [Fact] + public void Last_page_is_accepted() + { + bool ok = PageRangeParser.TryParse("3", 3, out IReadOnlyList pages, out _); + + Assert.True(ok); + Assert.Equal(new[] { 2 }, pages); + } + + /// Anything that is not numbers, commas and dashes is a mistake in the text. + [Theory] + [InlineData("abc")] + [InlineData("1-x")] + [InlineData("1,,2")] + [InlineData("1,")] + [InlineData(",1")] + [InlineData("1-")] + [InlineData("1-2-3")] + [InlineData("1.5")] + [InlineData("+2")] + [InlineData("1 2")] + [InlineData("all")] + public void Non_numeric_is_InvalidPageRange(string spec) + { + bool ok = PageRangeParser.TryParse(spec, 10, out IReadOnlyList pages, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.InvalidPageRange, error); + Assert.Empty(pages); + } + + /// + /// A reversed range is a typo even when a bound is too large for an int: "99999999999-2" runs from + /// high to low, so it is InvalidPageRange and not PageNotFound. When both bounds overflow the + /// digits are compared as numbers. + /// + [Theory] + [InlineData("99999999999-2")] + [InlineData("99999999999-88888888888")] + [InlineData("3, 99999999999-2")] + public void Reversed_range_with_an_overflowing_number_is_InvalidPageRange(string spec) + { + bool ok = PageRangeParser.TryParse(spec, 10, out IReadOnlyList pages, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.InvalidPageRange, error); + Assert.Empty(pages); + } + + /// An overflowing bound in the right order is a page the document does not have. + [Theory] + [InlineData("2-99999999999")] + [InlineData("88888888888-99999999999")] + [InlineData("99999999999-99999999999")] + public void Ascending_range_with_an_overflowing_number_is_PageNotFound(string spec) + { + bool ok = PageRangeParser.TryParse(spec, 10, out IReadOnlyList pages, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.PageNotFound, error); + Assert.Empty(pages); + } + + /// + /// When the text is both malformed and mentions a missing page, the malformed text is reported: + /// the caller has to fix the text before the page numbers mean anything. + /// + [Fact] + public void Malformed_text_wins_over_missing_page() + { + bool ok = PageRangeParser.TryParse("99, abc", 3, out _, out PrintStatus error); + + Assert.False(ok); + Assert.Equal(PrintStatus.InvalidPageRange, error); + } +} diff --git a/tests/PDFStream.NET.Tests/PdfPrinterTests.cs b/tests/PDFStream.NET.Tests/PdfPrinterTests.cs new file mode 100644 index 0000000..aac5a9d --- /dev/null +++ b/tests/PDFStream.NET.Tests/PdfPrinterTests.cs @@ -0,0 +1,556 @@ +// Every Print call here takes an optional CancellationToken that cancels the print job, not the test run, so +// the analyzer's advice to pass the test's own token does not apply. +#pragma warning disable xUnit1051 + +using System.Drawing; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Fixtures; +using PDFStream.NET.Tests.Printing; +using Xunit; + +namespace PDFStream.NET.Tests; + +/// +/// Tests , the public facade: option checks, the order of the steps (options, +/// load, page range, printer settings, job), that bad input never throws, that every document is +/// disposed and that unexpected failures become results. The print job itself is faked through the +/// runner, except in the one test that prints onto bitmaps and checks the ink. A test that has to get +/// past the printer check uses the installed "Microsoft Print to PDF" printer (it is never printed to) +/// and skips, with the reason shown, when that printer is missing. +/// +public sealed class PdfPrinterTests +{ + /// An engine that hands out a prepared document, or throws, and counts how often it was asked. + private sealed class FakeEngine(Func? open = null, Exception? throws = null) : IPdfEngine + { + public int Loads { get; private set; } + + public PdfLoadStatus TryLoad(byte[] pdf, string? password, out IPdfDocument? document) + { + Loads++; + if (throws is not null) + { + throw throws; + } + + document = open!(); + return PdfLoadStatus.Ok; + } + } + + /// A document that forwards to another one and remembers whether it was disposed. + private sealed class TrackedDocument(IPdfDocument inner) : IPdfDocument + { + public bool Disposed { get; private set; } + + public int PageCount => inner.PageCount; + + public System.Drawing.SizeF GetPageSizePoints(int pageIndex) => inner.GetPageSizePoints(pageIndex); + + public void RenderToDeviceContext(int pageIndex, IntPtr hdc, Rectangle destinationPixels, bool forPrinting, int quarterTurns) => + inner.RenderToDeviceContext(pageIndex, hdc, destinationPixels, forPrinting, quarterTurns); + + public Bitmap RenderToBitmap(int pageIndex, int dpi, int quarterTurns) => inner.RenderToBitmap(pageIndex, dpi, quarterTurns); + + public void Dispose() + { + Disposed = true; + inner.Dispose(); + } + } + + /// A printer list with fixed names. + private sealed class FakeCatalog(params string[] names) : IPrinterCatalog + { + public IReadOnlyList GetInstalledPrinterNames() => names; + } + + /// A job runner that records what the facade handed it instead of printing. + private sealed class RecordingRunner + { + private readonly object _gate = new(); + + public int Calls { get; private set; } + + public List PageLists { get; } = []; + + public string? DocumentName { get; private set; } + + public ScaleMode? Scale { get; private set; } + + public short? Copies { get; private set; } + + public string? PrinterName { get; private set; } + + public CancellationToken Token { get; private set; } + + /// What the runner returns; when , success with every page counted. + public PrintResult? Result { get; init; } + + /// When set, the runner throws this instead. + public Exception? Throws { get; init; } + + public PrintResult Run(IPdfDocument doc, IReadOnlyList pages, System.Drawing.Printing.PrinterSettings settings, string documentName, ScaleMode scale, CancellationToken token) + { + lock (_gate) + { + Calls++; + PageLists.Add(pages.ToArray()); + DocumentName = documentName; + Scale = scale; + Copies = settings.Copies; + PrinterName = settings.PrinterName; + Token = token; + } + + if (Throws is not null) + { + throw Throws; + } + + return Result ?? PrintResult.Success(pages.Count); + } + } + + private static PrintOptions ToPdfPrinter(string? pages = null) => + new() { PrinterName = TestPrinters.MicrosoftPrintToPdf, Pages = pages }; + + private static (FakeEngine Engine, TrackedDocument Document) FakeLetterEngine(int pages) + { + var document = new TrackedDocument(FakePdfDocument.Letter(pages)); + return (new FakeEngine(() => document), document); + } + + // The bytes only have to be non-empty: the fake engine does not read them. + private static readonly byte[] AnyBytes = [1, 2, 3]; + + /// A stream that cannot be read, like a connection that dropped. + private sealed class BrokenStream : Stream + { + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override int Read(byte[] buffer, int offset, int count) => throw new IOException("The connection was closed (test)."); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + /// Null options are a bad input like any other: InvalidOptions on every overload, never an exception. + [Fact] + public void Null_options_is_InvalidOptions() + { + byte[] pdf = FixtureFactory.CreatePdf(1); + using var stream = new MemoryStream(pdf); + + PrintResult[] results = + [ + PdfPrinter.Print("any.pdf", null!), + PdfPrinter.Print(stream, null!), + PdfPrinter.Print(pdf, null!), + ]; + + Assert.All(results, result => + { + Assert.Equal(PrintStatus.InvalidOptions, result.Status); + Assert.False(result.Succeeded); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(Messages.InvalidOptions(), result.Message); + }); + } + + /// + /// A table of bad inputs, every one of which must come back as a result with the right status, the + /// standard message, no pages and no exception, whichever overload it goes through. + /// + [Fact] + public void Bad_input_never_throws() + { + byte[] pdf = FixtureFactory.CreatePdf(1); + PrintOptions good = ToPdfPrinter(); + string missingFile = Path.Combine(Path.GetTempPath(), "pdfstream.net-missing-" + Guid.NewGuid().ToString("N") + ".pdf"); + + (string Case, Func Call, PrintStatus Expected)[] table = + [ + ("null path", () => PdfPrinter.Print((string)null!, good), PrintStatus.FileNotFound), + ("empty path", () => PdfPrinter.Print("", good), PrintStatus.FileNotFound), + ("blank path", () => PdfPrinter.Print(" ", good), PrintStatus.FileNotFound), + ("missing file", () => PdfPrinter.Print(missingFile, good), PrintStatus.FileNotFound), + ("folder instead of file", () => PdfPrinter.Print(Path.GetTempPath(), good), PrintStatus.FileNotFound), + ("null bytes", () => PdfPrinter.Print((byte[])null!, good), PrintStatus.InvalidPdf), + ("empty bytes", () => PdfPrinter.Print(Array.Empty(), good), PrintStatus.InvalidPdf), + ("garbage bytes", () => PdfPrinter.Print(new byte[] { 0x00, 0x01, 0x02, 0xFF, 0x10 }, good), PrintStatus.InvalidPdf), + ("text that is not a PDF", () => PdfPrinter.Print("This is not a PDF."u8.ToArray(), good), PrintStatus.InvalidPdf), + ("null stream", () => PdfPrinter.Print((Stream)null!, good), PrintStatus.InvalidPdf), + ("empty stream", () => PdfPrinter.Print(new MemoryStream(), good), PrintStatus.InvalidPdf), + ("broken stream", () => PdfPrinter.Print(new BrokenStream(), good), PrintStatus.InvalidPdf), + ("empty printer name", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "" }), PrintStatus.InvalidOptions), + ("default options (no printer name)", () => PdfPrinter.Print(pdf, new PrintOptions()), PrintStatus.InvalidOptions), + ("blank printer name", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = " " }), PrintStatus.InvalidOptions), + ("Copies 0", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "P", Copies = 0 }), PrintStatus.InvalidOptions), + ("Copies -1", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "P", Copies = -1 }), PrintStatus.InvalidOptions), + ("Copies too many", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "P", Copies = 40000 }), PrintStatus.InvalidOptions), + ("undefined Duplex", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "P", Duplex = (DuplexMode)99 }), PrintStatus.InvalidOptions), + ("undefined Scale", () => PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "P", Scale = (ScaleMode)99 }), PrintStatus.InvalidOptions), + ("options are checked before the file", () => PdfPrinter.Print(missingFile, new PrintOptions()), PrintStatus.InvalidOptions), + ("malformed page range", () => PdfPrinter.Print(pdf, ToPdfPrinter("5-2")), PrintStatus.InvalidPageRange), + ("page range beyond the document", () => PdfPrinter.Print(pdf, ToPdfPrinter("2")), PrintStatus.PageNotFound), + ]; + + foreach ((string name, Func call, PrintStatus expected) in table) + { + PrintResult result = call(); + + Assert.True(result.Status == expected, $"{name}: expected {expected} but got {result.Status} ({result.Message})."); + Assert.False(result.Succeeded, name); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(Messages.For(expected), result.Message); + } + } + + /// A protected PDF reports whether a password is missing or wrong, before any printer work. + [Fact] + public void Protected_pdf_reports_missing_and_wrong_password() + { + byte[] pdf = FixtureFactory.CreatePdf(1, userPassword: "open-sesame"); + var runner = new RecordingRunner(); + + PrintResult missing = PdfPrinter.Print(pdf, ToPdfPrinter(), new PdfiumEngine(), new FakeCatalog(), runner.Run); + PrintResult wrong = PdfPrinter.Print(pdf, new PrintOptions { PrinterName = "P", Password = "nope" }, new PdfiumEngine(), new FakeCatalog(), runner.Run); + + Assert.Equal(PrintStatus.PasswordRequired, missing.Status); + Assert.Equal(PrintStatus.PasswordInvalid, wrong.Status); + Assert.Equal(0, runner.Calls); + } + + /// An unknown printer is PrinterNotFound; the job is never started and the document is released. + [Fact] + public void Unknown_printer_is_PrinterNotFound_and_nothing_printed() + { + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(2); + var runner = new RecordingRunner(); + + PrintResult result = PdfPrinter.Print(AnyBytes, new PrintOptions { PrinterName = "No such printer" }, engine, new FakeCatalog("Another printer"), runner.Run); + + Assert.Equal(PrintStatus.PrinterNotFound, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(0, runner.Calls); + Assert.True(document.Disposed); + } + + /// + /// A PDF that is protected only by an owner password (restrictions, no open password) prints with no + /// password given. The job runs through the real print code onto bitmaps, so the test checks that + /// ink reached every sheet, not only the status. + /// + [Fact] + public void Owner_only_password_pdf_prints_without_password() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + byte[] pdf = FixtureFactory.CreatePdf(2, ownerPassword: "owner-secret"); + using var controller = new FakePrintController(); + + PrintResult result = PdfPrinter.Print( + pdf, + ToPdfPrinter(), + new PdfiumEngine(), + SystemPrinterCatalog.Instance, + (doc, pages, settings, name, scale, token) => PrintJob.Run(doc, pages, settings, name, scale, token, controller)); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.True(result.Succeeded); + Assert.Equal(2, result.PagesPrinted); + Assert.Equal(2, controller.Pages.Count); + Assert.All(controller.Pages, sheet => Assert.True(Pixels.CountDark(sheet) > 50, "Expected the page's text on every sheet.")); + } + + /// Only the pages named in the range reach the job, in the order written, with the repeats written. + [Fact] + public void Page_range_selects_only_those_pages() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(5); + var runner = new RecordingRunner(); + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter("4, 2-3, 4"), engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.Equal(4, result.PagesPrinted); + Assert.Equal(1, runner.Calls); + Assert.Equal([3, 1, 2, 3], runner.PageLists.Single()); + Assert.True(document.Disposed); + } + + /// No page range means every page, and the options reach the job as given. + [Fact] + public void No_page_range_prints_every_page_and_passes_the_options_on() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + (FakeEngine engine, _) = FakeLetterEngine(3); + var runner = new RecordingRunner(); + using var cancellation = new CancellationTokenSource(); + var options = new PrintOptions + { + PrinterName = TestPrinters.MicrosoftPrintToPdf, + DocumentName = "Delivery note 7", + Copies = 3, + Scale = ScaleMode.ActualSize, + }; + + PrintResult result = PdfPrinter.Print(AnyBytes, options, engine, SystemPrinterCatalog.Instance, runner.Run, cancellation.Token); + + Assert.True(result.Succeeded); + Assert.Equal([0, 1, 2], runner.PageLists.Single()); + Assert.Equal("Delivery note 7", runner.DocumentName); + Assert.Equal(ScaleMode.ActualSize, runner.Scale); + Assert.Equal((short)3, runner.Copies); + Assert.Equal(TestPrinters.MicrosoftPrintToPdf, runner.PrinterName, ignoreCase: true); + Assert.Equal(cancellation.Token, runner.Token); + } + + /// + /// Whatever the job returns is passed through untouched: a failure keeps its status, message and its + /// zero pages, and a cancellation that ended the job normally keeps the exact page count. + /// + [Fact] + public void Job_result_is_passed_through_untouched() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + PrintResult[] fromJob = + [ + PrintResult.Failure(PrintStatus.UnknownError, "Page 2 failed (test)."), + PrintResult.Failure(PrintStatus.Cancelled, pagesPrinted: 2), + ]; + + foreach (PrintResult expected in fromJob) + { + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(4); + var runner = new RecordingRunner { Result = expected }; + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter(), engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Same(expected, result); + Assert.True(document.Disposed); + } + } + + /// A page beyond the document is PageNotFound; nothing is printed and the document is released. + [Fact] + public void Page_range_beyond_count_is_PageNotFound_and_nothing_printed() + { + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(3); + var runner = new RecordingRunner(); + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter("2-4"), engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Equal(PrintStatus.PageNotFound, result.Status); + Assert.Equal(Messages.PageNotFound(), result.Message); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(0, runner.Calls); + Assert.True(document.Disposed); + } + + /// A malformed page range is InvalidPageRange, found after the document opened and before any printer work. + [Fact] + public void Malformed_page_range_is_InvalidPageRange_and_nothing_printed() + { + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(3); + var runner = new RecordingRunner(); + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter("99999999999-2"), engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Equal(PrintStatus.InvalidPageRange, result.Status); + Assert.Equal(0, runner.Calls); + Assert.True(document.Disposed); + } + + /// + /// Several threads printing at once all succeed: the engine serialises its own work, so the calls wait + /// for each other instead of failing. The runner renders a page of the real document so the engine is + /// really used by every thread, and the ink is checked. + /// + [Fact] + public void Two_concurrent_prints_both_succeed() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + var engine = new PdfiumEngine(); + const int threads = 8; + var results = new PrintResult[threads]; + var ink = new int[threads]; + + Parallel.For(0, threads, new ParallelOptions { MaxDegreeOfParallelism = threads }, i => + { + byte[] pdf = FixtureFactory.CreatePdf(1 + (i % 3)); + results[i] = PdfPrinter.Print( + pdf, + ToPdfPrinter(), + engine, + SystemPrinterCatalog.Instance, + (doc, pages, settings, name, scale, token) => + { + using Bitmap page = doc.RenderToBitmap(pages[0], 40, 0); + ink[i] = Pixels.CountDark(page); + return PrintResult.Success(pages.Count); + }); + }); + + for (int i = 0; i < threads; i++) + { + Assert.True(results[i].Succeeded, $"Thread {i}: {results[i].Status} {results[i].Message}"); + Assert.Equal(1 + (i % 3), results[i].PagesPrinted); + Assert.True(ink[i] > 0, $"Thread {i} rendered a blank page."); + } + } + + /// + /// A failure of the engine itself (here a missing native library) is not thrown: it becomes + /// UnknownError, with the exception's message after the standard text for the person who looks after + /// the program. + /// + [Fact] + public void Unexpected_engine_exception_becomes_UnknownError() + { + var engine = new FakeEngine(throws: new DllNotFoundException("pdfium.dll could not be loaded (test).")); + var runner = new RecordingRunner(); + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter(), engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Equal(PrintStatus.UnknownError, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.StartsWith(Messages.UnknownError(), result.Message); + Assert.Contains("pdfium.dll could not be loaded (test).", result.Message); + Assert.Equal(0, runner.Calls); + } + + /// An exception thrown while the job runs is also a result, and the document is still released. + [Fact] + public void Unexpected_job_exception_becomes_UnknownError_and_the_document_is_released() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(2); + var runner = new RecordingRunner { Throws = new InvalidOperationException("The job exploded (test).") }; + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter(), engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Equal(PrintStatus.UnknownError, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.Contains("The job exploded (test).", result.Message); + Assert.True(document.Disposed); + } + + /// An exception with an empty message still says something in the details. + [Fact] + public void Exception_without_a_message_still_names_its_type() + { + var engine = new FakeEngine(throws: new DllNotFoundException("")); + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter(), engine, SystemPrinterCatalog.Instance, new RecordingRunner().Run); + + Assert.Equal(PrintStatus.UnknownError, result.Status); + Assert.Contains("DllNotFoundException", result.Message); + } + + /// A token that is already cancelled stops everything before the PDF is even opened. + [Fact] + public void Cancelled_before_start_returns_Cancelled_with_zero_pages() + { + var engine = new FakeEngine(() => FakePdfDocument.Letter(1)); + var runner = new RecordingRunner(); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + PrintResult result = PdfPrinter.Print(AnyBytes, ToPdfPrinter(), engine, SystemPrinterCatalog.Instance, runner.Run, cancellation.Token); + + Assert.Equal(PrintStatus.Cancelled, result.Status); + Assert.Equal(Messages.Cancelled(), result.Message); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(0, engine.Loads); + Assert.Equal(0, runner.Calls); + } + + /// The public overloads honour the token too. + [Fact] + public void Public_overloads_return_Cancelled_for_a_cancelled_token() + { + byte[] pdf = FixtureFactory.CreatePdf(1); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + using var stream = new MemoryStream(pdf); + + PrintResult[] results = + [ + PdfPrinter.Print("any.pdf", ToPdfPrinter(), cancellation.Token), + PdfPrinter.Print(stream, ToPdfPrinter(), cancellation.Token), + PdfPrinter.Print(pdf, ToPdfPrinter(), cancellation.Token), + ]; + + Assert.All(results, result => + { + Assert.Equal(PrintStatus.Cancelled, result.Status); + Assert.Equal(0, result.PagesPrinted); + }); + } + + /// + /// The printer lookup's own message (here the list of paper sources) reaches the result, not just the + /// standard text of the status. + /// + [Fact] + public void Paper_source_message_reaches_the_result() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + (FakeEngine engine, TrackedDocument document) = FakeLetterEngine(1); + var runner = new RecordingRunner(); + var options = new PrintOptions { PrinterName = TestPrinters.MicrosoftPrintToPdf, PaperSource = "Tray that does not exist 42" }; + + PrintResult result = PdfPrinter.Print(AnyBytes, options, engine, SystemPrinterCatalog.Instance, runner.Run); + + Assert.Equal(PrintStatus.InvalidOptions, result.Status); + Assert.NotEqual(Messages.InvalidOptions(), result.Message); + Assert.Contains("Tray that does not exist 42", result.Message); + Assert.StartsWith("The paper source", result.Message); + Assert.Equal(0, runner.Calls); + Assert.True(document.Disposed); + } + + /// The path overload reads a real file and the stream overload reads from the stream's current position. + [Fact] + public void Path_and_stream_overloads_load_the_pdf() + { + TestPrinters.RequireMicrosoftPrintToPdf(); + byte[] pdf = FixtureFactory.CreatePdf(2); + string path = Path.Combine(Path.GetTempPath(), "pdfstream.net-facade-" + Guid.NewGuid().ToString("N") + ".pdf"); + File.WriteAllBytes(path, pdf); + try + { + var runner = new RecordingRunner(); + using var stream = new MemoryStream(pdf); + + PrintResult fromPath = PdfPrinter.Print(path, ToPdfPrinter(), new PdfiumEngine(), SystemPrinterCatalog.Instance, runner.Run); + PrintResult fromStream = PdfPrinter.Print(stream, ToPdfPrinter("2"), new PdfiumEngine(), SystemPrinterCatalog.Instance, runner.Run); + + Assert.True(fromPath.Succeeded); + Assert.True(fromStream.Succeeded); + Assert.Equal([[0, 1], [1]], runner.PageLists); + } + finally + { + File.Delete(path); + } + } +} diff --git a/tests/PDFStream.NET.Tests/PdfSourceTests.cs b/tests/PDFStream.NET.Tests/PdfSourceTests.cs new file mode 100644 index 0000000..89023ca --- /dev/null +++ b/tests/PDFStream.NET.Tests/PdfSourceTests.cs @@ -0,0 +1,446 @@ +using System.Text; +using PDFStream.NET.Engine; +using PDFStream.NET.Tests.Fixtures; +using Xunit; + +namespace PDFStream.NET.Tests; + +/// +/// Tests : turning a file path, a stream or a byte array into an open +/// document, and every way that can fail into a instead of an exception. +/// +public sealed class PdfSourceTests : IDisposable +{ + private const string UserPassword = "open-sesame"; + + private readonly PdfiumEngine _engine = new(); + private readonly List _tempFiles = []; + + /// Deletes the temporary files this test created. + public void Dispose() + { + foreach (string path in _tempFiles) + { + File.Delete(path); + } + } + + /// A path that does not exist is reported as FileNotFound, without throwing. + [Fact] + public void Missing_file_is_FileNotFound() + { + string path = Path.Combine(Path.GetTempPath(), "pdfstream.net-" + Guid.NewGuid().ToString("N") + ".pdf"); + + PrintStatus status = PdfSource.Load(_engine, path, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.FileNotFound, status); + Assert.Null(doc); + } + + /// A null, empty or directory path is also FileNotFound: there is no file to read. + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Blank_path_is_FileNotFound(string? path) + { + PrintStatus status = PdfSource.Load(_engine, path!, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.FileNotFound, status); + Assert.Null(doc); + } + + /// A folder is not a PDF file, so reading it fails as FileNotFound. + [Fact] + public void Directory_path_is_FileNotFound() + { + PrintStatus status = PdfSource.Load(_engine, Path.GetTempPath(), null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.FileNotFound, status); + Assert.Null(doc); + } + + /// A real PDF file on disk loads and has its pages. + [Fact] + public void File_path_loads() + { + string path = Path.Combine(Path.GetTempPath(), "pdfstream.net-" + Guid.NewGuid().ToString("N") + ".pdf"); + _tempFiles.Add(path); + File.WriteAllBytes(path, FixtureFactory.CreatePdf(2)); + + PrintStatus status = PdfSource.Load(_engine, path, null, out IPdfDocument? doc); + + using (doc) + { + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(doc); + Assert.Equal(2, doc.PageCount); + } + } + + /// A byte array that holds a PDF loads. + [Fact] + public void Bytes_load() + { + PrintStatus status = PdfSource.Load(_engine, FixtureFactory.CreatePdf(3), null, out IPdfDocument? doc); + + using (doc) + { + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(doc); + Assert.Equal(3, doc.PageCount); + } + } + + /// A null or empty byte array is InvalidPdf. + [Fact] + public void Null_and_empty_bytes_are_InvalidPdf() + { + Assert.Equal(PrintStatus.InvalidPdf, PdfSource.Load(_engine, (byte[])null!, null, out IPdfDocument? first)); + Assert.Null(first); + Assert.Equal(PrintStatus.InvalidPdf, PdfSource.Load(_engine, Array.Empty(), null, out IPdfDocument? second)); + Assert.Null(second); + } + + /// A stream with no bytes in it is InvalidPdf. + [Fact] + public void Empty_stream_is_InvalidPdf() + { + using var stream = new MemoryStream(); + + PrintStatus status = PdfSource.Load(_engine, stream, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + } + + /// A null stream is InvalidPdf rather than an exception. + [Fact] + public void Null_stream_is_InvalidPdf() + { + PrintStatus status = PdfSource.Load(_engine, (Stream)null!, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + } + + /// + /// A stream that cannot seek (a network or pipe stream) loads. PDFStream.NET reads it to the end + /// and must not depend on Length or Position. + /// + [Fact] + public void Non_seekable_stream_loads() + { + using var stream = new ForwardOnlyStream(FixtureFactory.CreatePdf(2), chunkSize: 100); + + PrintStatus status = PdfSource.Load(_engine, stream, null, out IPdfDocument? doc); + + using (doc) + { + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(doc); + Assert.Equal(2, doc.PageCount); + } + } + + /// The caller's stream stays open: it belongs to the caller. + [Fact] + public void Stream_is_left_open() + { + using var stream = new MemoryStream(FixtureFactory.CreatePdf(1)); + + PrintStatus status = PdfSource.Load(_engine, stream, null, out IPdfDocument? doc); + doc?.Dispose(); + + Assert.Equal(PrintStatus.Ok, status); + Assert.True(stream.CanRead); + } + + /// A stream that cannot be read at all is InvalidPdf, not an exception. + [Fact] + public void Unreadable_stream_is_InvalidPdf() + { + using var stream = new FailingStream(); + + PrintStatus status = PdfSource.Load(_engine, stream, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + } + + /// Text that is not a PDF is InvalidPdf. + [Fact] + public void Garbage_bytes_are_InvalidPdf() + { + byte[] garbage = Encoding.ASCII.GetBytes("This is plain text pretending to be a PDF file."); + + PrintStatus status = PdfSource.Load(_engine, garbage, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + } + + /// A PDF cut off halfway is InvalidPdf and never an exception. + [Fact] + public void Truncated_pdf_is_InvalidPdf_not_exception() + { + byte[] whole = FixtureFactory.CreatePdf(2); + byte[] truncated = whole[..(whole.Length / 3)]; + + PrintStatus status = PdfSource.Load(_engine, truncated, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + } + + /// + /// Junk in front of the PDF header never throws. Pinned to what PDFium actually does (measured, + /// not assumed): it looks for the "%PDF-" header within the first 1024 bytes, so a few bytes or + /// a few hundred bytes of junk (a stray BOM, an HTTP header, a mail wrapper) still load with + /// all pages. + /// + [Theory] + [InlineData(5)] + [InlineData(300)] + public void Leading_junk_within_the_header_window_still_loads(int junkBytes) + { + byte[] pdf = [.. new byte[junkBytes].Select(_ => (byte)'x'), .. FixtureFactory.CreatePdf(2)]; + + PrintStatus status = PdfSource.Load(_engine, pdf, null, out IPdfDocument? doc); + + using (doc) + { + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(doc); + Assert.Equal(2, doc.PageCount); + } + } + + /// + /// A well-formed PDF that has no pages is InvalidPdf: there is nothing in it to print. (What + /// to do with an empty page selection is the facade's concern, not this class's.) + /// + [Fact] + public void Zero_page_pdf_is_InvalidPdf() + { + // PDFsharp cannot save a document without pages, so the smallest valid PDF is written by + // hand: a catalog and an empty page tree. + byte[] pdf = BuildZeroPagePdf(); + + PrintStatus status = PdfSource.Load(_engine, pdf, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + } + + /// + /// If the engine opens a document with no pages, the document is disposed instead of leaked. + /// + [Fact] + public void Zero_page_document_from_engine_is_disposed() + { + var fake = new FakeEngine(PdfLoadStatus.Ok, new FakeDocument(pageCount: 0)); + + PrintStatus status = PdfSource.Load(fake, new byte[] { 1 }, null, out IPdfDocument? doc); + + Assert.Equal(PrintStatus.InvalidPdf, status); + Assert.Null(doc); + Assert.True(fake.Document!.IsDisposed); + } + + /// + /// Each engine load status maps to the matching print status, for the real engine and a + /// protected PDF: no password, an empty password, a wrong one and the right one. + /// + [Fact] + public void Password_statuses_pass_through() + { + byte[] pdf = FixtureFactory.CreatePdf(1, userPassword: UserPassword, ownerPassword: "owner-secret"); + + Assert.Equal(PrintStatus.PasswordRequired, PdfSource.Load(_engine, pdf, null, out IPdfDocument? a)); + Assert.Null(a); + Assert.Equal(PrintStatus.PasswordRequired, PdfSource.Load(_engine, pdf, string.Empty, out IPdfDocument? b)); + Assert.Null(b); + Assert.Equal(PrintStatus.PasswordInvalid, PdfSource.Load(_engine, pdf, "wrong", out IPdfDocument? c)); + Assert.Null(c); + + PrintStatus ok = PdfSource.Load(_engine, pdf, UserPassword, out IPdfDocument? d); + using (d) + { + Assert.Equal(PrintStatus.Ok, ok); + Assert.NotNull(d); + } + } + + /// The path and stream overloads pass passwords through the same way. + [Fact] + public void Password_statuses_pass_through_for_streams() + { + byte[] pdf = FixtureFactory.CreatePdf(1, userPassword: UserPassword); + + using var noPassword = new MemoryStream(pdf); + using var wrongPassword = new MemoryStream(pdf); + using var rightPassword = new MemoryStream(pdf); + + Assert.Equal(PrintStatus.PasswordRequired, PdfSource.Load(_engine, noPassword, null, out _)); + Assert.Equal(PrintStatus.PasswordInvalid, PdfSource.Load(_engine, wrongPassword, "wrong", out _)); + + PrintStatus ok = PdfSource.Load(_engine, rightPassword, UserPassword, out IPdfDocument? doc); + using (doc) + { + Assert.Equal(PrintStatus.Ok, ok); + } + } + + /// + /// Every engine status maps to the right print status. A fake engine reaches the statuses + /// the real one would need special files for. + /// + [Fact] + public void Engine_failure_statuses_map_one_to_one() + { + // The engine enum is internal, so a theory cannot take it as a parameter: loop instead. + (PdfLoadStatus Engine, PrintStatus Expected)[] cases = + [ + (PdfLoadStatus.Invalid, PrintStatus.InvalidPdf), + (PdfLoadStatus.PasswordRequired, PrintStatus.PasswordRequired), + (PdfLoadStatus.PasswordInvalid, PrintStatus.PasswordInvalid), + ]; + + foreach ((PdfLoadStatus engineStatus, PrintStatus expected) in cases) + { + var fake = new FakeEngine(engineStatus, null); + + PrintStatus status = PdfSource.Load(fake, new byte[] { 1 }, null, out IPdfDocument? doc); + + Assert.Equal(expected, status); + Assert.Null(doc); + } + } + + /// + /// An unexpected engine failure, such as a missing pdfium.dll, is not about the caller's file, so it + /// is not turned into a status here: it reaches the facade with its message, which turns it into + /// UnknownError (see PdfPrinterTests). No document is handed out. + /// + [Fact] + public void Engine_exception_reaches_the_caller_with_its_message() + { + var fake = new FakeEngine(new DllNotFoundException("pdfium.dll")); + IPdfDocument? doc = null; + + var thrown = Assert.Throws(() => PdfSource.Load(fake, new byte[] { 1 }, null, out doc)); + + Assert.Equal("pdfium.dll", thrown.Message); + Assert.Null(doc); + } + + /// Builds a structurally valid PDF whose page tree has no pages. + private static byte[] BuildZeroPagePdf() + { + var body = new StringBuilder("%PDF-1.4\n"); + var offsets = new List(); + + void AddObject(string content) + { + offsets.Add(body.Length); + body.Append(offsets.Count).Append(" 0 obj\n").Append(content).Append("\nendobj\n"); + } + + AddObject("<< /Type /Catalog /Pages 2 0 R >>"); + AddObject("<< /Type /Pages /Kids [] /Count 0 >>"); + + // The cross-reference table lists where each object starts; offsets are byte positions, + // and the text is pure ASCII so characters and bytes are the same. + int xrefStart = body.Length; + body.Append("xref\n0 ").Append(offsets.Count + 1).Append('\n'); + body.Append("0000000000 65535 f \n"); + foreach (int offset in offsets) + { + body.Append(offset.ToString("D10")).Append(" 00000 n \n"); + } + + body.Append("trailer\n<< /Size ").Append(offsets.Count + 1).Append(" /Root 1 0 R >>\n"); + body.Append("startxref\n").Append(xrefStart).Append("\n%%EOF\n"); + return Encoding.ASCII.GetBytes(body.ToString()); + } + + /// A readable stream that cannot seek and hands data out in small pieces. + private sealed class ForwardOnlyStream(byte[] data, int chunkSize) : Stream + { + private int _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override int Read(byte[] buffer, int offset, int count) + { + int n = Math.Min(Math.Min(count, chunkSize), data.Length - _position); + Array.Copy(data, _position, buffer, offset, n); + _position += n; + return n; + } + + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + /// A stream whose reads always fail, like a dropped network connection. + private sealed class FailingStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override int Read(byte[] buffer, int offset, int count) => throw new IOException("The connection was closed."); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + /// An engine that returns a canned answer, or throws a canned exception. + private sealed class FakeEngine : IPdfEngine + { + private readonly PdfLoadStatus _status; + private readonly Exception? _failure; + + public FakeEngine(PdfLoadStatus status, FakeDocument? document) + { + _status = status; + Document = document; + } + + public FakeEngine(Exception failure) => _failure = failure; + + public FakeDocument? Document { get; } + + public PdfLoadStatus TryLoad(byte[] pdf, string? password, out IPdfDocument? document) + { + if (_failure is not null) + { + throw _failure; + } + + document = Document; + return _status; + } + } + + /// A document with a chosen page count that records whether it was disposed. + private sealed class FakeDocument(int pageCount) : IPdfDocument + { + public bool IsDisposed { get; private set; } + public int PageCount { get; } = pageCount; + public System.Drawing.SizeF GetPageSizePoints(int pageIndex) => throw new NotSupportedException(); + public void RenderToDeviceContext(int pageIndex, IntPtr hdc, System.Drawing.Rectangle destinationPixels, bool forPrinting, int quarterTurns) => throw new NotSupportedException(); + public System.Drawing.Bitmap RenderToBitmap(int pageIndex, int dpi, int quarterTurns) => throw new NotSupportedException(); + public void Dispose() => IsDisposed = true; + } +} diff --git a/tests/PDFStream.NET.Tests/PrintResultTests.cs b/tests/PDFStream.NET.Tests/PrintResultTests.cs new file mode 100644 index 0000000..02843d0 --- /dev/null +++ b/tests/PDFStream.NET.Tests/PrintResultTests.cs @@ -0,0 +1,167 @@ +using Xunit; + +namespace PDFStream.NET.Tests; + +/// Tests the plain-language messages and the shape of . +public sealed class PrintResultTests +{ + /// + /// Every status has a message. A failure message ends with a sentence that starts with an + /// instruction (what to do next); the Ok message ends with a confirmation. + /// + [Fact] + public void Every_status_has_a_non_empty_message_ending_with_what_to_do_next_or_confirmation() + { + // Words a "what to do next" sentence may open with. A new status with a message that + // does not end in advice makes this test fail, which is the point. + string[] instructionOpeners = + { + "Check", "Enter", "Ask", "Choose", "Open", "Try", "Install", "Use", "Make", "Contact", "Select", "Fix", "Wait", "Run", "Start", + }; + + foreach (PrintStatus status in Enum.GetValues()) + { + string message = Messages.For(status); + + Assert.False(string.IsNullOrWhiteSpace(message), $"{status} has no message."); + Assert.EndsWith(".", message); + + string lastSentence = LastSentence(message); + if (status == PrintStatus.Ok) + { + Assert.Contains("sent", lastSentence, StringComparison.OrdinalIgnoreCase); + } + else + { + string firstWord = lastSentence.Split(' ')[0]; + Assert.True( + instructionOpeners.Contains(firstWord), + $"{status}: the last sentence should tell the user what to do next, but it is \"{lastSentence}\"."); + } + } + } + + /// A message is its own text, not a copy of another status's text. + [Fact] + public void Every_status_has_its_own_message() + { + string[] messages = Enum.GetValues().Select(Messages.For).ToArray(); + + Assert.Equal(messages.Length, messages.Distinct().Count()); + } + + /// The success result carries the Ok message and the page count, and reports success. + [Fact] + public void Success_result_reports_pages_and_Ok() + { + PrintResult result = PrintResult.Success(3); + + Assert.True(result.Succeeded); + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.Equal(3, result.PagesPrinted); + Assert.Equal(Messages.For(PrintStatus.Ok), result.Message); + } + + /// A failure result is not a success and uses the status's message unless a more specific one is given. + [Fact] + public void Failure_result_is_not_a_success() + { + PrintResult result = PrintResult.Failure(PrintStatus.PrinterNotFound); + PrintResult partial = PrintResult.Failure(PrintStatus.Cancelled, pagesPrinted: 2); + PrintResult custom = PrintResult.Failure(PrintStatus.UnknownError, "Custom text."); + + Assert.False(result.Succeeded); + Assert.Equal(PrintStatus.PrinterNotFound, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(Messages.For(PrintStatus.PrinterNotFound), result.Message); + Assert.Equal(2, partial.PagesPrinted); + Assert.Equal("Custom text.", custom.Message); + } + + /// A failure can never be built with the Ok status, so Succeeded and Status cannot disagree. + [Fact] + public void Failure_with_Ok_status_is_rejected() + { + Assert.Throws(() => PrintResult.Failure(PrintStatus.Ok)); + } + + /// The options default to what the design promises: one copy, the printer's own colour and duplex, fit to page. + [Fact] + public void Options_have_the_documented_defaults() + { + var options = new PrintOptions(); + + Assert.Equal(1, options.Copies); + Assert.Null(options.Color); + Assert.Equal(ScaleMode.FitToPage, options.Scale); + Assert.Equal(DuplexMode.PrinterDefault, options.Duplex); + Assert.Null(options.Pages); + Assert.Null(options.Password); + Assert.Null(options.DocumentName); + Assert.Null(options.PaperSource); + Assert.Null(options.OutputFile); + Assert.Equal(string.Empty, options.PrinterName); + } + + /// + /// A custom message that is empty or only spaces would show the user a blank line, so the standard + /// message for the status is used instead; a real custom message is kept. + /// + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\t\r\n")] + public void Blank_custom_message_falls_back_to_the_standard_message(string blank) + { + PrintResult result = PrintResult.Failure(PrintStatus.PrinterNotFound, blank); + + Assert.Equal(Messages.For(PrintStatus.PrinterNotFound), result.Message); + } + + /// + /// The generic "printer unavailable" text is what a stopped Print Spooler produces when the printer + /// list itself cannot be read, so it must point at the spooler. + /// + [Fact] + public void PrinterUnavailable_message_hints_at_the_Print_Spooler() + { + Assert.Contains("Print Spooler", Messages.PrinterUnavailable()); + } + + /// + /// Under the default fit-to-page, "fit the page to the paper" is advice the caller already follows, + /// so the too-large advice must name something else: a smaller paper size or splitting the document. + /// + [Fact] + public void PageTooLarge_advice_is_not_circular_and_does_not_promise_a_withdrawn_job() + { + string message = Messages.PageTooLarge(3); + + Assert.DoesNotContain("fitted to the paper", message); + Assert.Contains("smaller paper size", message); + Assert.Contains("split", message); + Assert.DoesNotContain("job was withdrawn", message); + Assert.Contains("may have been withdrawn", message); + Assert.Contains("print queue", message); + } + + /// The page-failure text says the job may have been withdrawn and tells the user to check the queue. + [Fact] + public void PageFailed_message_does_not_promise_a_withdrawn_job() + { + string message = Messages.PageFailed(2, "boom"); + + Assert.DoesNotContain("job was withdrawn", message); + Assert.Contains("may have been withdrawn", message); + Assert.Contains("check the print queue", message, StringComparison.OrdinalIgnoreCase); + Assert.EndsWith("Details: boom", message); + } + + // The text after the last ". " (or the whole message if it is a single sentence). + private static string LastSentence(string message) + { + string body = message.TrimEnd('.'); + int cut = body.LastIndexOf(". ", StringComparison.Ordinal); + return cut < 0 ? body : body[(cut + 2)..]; + } +} diff --git a/tests/PDFStream.NET.Tests/PrinterLocatorTests.cs b/tests/PDFStream.NET.Tests/PrinterLocatorTests.cs new file mode 100644 index 0000000..758b36c --- /dev/null +++ b/tests/PDFStream.NET.Tests/PrinterLocatorTests.cs @@ -0,0 +1,604 @@ +using System.ComponentModel; +using System.Drawing.Printing; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Printing; +using Xunit; + +namespace PDFStream.NET.Tests; + +/// +/// Tests : option validation, printer-name matching and the settings +/// that end up on the printer. Name matching and the unknown-printer path use a fake printer list, +/// so they run anywhere. The tests that need a real printer use "Microsoft Print to PDF" and skip, +/// with the reason shown in the test output, when it is not installed. None of them prints, +/// opens a dialog or writes a file. +/// +public sealed class PrinterLocatorTests +{ + private const string PdfPrinter = "Microsoft Print to PDF"; + + /// A printer list that returns a fixed set of names, or fails like a stopped spooler. + private sealed class FakeCatalog(params string[] names) : IPrinterCatalog + { + public bool Fails { get; init; } + + public IReadOnlyList GetInstalledPrinterNames() => + Fails ? throw new InvalidOperationException("The Print Spooler service is not running.") : names; + } + + /// A printer list that fails with the given exception, as the print system does when it cannot be reached. + private sealed class ThrowingCatalog(Exception failure) : IPrinterCatalog + { + public IReadOnlyList GetInstalledPrinterNames() => throw failure; + } + + /// Skips the calling test, visibly, when the Microsoft Print to PDF printer is missing. + private static void RequirePdfPrinter() + { + bool installed = SystemPrinterCatalog.Instance.GetInstalledPrinterNames() + .Contains(PdfPrinter, StringComparer.OrdinalIgnoreCase); + Assert.SkipUnless(installed, $"The '{PdfPrinter}' printer is not installed on this machine, so the real-printer settings cannot be checked."); + } + + /// An empty or blank printer name is InvalidOptions and never reaches the print system. + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Missing_printer_name_is_InvalidOptions(string name) + { + var options = new PrintOptions { PrinterName = name }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, new FakeCatalog("Any"), out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.InvalidOptions, status); + Assert.Null(settings); + Assert.Equal(Messages.InvalidOptions(), message); + } + + /// The two-argument form that later tasks call gives the same answer. + [Fact] + public void Two_argument_overload_reports_InvalidOptions_too() + { + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions(), out PrinterSettings? settings); + + Assert.Equal(PrintStatus.InvalidOptions, status); + Assert.Null(settings); + } + + /// Null options are a bad input like any other, not a NullReferenceException. + [Fact] + public void Null_options_are_InvalidOptions() + { + PrintStatus status = PrinterLocator.TryCreateSettings(null!, new FakeCatalog(), out PrinterSettings? settings, out _); + + Assert.Equal(PrintStatus.InvalidOptions, status); + Assert.Null(settings); + } + + /// Zero, negative and too many copies are InvalidOptions. + [Theory] + [InlineData(0)] + [InlineData(-3)] + [InlineData(32768)] + public void Zero_copies_is_InvalidOptions(int copies) + { + var options = new PrintOptions { PrinterName = "Any", Copies = copies }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, new FakeCatalog("Any"), out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.InvalidOptions, status); + Assert.Null(settings); + Assert.Equal(Messages.InvalidOptions(), message); + } + + /// A name no installed printer has is PrinterNotFound, with the standard message. + [Fact] + public void Unknown_printer_is_PrinterNotFound() + { + var options = new PrintOptions { PrinterName = "No such printer " + Guid.NewGuid().ToString("N") }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, new FakeCatalog("Office Laser", "Front Desk"), out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.PrinterNotFound, status); + Assert.Null(settings); + Assert.Equal(Messages.PrinterNotFound(), message); + } + + /// Against the real print system an unknown name is PrinterNotFound too (no fake involved). + [Fact] + public void Unknown_printer_on_the_real_system_is_PrinterNotFound() + { + var options = new PrintOptions { PrinterName = "No such printer " + Guid.NewGuid().ToString("N") }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.PrinterNotFound, status); + Assert.Null(settings); + } + + /// A print system that cannot be read (spooler stopped) is PrinterUnavailable, not an exception. + [Fact] + public void Unreadable_print_system_is_PrinterUnavailable() + { + var options = new PrintOptions { PrinterName = "Any" }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, new FakeCatalog { Fails = true }, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Null(settings); + Assert.Equal(Messages.PrinterUnavailable(), message); + } + + /// + /// Reading the printer list fails with RPC_S_SERVER_UNAVAILABLE (1722), which is how Windows answers when the + /// Print Spooler service is not running: the result names the stopped spooler. The error code alone is + /// enough; the separate spooler check says "running" here. + /// + [Fact] + public void Printer_list_failing_with_rpc_server_unavailable_names_the_stopped_spooler() + { + var catalog = new ThrowingCatalog(new Win32Exception(1722)); + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) { SpoolerStopped = false }; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = "Any" }, catalog, probe, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Null(settings); + Assert.Equal(Messages.SpoolerNotRunning(), message); + } + + /// The same error code is recognised when it arrives wrapped in another exception. + [Fact] + public void Wrapped_rpc_server_unavailable_names_the_stopped_spooler() + { + var catalog = new ThrowingCatalog(new InvalidOperationException("Could not list printers.", new Win32Exception(1722))); + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) { SpoolerStopped = false }; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = "Any" }, catalog, probe, out _, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Equal(Messages.SpoolerNotRunning(), message); + } + + /// + /// Any other failure to read the printer list, while the spooler check reports the spooler stopped, also + /// names the stopped spooler. + /// + [Fact] + public void Printer_list_failing_while_the_spooler_is_stopped_names_the_stopped_spooler() + { + var catalog = new ThrowingCatalog(new InvalidOperationException("Something went wrong.")); + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) { SpoolerStopped = true }; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = "Any" }, catalog, probe, out _, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Equal(Messages.SpoolerNotRunning(), message); + } + + /// + /// Any other failure to read the printer list with the spooler running keeps the general printer message, + /// which also tells the reader to check the spooler; a spooler check that throws counts as "running". + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Printer_list_failing_with_the_spooler_running_keeps_the_general_message(bool spoolerCheckThrows) + { + var catalog = new ThrowingCatalog(new InvalidOperationException("Something went wrong.")); + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) + { + SpoolerStopped = false, + SpoolerCheckThrows = spoolerCheckThrows ? new InvalidOperationException("Cannot tell.") : null, + }; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = "Any" }, catalog, probe, out _, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Equal(Messages.PrinterUnavailable(), message); + } + + /// + /// A stopped spooler can also make the printer list come back empty, which on its own reads as "no such + /// printer". When the named printer is not found and the spooler check reports it stopped, the result names + /// the stopped spooler instead. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Missing_printer_while_the_spooler_is_stopped_names_the_stopped_spooler(bool listHasOtherPrinters) + { + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) { SpoolerStopped = true }; + var catalog = listHasOtherPrinters ? new FakeCatalog("Office Laser") : new FakeCatalog(); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = "Warehouse Printer 1" }, catalog, probe, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Null(settings); + Assert.Equal(Messages.SpoolerNotRunning(), message); + } + + /// + /// The real spooler check says "running" on a machine whose printer list can be read (this one). Stopping the + /// real spooler to see the other answer is left to the manual release checklist. + /// + [Fact] + public void Real_spooler_check_says_running_while_printers_can_be_listed() + { + bool listed; + try + { + listed = SystemPrinterCatalog.Instance.GetInstalledPrinterNames().Count > 0; + } + catch (Exception) + { + listed = false; + } + + Assert.SkipUnless(listed, "No printer list could be read on this machine, so the spooler cannot be shown to be running."); + Assert.False(WinspoolPrinterStatusProbe.Instance.IsSpoolerStopped()); + } + + /// A printer that is genuinely missing, with the spooler running, stays PrinterNotFound. + [Fact] + public void Missing_printer_while_the_spooler_runs_is_PrinterNotFound() + { + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) { SpoolerStopped = false }; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = "Warehouse Printer 1" }, new FakeCatalog("Office Laser"), probe, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.PrinterNotFound, status); + Assert.Null(settings); + Assert.Equal(Messages.PrinterNotFound(), message); + } + + /// + /// A name that is in the list but that Windows cannot open (a fake entry here) is + /// PrinterUnavailable, distinct from "not installed". + /// + [Fact] + public void Listed_but_unopenable_printer_is_PrinterUnavailable() + { + string ghost = "Ghost printer " + Guid.NewGuid().ToString("N"); + var options = new PrintOptions { PrinterName = ghost }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, new FakeCatalog(ghost), out PrinterSettings? settings, out _); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Null(settings); + } + + /// + /// Name matching ignores letter case and surrounding spaces, handles non-ASCII letters and + /// accepts the network form, and always returns the name exactly as the list spells it. + /// + [Theory] + [InlineData("Microsoft Print to PDF", "microsoft print to pdf", "Microsoft Print to PDF")] + [InlineData("Microsoft Print to PDF", "MICROSOFT PRINT TO PDF", "Microsoft Print to PDF")] + [InlineData("Microsoft Print to PDF", " Microsoft Print to PDF ", "Microsoft Print to PDF")] + [InlineData("Etiquetas Almac\u00E9n", "ETIQUETAS ALMAC\u00C9N", "Etiquetas Almac\u00E9n")] + [InlineData("\u30D7\u30EA\u30F3\u30BF\u30FC 1", "\u30D7\u30EA\u30F3\u30BF\u30FC 1", "\u30D7\u30EA\u30F3\u30BF\u30FC 1")] + [InlineData(@"\\SERVER\Label Printer", @"\\server\label printer", @"\\SERVER\Label Printer")] + [InlineData(@"\\server\printer", @"\\server\printer", @"\\server\printer")] + public void Printer_name_match_is_case_insensitive_and_accepts_network_form(string installed, string requested, string expected) + { + var catalog = new FakeCatalog("Other printer", installed, "Another one"); + + string? found = PrinterLocator.FindInstalledName(catalog, requested); + + Assert.Equal(expected, found); + } + + /// Names that only look alike do not match: a different server, a missing part, a changed space. + [Theory] + [InlineData(@"\\server2\printer")] + [InlineData(@"server\printer")] + [InlineData("MicrosoftPrint to PDF")] + [InlineData("Microsoft Print")] + [InlineData("Microsoft Print to PDF")] + public void Printer_name_match_does_not_guess(string requested) + { + var catalog = new FakeCatalog(@"\\server\printer", "Microsoft Print to PDF"); + + string? found = PrinterLocator.FindInstalledName(catalog, requested); + + Assert.Null(found); + } + + /// When two names differ only by case, the exact spelling wins. + [Fact] + public void Exact_spelling_beats_case_insensitive_match() + { + var catalog = new FakeCatalog("label printer", "Label Printer"); + + Assert.Equal("Label Printer", PrinterLocator.FindInstalledName(catalog, "Label Printer")); + Assert.Equal("label printer", PrinterLocator.FindInstalledName(catalog, "label printer")); + } + + /// The duplex choices map to the Windows ones; the default maps to "change nothing". + [Theory] + [InlineData(DuplexMode.PrinterDefault, Duplex.Default)] + [InlineData(DuplexMode.None, Duplex.Simplex)] + [InlineData(DuplexMode.LongEdge, Duplex.Vertical)] + [InlineData(DuplexMode.ShortEdge, Duplex.Horizontal)] + public void Duplex_mode_maps_to_the_windows_value(DuplexMode mode, Duplex expected) + { + Assert.Equal(expected, PrinterLocator.ToSystemDuplex(mode)); + } + + /// + /// Copies and colour reach the real printer settings, and the printer name is the installed + /// spelling even when the caller typed it in another case. + /// + [Fact] + public void Existing_printer_gets_copies_duplex_color_applied() + { + RequirePdfPrinter(); + var options = new PrintOptions + { + PrinterName = PdfPrinter.ToUpperInvariant(), + Copies = 3, + Color = false, + Duplex = DuplexMode.None, + }; + + PrintStatus status = PrinterLocator.TryCreateSettings(options, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + Assert.Equal(PdfPrinter, settings.PrinterName); + Assert.Equal(3, settings.Copies); + Assert.False(settings.DefaultPageSettings.Color); + Assert.False(settings.PrintToFile); + } + + /// + /// Leaving Color out keeps the printer's own colour setting: the settings come back with the colour the + /// driver reports for this printer, exactly as a fresh set of settings for it has. + /// + [Fact] + public void Color_left_out_keeps_the_printers_own_default() + { + RequirePdfPrinter(); + bool driverDefault = new PrinterSettings { PrinterName = PdfPrinter }.DefaultPageSettings.Color; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter }, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + Assert.Equal(1, settings.Copies); + Assert.Equal(driverDefault, settings.DefaultPageSettings.Color); + } + + /// + /// Leaving Color out never touches the colour on the settings. Real printer settings are first set to + /// black and white, standing in for a printer whose own default is black and white (Microsoft Print to PDF + /// defaults to colour, so the driver alone cannot show this); applying options without a colour must leave + /// them black and white rather than switch them to colour. + /// + [Fact] + public void Color_left_out_does_not_touch_the_colour_on_the_printer_settings() + { + RequirePdfPrinter(); + var settings = new PrinterSettings { PrinterName = PdfPrinter }; + settings.DefaultPageSettings.Color = false; + + PrintStatus status = PrinterLocator.Apply(new PrintOptions { PrinterName = PdfPrinter }, settings, outputFile: null, out _); + + Assert.Equal(PrintStatus.Ok, status); + Assert.False(settings.DefaultPageSettings.Color); + } + + /// Color = false forces black and white on settings that were set to colour. + [Fact] + public void Color_false_forces_black_and_white() + { + RequirePdfPrinter(); + var settings = new PrinterSettings { PrinterName = PdfPrinter }; + settings.DefaultPageSettings.Color = true; + + PrintStatus status = PrinterLocator.Apply(new PrintOptions { PrinterName = PdfPrinter, Color = false }, settings, outputFile: null, out _); + + Assert.Equal(PrintStatus.Ok, status); + Assert.False(settings.DefaultPageSettings.Color); + } + + /// Color = true forces colour on settings that were set to black and white. + [Fact] + public void Color_true_forces_colour() + { + RequirePdfPrinter(); + var settings = new PrinterSettings { PrinterName = PdfPrinter }; + settings.DefaultPageSettings.Color = false; + + PrintStatus status = PrinterLocator.Apply(new PrintOptions { PrinterName = PdfPrinter, Color = true }, settings, outputFile: null, out _); + + Assert.Equal(PrintStatus.Ok, status); + Assert.True(settings.DefaultPageSettings.Color); + } + + /// + /// Double-sided printing on a printer that cannot do it is PrinterUnavailable, not a silent + /// single-sided printout. Microsoft Print to PDF cannot duplex. + /// + [Theory] + [InlineData(DuplexMode.LongEdge)] + [InlineData(DuplexMode.ShortEdge)] + public void Duplex_on_a_printer_that_cannot_duplex_is_PrinterUnavailable(DuplexMode mode) + { + RequirePdfPrinter(); + Assert.SkipWhen(new PrinterSettings { PrinterName = PdfPrinter }.CanDuplex, $"'{PdfPrinter}' can duplex on this machine, so the refusal path cannot be shown."); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter, Duplex = mode }, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Null(settings); + } + + /// An output file turns on print to file with the full path, without creating the file. + [Fact] + public void OutputFile_sets_PrintToFile() + { + RequirePdfPrinter(); + string path = Path.Combine(Path.GetTempPath(), "pdfstream.net-" + Guid.NewGuid().ToString("N") + ".pdf"); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter, OutputFile = path }, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + Assert.True(settings.PrintToFile); + Assert.Equal(path, settings.PrintFileName); + Assert.False(File.Exists(path), "Preparing settings must not write the output file."); + } + + /// A relative output path is anchored to the current folder so a service's own working folder never surprises anyone. + [Fact] + public void Relative_OutputFile_becomes_a_full_path() + { + RequirePdfPrinter(); + string name = "pdfstream.net-" + Guid.NewGuid().ToString("N") + ".pdf"; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter, OutputFile = name }, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + Assert.Equal(Path.GetFullPath(name), settings.PrintFileName); + Assert.False(File.Exists(settings.PrintFileName)); + } + + /// An output file in a folder that does not exist, or that names a folder, is InvalidOptions. + [Fact] + public void Unusable_OutputFile_is_InvalidOptions() + { + string missingFolder = Path.Combine(Path.GetTempPath(), "pdfstream.net-" + Guid.NewGuid().ToString("N"), "out.pdf"); + + foreach (string bad in new[] { missingFolder, Path.GetTempPath(), " ", "bad|name?.pdf" }) + { + PrintStatus status = PrinterLocator.TryCreateSettings( + new PrintOptions { PrinterName = "Any", OutputFile = bad }, new FakeCatalog("Any"), out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.InvalidOptions, status); + Assert.Null(settings); + Assert.Equal(Messages.InvalidOutputFile(bad), message); + } + } + + /// + /// A paper source the printer does not have is InvalidOptions, and the message names the + /// printer's real sources so the caller can pick one. + /// + [Fact] + public void Unknown_paper_source_is_InvalidOptions_listing_the_available_sources() + { + RequirePdfPrinter(); + string[] real = new PrinterSettings { PrinterName = PdfPrinter }.PaperSources.Cast().Select(s => s.SourceName).ToArray(); + + PrintStatus status = PrinterLocator.TryCreateSettings( + new PrintOptions { PrinterName = PdfPrinter, PaperSource = "Tray that does not exist" }, SystemPrinterCatalog.Instance, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.InvalidOptions, status); + Assert.Null(settings); + Assert.Contains("Tray that does not exist", message); + Assert.Equal(Messages.UnknownPaperSource("Tray that does not exist", real), message); + foreach (string source in real) + { + Assert.Contains(source, message); + } + } + + /// The paper source message lists every source, or says there are none. + [Fact] + public void Unknown_paper_source_message_lists_sources_or_says_there_are_none() + { + string withSources = Messages.UnknownPaperSource("Tray 9", ["Tray 1", "Manual Feed"]); + string without = Messages.UnknownPaperSource("Tray 9", []); + + Assert.Contains("Tray 9", withSources); + Assert.Contains("Tray 1", withSources); + Assert.Contains("Manual Feed", withSources); + Assert.Contains("Tray 9", without); + Assert.Contains("does not report any", without); + } + + /// A known paper source is matched ignoring case and applied to the page settings. + [Fact] + public void Known_paper_source_is_applied_ignoring_case() + { + // Microsoft Print to PDF has no sources at all, so use the XPS writer, which lists + // "Automatically Select". Skips when it is not there. + const string xps = "Microsoft XPS Document Writer"; + Assert.SkipUnless( + SystemPrinterCatalog.Instance.GetInstalledPrinterNames().Contains(xps, StringComparer.OrdinalIgnoreCase), + $"The '{xps}' printer is not installed on this machine."); + string first = new PrinterSettings { PrinterName = xps }.PaperSources.Cast().Select(s => s.SourceName).FirstOrDefault() + ?? ""; + Assert.SkipWhen(first.Length == 0, $"'{xps}' reports no paper sources on this machine."); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = xps, PaperSource = first.ToUpperInvariant() }, out PrinterSettings? settings); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + Assert.Equal(first, settings.DefaultPageSettings.PaperSource.SourceName); + } + + /// + /// Settings creation checks the queue before handing out settings: a paused printer is refused with + /// the paused message, so the job never starts and nothing claims success. + /// + [Fact] + public void Paused_printer_is_PrinterUnavailable_before_any_settings_are_returned() + { + RequirePdfPrinter(); + var probe = FakeStatusProbe.Reading(0x00000001u); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter }, SystemPrinterCatalog.Instance, probe, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, status); + Assert.Null(settings); + Assert.Equal(Messages.PrinterPaused(PdfPrinter), message); + Assert.Equal([PdfPrinter], probe.Asked); + } + + /// + /// An offline report does not stop settings from being created: network printers often report + /// offline through SNMP while working, and a printer that really is off simply queues the job. + /// + [Fact] + public void Offline_report_does_not_block_settings() + { + RequirePdfPrinter(); + var probe = FakeStatusProbe.Reading(0x00000080u | 0x02000000u); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter }, SystemPrinterCatalog.Instance, probe, out PrinterSettings? settings, out _); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + } + + /// A status probe that fails does not stop settings from being created. + [Fact] + public void Unreadable_printer_status_does_not_block_settings() + { + RequirePdfPrinter(); + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read) { Throws = new InvalidOperationException("Status unavailable.") }; + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter }, SystemPrinterCatalog.Instance, probe, out PrinterSettings? settings, out string message); + + Assert.Equal(PrintStatus.Ok, status); + Assert.NotNull(settings); + Assert.Equal(Messages.Ok(), message); + } + + /// The probe is asked about the installed spelling of the name, not the caller's. + [Fact] + public void Status_probe_is_asked_about_the_installed_name() + { + RequirePdfPrinter(); + var probe = FakeStatusProbe.Reading(0); + + PrintStatus status = PrinterLocator.TryCreateSettings(new PrintOptions { PrinterName = PdfPrinter.ToUpperInvariant() }, SystemPrinterCatalog.Instance, probe, out _, out _); + + Assert.Equal(PrintStatus.Ok, status); + Assert.Equal([PdfPrinter], probe.Asked); + } +} diff --git a/tests/PDFStream.NET.Tests/Printing/FakePdfDocument.cs b/tests/PDFStream.NET.Tests/Printing/FakePdfDocument.cs new file mode 100644 index 0000000..ce7a9ca --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/FakePdfDocument.cs @@ -0,0 +1,125 @@ +using System.Drawing; +using System.Drawing.Imaging; +using PDFStream.NET.Engine; + +namespace PDFStream.NET.Tests.Printing; + +/// The two ways a page can be put on paper. +internal enum RenderKind +{ + /// Drawn straight onto the printer's device context. + DeviceContext, + + /// Rendered to a bitmap that is then drawn onto the sheet (the fallback). + Bitmap, +} + +/// One render request the printing code made. +/// Device context or bitmap. +/// Zero-based page index. +/// Device-context target in device pixels; empty for a bitmap. +/// Extra clockwise quarter turns requested. +/// Bitmap resolution; 0 for a device-context call. +internal sealed record RenderCall(RenderKind Kind, int PageIndex, Rectangle DestinationPixels, int QuarterTurns, int Dpi); + +/// +/// A stand-in for printing tests. It records every render request and can +/// refuse or fail them on demand. Built from page sizes, it "renders" a page as solid black (so the +/// output is easy to find on a sheet); built around a real document, it passes the calls on to it. +/// +internal sealed class FakePdfDocument : IPdfDocument +{ + private readonly IPdfDocument? _inner; + private readonly SizeF[] _pageSizes; + + /// Creates a fake document with these page sizes, in points. + public FakePdfDocument(params SizeF[] pageSizes) + { + _pageSizes = pageSizes; + } + + /// Wraps a real document: calls go through to it, but are recorded and can be refused. + public FakePdfDocument(IPdfDocument inner) + { + _inner = inner; + _pageSizes = []; + } + + /// Every render request, in order. + public List Calls { get; } = []; + + /// + /// When , every device-context call throws the exception the engine uses for + /// a device context that refuses the drawing calls, like a printer driver that cannot take them. + /// + public bool RefuseDeviceContext { get; init; } + + /// Returns the exception a bitmap render of the given page index throws, or . + public Func? BitmapFailure { get; init; } + + /// Runs at the start of every render request, with the page index (for example to cancel a job mid-way). + public Action? BeforeRender { get; init; } + + /// US Letter portrait pages. + public static FakePdfDocument Letter(int pages) => + new(Enumerable.Repeat(new SizeF(612, 792), pages).ToArray()); + + /// + public int PageCount => _inner?.PageCount ?? _pageSizes.Length; + + /// + public SizeF GetPageSizePoints(int pageIndex) => _inner?.GetPageSizePoints(pageIndex) ?? _pageSizes[pageIndex]; + + /// + public void RenderToDeviceContext(int pageIndex, IntPtr hdc, Rectangle destinationPixels, bool forPrinting, int quarterTurns) + { + Calls.Add(new RenderCall(RenderKind.DeviceContext, pageIndex, destinationPixels, quarterTurns, 0)); + BeforeRender?.Invoke(pageIndex); + if (RefuseDeviceContext) + { + throw new InvalidOperationException("The device context refused the drawing calls (test)."); + } + + if (_inner is not null) + { + _inner.RenderToDeviceContext(pageIndex, hdc, destinationPixels, forPrinting, quarterTurns); + return; + } + + // A Graphics made from the device context works in device pixels, the same units as the rectangle. + using Graphics graphics = Graphics.FromHdc(hdc); + graphics.FillRectangle(Brushes.Black, destinationPixels); + } + + /// + public Bitmap RenderToBitmap(int pageIndex, int dpi, int quarterTurns) + { + Calls.Add(new RenderCall(RenderKind.Bitmap, pageIndex, Rectangle.Empty, quarterTurns, dpi)); + BeforeRender?.Invoke(pageIndex); + if (BitmapFailure?.Invoke(pageIndex) is Exception failure) + { + throw failure; + } + + if (_inner is not null) + { + return _inner.RenderToBitmap(pageIndex, dpi, quarterTurns); + } + + SizeF size = GetPageSizePoints(pageIndex); + bool turned = quarterTurns % 2 == 1; + int width = Math.Max(1, (int)Math.Round((turned ? size.Height : size.Width) * dpi / 72.0)); + int height = Math.Max(1, (int)Math.Round((turned ? size.Width : size.Height) * dpi / 72.0)); + var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + bitmap.SetResolution(dpi, dpi); + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.Black); + } + + return bitmap; + } + + /// Disposes the wrapped document, if any. + public void Dispose() => _inner?.Dispose(); +} diff --git a/tests/PDFStream.NET.Tests/Printing/FakePrintController.cs b/tests/PDFStream.NET.Tests/Printing/FakePrintController.cs new file mode 100644 index 0000000..ad93723 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/FakePrintController.cs @@ -0,0 +1,135 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Drawing.Printing; + +namespace PDFStream.NET.Tests.Printing; + +/// +/// A print controller that "prints" onto in-memory bitmaps instead of a printer, so print jobs can be +/// tested without any printer, driver or spooler. Each page becomes one white 24-bit bitmap the size +/// of the sheet, which the tests then inspect pixel by pixel. +/// +/// +/// +/// It deliberately does not call base.OnStartPrint: that asks the printer driver for its +/// settings (a DEVMODE) and fails for a printer that is not installed. Without it, System.Drawing still +/// builds each page's event arguments, as long as the page settings name the paper size and the +/// orientation explicitly (see ), because then it never needs the driver. +/// +/// +/// 24 bits per pixel on purpose: GDI drawing (the device-context path) leaves the alpha byte of 32-bit +/// pixels at zero, which would make drawn pixels look transparent. +/// +/// +internal sealed class FakePrintController : PrintController, IDisposable +{ + private readonly int _sheetWidth; + private readonly int _sheetHeight; + private readonly int _dpi; + private readonly List _pages = []; + + /// Creates a controller whose sheets have the given size and resolution. + /// Sheet width in hundredths of an inch (850 is US Letter). + /// Sheet height in hundredths of an inch (1100 is US Letter). + /// Resolution of the sheet bitmaps, which the job sees as the printer resolution. + public FakePrintController(int sheetWidth = 850, int sheetHeight = 1100, int dpi = 100) + { + _sheetWidth = sheetWidth; + _sheetHeight = sheetHeight; + _dpi = dpi; + } + + /// One bitmap per page that was started, in order. + public IReadOnlyList Pages => _pages; + + /// How many times a job was started. + public int StartPrintCalls { get; private set; } + + /// The copy count the "driver" was asked for when the job started. + public short? CopiesAtStart { get; private set; } + + /// The name the job was given for the print queue. + public string? DocumentNameAtStart { get; private set; } + + /// + /// Whether the job ended as cancelled (a real controller then aborts the spooled job and nothing + /// prints) rather than normally; when the job never reached its end. + /// + public bool? EndedWithCancel { get; private set; } + + /// When set, starting the job throws this, like a printer that cannot be opened or was deleted. + public Exception? ThrowOnStartPrint { get; init; } + + /// + /// When , starting the job cancels it, as the real controller does when the + /// print system reports the job cancelled (for example a Save As box closed without saving). + /// + public bool CancelOnStartPrint { get; init; } + + /// Runs when the job starts, before any page (for example to cancel a token at that moment). + public Action? OnStartPrintCallback { get; init; } + + /// When set, closing the job throws this, like EndDoc or AbortDoc failing in the print system. + public Exception? ThrowOnEndPrint { get; init; } + + /// When set together with , starting that page throws this. + public Exception? ThrowOnStartPage { get; init; } + + /// The 1-based number of the page whose start throws . + public int ThrowOnStartPageNumber { get; init; } + + /// + public override void OnStartPrint(PrintDocument document, PrintEventArgs e) + { + StartPrintCalls++; + CopiesAtStart = document.PrinterSettings.Copies; + DocumentNameAtStart = document.DocumentName; + OnStartPrintCallback?.Invoke(); + if (ThrowOnStartPrint is not null) + { + throw ThrowOnStartPrint; + } + + e.Cancel = CancelOnStartPrint; + } + + /// + public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) + { + if (ThrowOnStartPage is not null && _pages.Count + 1 == ThrowOnStartPageNumber) + { + throw ThrowOnStartPage; + } + + var sheet = new Bitmap(ToPixels(_sheetWidth), ToPixels(_sheetHeight), PixelFormat.Format24bppRgb); + sheet.SetResolution(_dpi, _dpi); + _pages.Add(sheet); + + // The print loop disposes this Graphics when the page ends; the bitmap stays for inspection. + Graphics graphics = Graphics.FromImage(sheet); + graphics.Clear(Color.White); + return graphics; + } + + /// + public override void OnEndPrint(PrintDocument document, PrintEventArgs e) + { + EndedWithCancel = e.Cancel; + base.OnEndPrint(document, e); + if (ThrowOnEndPrint is not null) + { + throw ThrowOnEndPrint; + } + } + + /// Releases the page bitmaps. + public void Dispose() + { + foreach (Bitmap page in _pages) + { + page.Dispose(); + } + } + + private int ToPixels(int hundredths) => (int)Math.Round(hundredths * _dpi / 100.0); +} diff --git a/tests/PDFStream.NET.Tests/Printing/FakeStatusProbe.cs b/tests/PDFStream.NET.Tests/Printing/FakeStatusProbe.cs new file mode 100644 index 0000000..a2a99fe --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/FakeStatusProbe.cs @@ -0,0 +1,61 @@ +using PDFStream.NET.Printing; + +namespace PDFStream.NET.Tests.Printing; + +/// +/// A printer status probe that returns a fixed reading, or throws, so every queue state can be tested +/// without pausing or unplugging a real printer. +/// +internal sealed class FakeStatusProbe : IPrinterStatusProbe +{ + private readonly PrinterStatusReadOutcome _outcome; + private readonly uint _status; + private readonly uint _attributes; + + /// Creates a probe that reports the given outcome and raw winspool values. + public FakeStatusProbe(PrinterStatusReadOutcome outcome, uint status = 0, uint attributes = 0) + { + _outcome = outcome; + _status = status; + _attributes = attributes; + } + + /// When set, reading the status throws this instead. + public Exception? Throws { get; init; } + + /// The printer names asked about, in order. + public List Asked { get; } = []; + + /// What the spooler check reports: stands for a stopped Print Spooler. + public bool SpoolerStopped { get; init; } + + /// When set, the spooler check throws this instead of answering. + public Exception? SpoolerCheckThrows { get; init; } + + /// How many times the spooler check was made. + public int SpoolerChecks { get; private set; } + + /// A probe that reads these status and attribute bits. + public static FakeStatusProbe Reading(uint status, uint attributes = 0) => new(PrinterStatusReadOutcome.Read, status, attributes); + + /// + public PrinterStatusReadOutcome TryRead(string printerName, out uint status, out uint attributes) + { + Asked.Add(printerName); + if (Throws is not null) + { + throw Throws; + } + + status = _status; + attributes = _attributes; + return _outcome; + } + + /// Reports , or throws . + public bool IsSpoolerStopped() + { + SpoolerChecks++; + return SpoolerCheckThrows is null ? SpoolerStopped : throw SpoolerCheckThrows; + } +} diff --git a/tests/PDFStream.NET.Tests/Printing/PagePainterTests.cs b/tests/PDFStream.NET.Tests/Printing/PagePainterTests.cs new file mode 100644 index 0000000..1bd9a51 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/PagePainterTests.cs @@ -0,0 +1,581 @@ +using System.Drawing; +using System.Drawing.Imaging; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Fixtures; +using Xunit; + +namespace PDFStream.NET.Tests.Printing; + +/// +/// Tests : the layout math (where a page lands on the sheet, how large, and +/// whether it is turned) as a pure function, and , which draws a page +/// through the device context or the bitmap fallback. Sheets are in-memory bitmaps; no printer is used. +/// +/// +/// Printable areas and destinations are in hundredths of an inch, the unit of the Windows print system. +/// Page sizes are in points (1/72 inch). +/// +public sealed class PagePainterTests +{ + private const float Tolerance = 0.01f; + + // US Letter with quarter-inch margins, in hundredths of an inch. + private static readonly RectangleF PortraitArea = new(0, 0, 800, 1050); + private static readonly RectangleF LandscapeArea = new(0, 0, 1050, 800); + + private static readonly SizeF LetterPortrait = new(612, 792); + private static readonly SizeF LetterLandscape = new(792, 612); + private static readonly SizeF A4Portrait = new(595.28f, 841.89f); + private static readonly SizeF A5Portrait = new(419.53f, 595.28f); + private static readonly SizeF TabloidLandscape = new(1224, 792); + + private readonly PdfiumEngine _engine = new(); + + // ---------------------------------------------------------------- Fit to page + + /// A page relatively wider than the area is limited by the width and centred vertically. + [Fact] + public void Fit_portrait_page_on_portrait_sheet_fills_width_and_is_centred() + { + RectangleF destination = PagePainter.ComputeDestination(new SizeF(600, 700), new RectangleF(0, 0, 800, 1100), ScaleMode.FitToPage, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(0, 83.333f, 800, 933.333f), destination); + } + + /// A page relatively taller than the area is limited by the height and centred horizontally. + [Fact] + public void Fit_portrait_page_relatively_taller_than_the_sheet_fills_height_and_is_centred() + { + RectangleF destination = PagePainter.ComputeDestination(A4Portrait, PortraitArea, ScaleMode.FitToPage, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(28.785f, 0, 742.43f, 1050), destination); + } + + /// + /// A landscape page on a portrait sheet is turned, because turned it is printed much larger + /// (800 x 1035 instead of 800 x 618). The destination is the turned page's footprint. + /// + [Fact] + public void Fit_landscape_page_on_portrait_sheet_rotates() + { + RectangleF destination = PagePainter.ComputeDestination(LetterLandscape, PortraitArea, ScaleMode.FitToPage, out bool rotate); + + Assert.True(rotate); + AssertRect(new RectangleF(0, 7.353f, 800, 1035.294f), destination); + } + + /// The reverse: a portrait page on a landscape sheet is turned too. + [Fact] + public void Fit_portrait_page_on_landscape_sheet_rotates() + { + RectangleF destination = PagePainter.ComputeDestination(LetterPortrait, LandscapeArea, ScaleMode.FitToPage, out bool rotate); + + Assert.True(rotate); + AssertRect(new RectangleF(7.353f, 0, 1035.294f, 800), destination); + } + + /// A page with exactly the sheet's proportions fills the sheet, in either orientation. + [Fact] + public void Fit_page_with_the_sheet_proportions_fills_the_sheet_exactly() + { + RectangleF portrait = PagePainter.ComputeDestination(LetterPortrait, new RectangleF(0, 0, 850, 1100), ScaleMode.FitToPage, out bool portraitRotated); + RectangleF landscape = PagePainter.ComputeDestination(LetterLandscape, new RectangleF(0, 0, 1100, 850), ScaleMode.FitToPage, out bool landscapeRotated); + + Assert.False(portraitRotated); + Assert.False(landscapeRotated); + AssertRect(new RectangleF(0, 0, 850, 1100), portrait); + AssertRect(new RectangleF(0, 0, 1100, 850), landscape); + } + + /// Turning a square page gains nothing, so it is never turned. + [Theory] + [InlineData(800, 1100, 0, 150)] + [InlineData(1100, 800, 150, 0)] + public void Fit_square_page_is_never_rotated(float areaWidth, float areaHeight, float expectedX, float expectedY) + { + RectangleF destination = PagePainter.ComputeDestination(new SizeF(500, 500), new RectangleF(0, 0, areaWidth, areaHeight), ScaleMode.FitToPage, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(expectedX, expectedY, 800, 800), destination); + } + + /// On a square sheet turning gains nothing either. + [Fact] + public void Fit_landscape_page_on_square_sheet_is_not_rotated() + { + RectangleF destination = PagePainter.ComputeDestination(LetterLandscape, new RectangleF(0, 0, 1000, 1000), ScaleMode.FitToPage, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(0, 113.636f, 1000, 772.727f), destination); + } + + /// A page with the sheet's orientation is never turned, however narrow it is. + [Theory] + [InlineData(100, 1000, 800, 1100, 345, 0, 110, 1100)] + [InlineData(1000, 100, 1100, 800, 0, 345, 1100, 110)] + public void Fit_page_with_the_sheet_orientation_is_not_rotated_even_when_narrow( + float pageWidth, float pageHeight, float areaWidth, float areaHeight, float x, float y, float width, float height) + { + RectangleF destination = PagePainter.ComputeDestination(new SizeF(pageWidth, pageHeight), new RectangleF(0, 0, areaWidth, areaHeight), ScaleMode.FitToPage, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(x, y, width, height), destination); + } + + /// The destination is placed inside the printable area wherever that area starts. + [Fact] + public void Fit_is_placed_inside_a_printable_area_that_does_not_start_at_zero() + { + RectangleF destination = PagePainter.ComputeDestination(LetterLandscape, new RectangleF(25, 40, 800, 1050), ScaleMode.FitToPage, out bool rotate); + + Assert.True(rotate); + AssertRect(new RectangleF(25, 47.353f, 800, 1035.294f), destination); + } + + /// Tiny pages are enlarged to fill the area (and turned when that makes them larger). + [Fact] + public void Fit_enlarges_tiny_pages() + { + var area = new RectangleF(0, 0, 800, 1100); + + RectangleF square = PagePainter.ComputeDestination(new SizeF(1, 1), area, ScaleMode.FitToPage, out bool squareRotated); + RectangleF wide = PagePainter.ComputeDestination(new SizeF(2, 1), area, ScaleMode.FitToPage, out bool wideRotated); + + Assert.False(squareRotated); + AssertRect(new RectangleF(0, 150, 800, 800), square); + Assert.True(wideRotated); + AssertRect(new RectangleF(125, 0, 550, 1100), wide); + } + + /// Huge pages (200 inches, the largest a PDF page normally is) are shrunk to the area. + [Fact] + public void Fit_shrinks_huge_pages() + { + var area = new RectangleF(0, 0, 800, 1100); + + RectangleF square = PagePainter.ComputeDestination(new SizeF(14400, 14400), area, ScaleMode.FitToPage, out bool squareRotated); + RectangleF wide = PagePainter.ComputeDestination(new SizeF(14400, 7200), area, ScaleMode.FitToPage, out bool wideRotated); + + Assert.False(squareRotated); + AssertRect(new RectangleF(0, 150, 800, 800), square); + Assert.True(wideRotated); + AssertRect(new RectangleF(125, 0, 550, 1100), wide); + } + + // ---------------------------------------------------------------- Actual size + + /// + /// Actual size prints the page at its own size: points become hundredths of an inch (x 100 / 72), + /// centred on the area, and what does not fit is cut off evenly on each side. + /// + [Fact] + public void ActualSize_keeps_point_size_without_scaling() + { + RectangleF letter = PagePainter.ComputeDestination(LetterPortrait, PortraitArea, ScaleMode.ActualSize, out bool letterRotated); + RectangleF a4 = PagePainter.ComputeDestination(A4Portrait, PortraitArea, ScaleMode.ActualSize, out bool a4Rotated); + + Assert.False(letterRotated); + AssertRect(new RectangleF(-25, -25, 850, 1100), letter); + Assert.False(a4Rotated); + AssertRect(new RectangleF(-13.389f, -59.646f, 826.778f, 1169.292f), a4); + } + + /// + /// At actual size a landscape page is turned onto a portrait sheet when more of it fits that way + /// (here 800 x 1050 of it instead of 800 x 850). The size stays the page's own. + /// + [Fact] + public void ActualSize_rotates_a_landscape_page_when_more_of_it_fits() + { + RectangleF destination = PagePainter.ComputeDestination(LetterLandscape, PortraitArea, ScaleMode.ActualSize, out bool rotate); + + Assert.True(rotate); + AssertRect(new RectangleF(-25, -25, 850, 1100), destination); + } + + /// The reverse: a portrait page on a landscape sheet at actual size. + [Fact] + public void ActualSize_rotates_a_portrait_page_onto_a_landscape_sheet_when_more_of_it_fits() + { + RectangleF destination = PagePainter.ComputeDestination(LetterPortrait, LandscapeArea, ScaleMode.ActualSize, out bool rotate); + + Assert.True(rotate); + AssertRect(new RectangleF(-25, -25, 1100, 850), destination); + } + + /// A small landscape page fits whole either way, so it is printed as it is, centred. + [Fact] + public void ActualSize_does_not_rotate_a_page_that_fits_either_way() + { + RectangleF destination = PagePainter.ComputeDestination(new SizeF(288, 216), PortraitArea, ScaleMode.ActualSize, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(200, 375, 400, 300), destination); + } + + /// A huge page at actual size is centred and cut off evenly; nothing overflows the arithmetic. + [Fact] + public void ActualSize_huge_page_is_centred_and_cut_off_evenly() + { + RectangleF destination = PagePainter.ComputeDestination(new SizeF(14400, 14400), PortraitArea, ScaleMode.ActualSize, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(-9600, -9475, 20000, 20000), destination); + } + + /// A tiny page at actual size stays tiny and is centred. + [Fact] + public void ActualSize_tiny_page_is_centred() + { + RectangleF destination = PagePainter.ComputeDestination(new SizeF(1, 1), PortraitArea, ScaleMode.ActualSize, out bool rotate); + + Assert.False(rotate); + AssertRect(new RectangleF(399.306f, 524.306f, 1.389f, 1.389f), destination); + } + + // ---------------------------------------------------------------- Mixed sizes and rotated pages + + /// + /// Each page of a mixed document gets its own size, position and turn, and the result for a page + /// does not depend on the pages before it (the same answers in reverse order). + /// + [Fact] + public void Mixed_size_pages_are_each_computed_independently() + { + (SizeF Page, RectangleF Expected, bool Rotated)[] pages = + [ + (A4Portrait, new RectangleF(28.785f, 0, 742.43f, 1050), false), + (LetterLandscape, new RectangleF(0, 7.353f, 800, 1035.294f), true), + (A5Portrait, new RectangleF(30.001f, 0, 739.999f, 1050), false), + (TabloidLandscape, new RectangleF(60.294f, 0, 679.412f, 1050), true), + ]; + + // Enumerable.Reverse by name: with C# 14 spans, array.Reverse() binds to the in-place span method. + foreach (var order in new[] { pages, Enumerable.Reverse(pages).ToArray() }) + { + foreach ((SizeF page, RectangleF expected, bool rotated) in order) + { + RectangleF destination = PagePainter.ComputeDestination(page, PortraitArea, ScaleMode.FitToPage, out bool rotate); + + Assert.Equal(rotated, rotate); + AssertRect(expected, destination); + } + } + } + + /// + /// A page with /Rotate 90 is laid out by its displayed size: the engine reports the A4 page as + /// landscape, so on a portrait A4 sheet it is turned back and fills the sheet. + /// + [Fact] + public void Rotated_page_is_laid_out_by_its_displayed_size() + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(FixtureFactory.CreatePdf(1, rotation: 90), null, out IPdfDocument? document)); + using (document) + { + SizeF displayed = document!.GetPageSizePoints(0); + + // A portrait sheet of exactly the page's stored size (PDFsharp writes A4 as whole points), + // in hundredths of an inch: turned back, the page must fill it exactly. + var portraitSheet = new RectangleF(0, 0, displayed.Height * 100 / 72, displayed.Width * 100 / 72); + + RectangleF destination = PagePainter.ComputeDestination(displayed, portraitSheet, ScaleMode.FitToPage, out bool rotate); + + Assert.True(displayed.Width > displayed.Height, $"Expected a landscape displayed size, got {displayed}."); + Assert.True(rotate); + AssertRect(portraitSheet, destination); + } + } + + // ---------------------------------------------------------------- Bad input + + /// A page without a usable size is refused rather than producing NaN or infinite rectangles. + [Theory] + [InlineData(0f, 792f)] + [InlineData(612f, 0f)] + [InlineData(-612f, 792f)] + [InlineData(float.NaN, 792f)] + [InlineData(float.PositiveInfinity, 792f)] + public void ComputeDestination_rejects_a_page_without_a_usable_size(float width, float height) + { + Assert.Throws(() => PagePainter.ComputeDestination(new SizeF(width, height), PortraitArea, ScaleMode.FitToPage, out _)); + Assert.Throws(() => PagePainter.ComputeDestination(new SizeF(width, height), PortraitArea, ScaleMode.ActualSize, out _)); + } + + /// A printable area without a usable size is refused too. + [Theory] + [InlineData(0f, 1050f)] + [InlineData(800f, -1f)] + [InlineData(float.NaN, 1050f)] + public void ComputeDestination_rejects_a_printable_area_without_a_usable_size(float width, float height) + { + Assert.Throws(() => PagePainter.ComputeDestination(LetterPortrait, new RectangleF(0, 0, width, height), ScaleMode.FitToPage, out _)); + } + + /// A scale mode the painter does not know is refused. + [Fact] + public void ComputeDestination_rejects_an_unknown_scale_mode() + { + Assert.Throws(() => PagePainter.ComputeDestination(LetterPortrait, PortraitArea, (ScaleMode)42, out _)); + } + + // ---------------------------------------------------------------- Paint + + /// + /// Paint hands the engine the destination in device pixels (hundredths of an inch times the + /// resolution / 100) and asks for a counter-clockwise quarter turn for a landscape page on a + /// portrait sheet; the page ends up covering the sheet. + /// + [Theory] + [InlineData(100)] + [InlineData(300)] + public void Paint_sends_device_pixels_and_a_counter_clockwise_turn_for_a_landscape_page_on_a_portrait_sheet(int dpi) + { + var document = new FakePdfDocument(LetterLandscape); + using var sheet = new Sheet(425, 550, dpi); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, dpi); + + RenderCall call = Assert.Single(document.Calls); + Assert.Equal(RenderKind.DeviceContext, call.Kind); + Assert.Equal(new Rectangle(0, 0, 425 * dpi / 100, 550 * dpi / 100), call.DestinationPixels); + Assert.Equal(3, call.QuarterTurns); + Assert.Equal(Color.Black.ToArgb(), sheet.Bitmap.GetPixel(sheet.Bitmap.Width / 2, sheet.Bitmap.Height / 2).ToArgb()); + } + + /// A portrait page on a landscape sheet gets a clockwise quarter turn. + [Fact] + public void Paint_turns_a_portrait_page_clockwise_onto_a_landscape_sheet() + { + var document = new FakePdfDocument(LetterPortrait); + using var sheet = new Sheet(1100, 850, 100); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100); + + RenderCall call = Assert.Single(document.Calls); + Assert.Equal(new Rectangle(0, 0, 1100, 850), call.DestinationPixels); + Assert.Equal(1, call.QuarterTurns); + } + + /// A page that already matches the sheet's orientation is not turned. + [Fact] + public void Paint_does_not_turn_a_page_with_the_sheet_orientation() + { + var document = new FakePdfDocument(A4Portrait); + using var sheet = new Sheet(800, 1050, 100); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100); + + RenderCall call = Assert.Single(document.Calls); + Assert.Equal(0, call.QuarterTurns); + Assert.Equal(new Rectangle(29, 0, 742, 1050), call.DestinationPixels); + } + + /// The real engine draws the page's text onto the sheet through the device context, with no fallback. + [Fact] + public void Paint_draws_the_real_page_through_the_device_context() + { + using FakePdfDocument document = LoadRecorded(FixtureFactory.CreatePdf(1)); + using var sheet = new Sheet(850, 1100, 100); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100); + + Assert.All(document.Calls, call => Assert.Equal(RenderKind.DeviceContext, call.Kind)); + Assert.True(Pixels.CountDark(sheet.Bitmap) > 50, "Expected the page's text on the sheet."); + } + + /// + /// End to end with the real engine: a landscape page printed on a portrait sheet comes out turned. + /// Its line of text, near the top-left of the landscape page, ends up running up the left-hand side + /// of the sheet (a counter-clockwise turn), so the ink is taller than wide and in the lower left. + /// + [Fact] + public void Paint_turns_a_real_landscape_page_onto_a_portrait_sheet() + { + using FakePdfDocument document = LoadRecorded(FixtureFactory.CreatePdf(2, mixedSizes: true)); + using var sheet = new Sheet(850, 1100, 100); + + PagePainter.Paint(document, 1, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100); + + Rectangle ink = Pixels.InkBounds(sheet.Bitmap); + Assert.False(ink.IsEmpty, "Expected the page's text on the sheet."); + Assert.True(ink.Height > ink.Width, $"Expected turned text (taller than wide), got {ink}."); + Assert.True(ink.Right < sheet.Bitmap.Width / 2, $"Expected the text on the left half, got {ink}."); + Assert.True(ink.Top > sheet.Bitmap.Height / 2, $"Expected the text on the lower half, got {ink}."); + } + + /// + /// End to end with the real engine: a portrait page stored with /Rotate 90 displays as landscape; + /// on a portrait sheet it is turned back, so its text reads normally again, across the top-left. + /// + [Fact] + public void Paint_turns_a_real_rotated_page_back_upright_on_a_portrait_sheet() + { + using FakePdfDocument document = LoadRecorded(FixtureFactory.CreatePdf(1, rotation: 90)); + using var sheet = new Sheet(827, 1169, 100); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100); + + Rectangle ink = Pixels.InkBounds(sheet.Bitmap); + Assert.False(ink.IsEmpty, "Expected the page's text on the sheet."); + Assert.True(ink.Width > ink.Height, $"Expected upright text (wider than tall), got {ink}."); + Assert.True(ink.Left < sheet.Bitmap.Width / 4, $"Expected the text to start near the left edge, got {ink}."); + Assert.True(ink.Top < sheet.Bitmap.Height / 4, $"Expected the text near the top, got {ink}."); + } + + /// + /// When the device context refuses the drawing, the real page is rendered to a bitmap instead and + /// lands in the same place on the sheet. + /// + [Fact] + public void Paint_falls_back_to_a_bitmap_of_the_real_page_when_the_device_context_refuses() + { + byte[] pdf = FixtureFactory.CreatePdf(1); + using FakePdfDocument direct = LoadRecorded(pdf); + using FakePdfDocument refusing = LoadRecorded(pdf, refuseDeviceContext: true); + using var directSheet = new Sheet(850, 1100, 100); + using var fallbackSheet = new Sheet(850, 1100, 100); + + PagePainter.Paint(direct, 0, directSheet.Graphics, directSheet.PrintableArea, ScaleMode.FitToPage, 100); + PagePainter.Paint(refusing, 0, fallbackSheet.Graphics, fallbackSheet.PrintableArea, ScaleMode.FitToPage, 100); + + Assert.Equal([RenderKind.DeviceContext, RenderKind.Bitmap], refusing.Calls.Select(call => call.Kind)); + Rectangle expected = Pixels.InkBounds(directSheet.Bitmap); + Rectangle actual = Pixels.InkBounds(fallbackSheet.Bitmap); + Assert.False(actual.IsEmpty, "Expected the page's text on the sheet from the bitmap fallback."); + Assert.InRange(actual.Left, expected.Left - 3, expected.Left + 3); + Assert.InRange(actual.Top, expected.Top - 3, expected.Top + 3); + Assert.InRange(actual.Right, expected.Right - 3, expected.Right + 3); + Assert.InRange(actual.Bottom, expected.Bottom - 3, expected.Bottom + 3); + } + + /// + /// The fallback bitmap matches the printer resolution on paper, capped at 300 dpi to bound memory: + /// the dpi asked of the engine is relative to the page, so a page printed at half its size needs + /// half the dpi for the same dots on paper, and a page enlarged four times needs four times as many. + /// + [Theory] + [InlineData(600, 144f, 300)] + [InlineData(200, 144f, 200)] + [InlineData(600, 288f, 150)] + [InlineData(600, 36f, 1200)] + [InlineData(100, 14400f, 1)] + public void Bitmap_fallback_matches_the_printer_resolution_capped_at_300_dpi(int printerDpi, float pagePoints, int expectedDpi) + { + // A 2 x 2 inch sheet keeps the sheet bitmap small even at 600 dpi. + var document = new FakePdfDocument(new SizeF(pagePoints, pagePoints)) { RefuseDeviceContext = true }; + using var sheet = new Sheet(200, 200, printerDpi); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, printerDpi); + + RenderCall bitmapCall = Assert.Single(document.Calls, call => call.Kind == RenderKind.Bitmap); + Assert.Equal(expectedDpi, bitmapCall.Dpi); + Assert.Equal(Color.Black.ToArgb(), sheet.Bitmap.GetPixel(sheet.Bitmap.Width / 2, sheet.Bitmap.Height / 2).ToArgb()); + } + + /// The bitmap fallback is turned the same way as the device-context path would have been. + [Fact] + public void Bitmap_fallback_is_turned_like_the_device_context_path() + { + var document = new FakePdfDocument(LetterLandscape) { RefuseDeviceContext = true }; + using var sheet = new Sheet(850, 1100, 100); + + PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100); + + Assert.All(document.Calls, call => Assert.Equal(3, call.QuarterTurns)); + } + + /// + /// A page too large for a bitmap (the engine or GDI+ cannot allocate it) is reported as such, with + /// its page number, instead of surfacing as a raw out-of-memory or argument error. + /// + [Theory] + [InlineData(typeof(OutOfMemoryException))] + [InlineData(typeof(ArgumentException))] + public void Bitmap_fallback_too_large_is_reported_as_PageTooLargeException(Type failure) + { + var document = new FakePdfDocument(LetterPortrait, LetterPortrait) + { + RefuseDeviceContext = true, + BitmapFailure = _ => (Exception)Activator.CreateInstance(failure)!, + }; + using var sheet = new Sheet(850, 1100, 100); + + var thrown = Assert.Throws( + () => PagePainter.Paint(document, 1, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100)); + + Assert.Equal(1, thrown.PageIndex); + Assert.IsType(failure, thrown.InnerException); + } + + /// Errors other than a refused device context are not hidden by the fallback. + [Fact] + public void Paint_lets_a_page_size_failure_through() + { + var document = new FakePdfDocument(new SizeF(0, 0)); + using var sheet = new Sheet(850, 1100, 100); + + Assert.Throws(() => PagePainter.Paint(document, 0, sheet.Graphics, sheet.PrintableArea, ScaleMode.FitToPage, 100)); + Assert.Empty(document.Calls); + } + + /// PrepareSheet switches a sheet to hundredths of an inch and returns its printable area in that unit. + [Theory] + [InlineData(100)] + [InlineData(300)] + public void PrepareSheet_reports_the_area_in_hundredths_of_an_inch(int dpi) + { + using var bitmap = new Bitmap(850 * dpi / 100, 1100 * dpi / 100, PixelFormat.Format24bppRgb); + bitmap.SetResolution(dpi, dpi); + using Graphics graphics = Graphics.FromImage(bitmap); + + RectangleF area = PagePainter.PrepareSheet(graphics); + + AssertRect(new RectangleF(0, 0, 850, 1100), area, 0.5f); + } + + private FakePdfDocument LoadRecorded(byte[] pdf, bool refuseDeviceContext = false) + { + Assert.Equal(PdfLoadStatus.Ok, _engine.TryLoad(pdf, null, out IPdfDocument? document)); + return new FakePdfDocument(document!) { RefuseDeviceContext = refuseDeviceContext }; + } + + private static void AssertRect(RectangleF expected, RectangleF actual, float tolerance = Tolerance) + { + Assert.True( + Math.Abs(expected.X - actual.X) <= tolerance + && Math.Abs(expected.Y - actual.Y) <= tolerance + && Math.Abs(expected.Width - actual.Width) <= tolerance + && Math.Abs(expected.Height - actual.Height) <= tolerance, + $"Expected {expected}, got {actual}."); + } + + /// A white in-memory sheet with a Graphics prepared the way a print job prepares a printer page. + private sealed class Sheet : IDisposable + { + public Sheet(int widthHundredths, int heightHundredths, int dpi) + { + // 24 bits per pixel: GDI drawing through the device context leaves 32-bit alpha at zero. + Bitmap = new Bitmap(widthHundredths * dpi / 100, heightHundredths * dpi / 100, PixelFormat.Format24bppRgb); + Bitmap.SetResolution(dpi, dpi); + Graphics = Graphics.FromImage(Bitmap); + Graphics.Clear(Color.White); + PrintableArea = PagePainter.PrepareSheet(Graphics); + } + + public Bitmap Bitmap { get; } + + public Graphics Graphics { get; } + + public RectangleF PrintableArea { get; } + + public void Dispose() + { + Graphics.Dispose(); + Bitmap.Dispose(); + } + } +} diff --git a/tests/PDFStream.NET.Tests/Printing/PrintJobTests.cs b/tests/PDFStream.NET.Tests/Printing/PrintJobTests.cs new file mode 100644 index 0000000..875e0d3 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/PrintJobTests.cs @@ -0,0 +1,460 @@ +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Printing; +using PDFStream.NET.Engine; +using PDFStream.NET.Printing; +using PDFStream.NET.Tests.Fixtures; +using Xunit; + +namespace PDFStream.NET.Tests.Printing; + +/// +/// Tests : the page loop, cancellation, software copies, the bitmap fallback and +/// how printer and page failures become statuses. No test uses a printer: the jobs run through +/// , which prints onto bitmaps that the tests inspect. +/// +public sealed class PrintJobTests +{ + private static readonly TimeSpan NoHang = TimeSpan.FromSeconds(30); + + /// + /// Pins the test harness itself: a print document with a printer that does not exist reaches its + /// page events through the fake controller, so every other test here really runs the print loop. + /// + [Fact] + public void Test_harness_prints_two_pages_without_any_printer() + { + using var controller = new FakePrintController(); + using var document = new PrintDocument { PrinterSettings = TestPrinters.Settings(), PrintController = controller }; + int pages = 0; + document.PrintPage += (_, e) => + { + pages++; + e.Graphics!.FillRectangle(Brushes.Black, 0, 0, 10, 10); + e.HasMorePages = pages < 2; + }; + + document.Print(); + + Assert.Equal(2, pages); + Assert.Equal(2, controller.Pages.Count); + Assert.False(controller.EndedWithCancel); + Assert.Equal(Color.Black.ToArgb(), controller.Pages[1].GetPixel(2, 2).ToArgb()); + } + + /// + /// A real three-page PDF goes through the whole job: Ok, three pages counted, three sheets, and + /// each sheet carries the page's ink (the status alone is not trusted). + /// + [Fact] + public void Prints_every_page_of_a_real_pdf_with_ink_on_each_sheet() + { + Assert.Equal(PdfLoadStatus.Ok, new PdfiumEngine().TryLoad(FixtureFactory.CreatePdf(3), null, out IPdfDocument? document)); + using (document) + using (var controller = new FakePrintController()) + { + PrintResult result = PrintJob.Run(document!, [0, 1, 2], TestPrinters.Settings(), "Three pages", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.Equal(3, result.PagesPrinted); + Assert.Equal(3, controller.Pages.Count); + Assert.All(controller.Pages, sheet => Assert.True(Pixels.CountDark(sheet) > 50, "Expected the page's text on every sheet.")); + Assert.False(controller.EndedWithCancel); + } + } + + /// The pages print in the order given, repeats included, and the queue shows the document name. + [Fact] + public void Pages_print_in_the_order_given_under_the_document_name() + { + var document = FakePdfDocument.Letter(3); + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(document, [2, 0, 2], TestPrinters.Settings(), "Packing slip 42", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.Equal(3, result.PagesPrinted); + Assert.Equal([2, 0, 2], document.Calls.Select(call => call.PageIndex)); + Assert.Equal("Packing slip 42", controller.DocumentNameAtStart); + } + + /// + /// Cancelling between pages stops the job: the result is Cancelled and counts the pages already + /// sent. The job ends normally rather than being aborted, so the pages counted really print. + /// + [Fact] + public void Cancelled_token_returns_Cancelled_with_pages_already_sent() + { + using var cancellation = new CancellationTokenSource(); + + // The token fires while the second page is being drawn, as a caller cancelling mid-job would. + var document = new FakePdfDocument(Enumerable.Repeat(new SizeF(612, 792), 4).ToArray()) + { + BeforeRender = pageIndex => + { + if (pageIndex == 1) + { + cancellation.Cancel(); + } + }, + }; + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(document, [0, 1, 2, 3], TestPrinters.Settings(), "Cancel me", ScaleMode.FitToPage, cancellation.Token, controller); + + Assert.Equal(PrintStatus.Cancelled, result.Status); + Assert.Equal(Messages.Cancelled(), result.Message); + Assert.Equal(2, result.PagesPrinted); + Assert.Equal(2, controller.Pages.Count); + Assert.All(controller.Pages, sheet => Assert.True(Pixels.CountDark(sheet) > 0, "Every sent page must carry its drawing; no blank sheet may be started.")); + Assert.False(controller.EndedWithCancel); + } + + /// A token cancelled before the job starts prints nothing and opens no job at all. + [Fact] + public void Token_cancelled_before_the_start_prints_nothing() + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(2), [0, 1], TestPrinters.Settings(), "Never", ScaleMode.FitToPage, cancellation.Token, controller); + + Assert.Equal(PrintStatus.Cancelled, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(0, controller.StartPrintCalls); + } + + /// + /// A token that fires after the job opened but before the first page is drawn aborts the job, so + /// not even a blank sheet comes out. + /// + [Fact] + public void Token_cancelled_as_the_job_opens_aborts_it_with_nothing_printed() + { + using var cancellation = new CancellationTokenSource(); + using var controller = new FakePrintController { OnStartPrintCallback = cancellation.Cancel }; + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(2), [0, 1], TestPrinters.Settings(), "Abort", ScaleMode.FitToPage, cancellation.Token, controller); + + Assert.Equal(PrintStatus.Cancelled, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.True(controller.EndedWithCancel); + } + + /// + /// When the printer driver refuses device-context drawing, the page is rendered as a bitmap and + /// drawn onto the sheet instead, and the job still succeeds with ink where the page belongs. + /// + [Fact] + public void Driver_refusing_device_context_rendering_falls_back_to_bitmap() + { + var document = new FakePdfDocument(new SizeF(612, 792), new SizeF(612, 792)) { RefuseDeviceContext = true }; + using var controller = new FakePrintController(dpi: 100); + + PrintResult result = PrintJob.Run(document, [0, 1], TestPrinters.Settings(), "Fallback", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.Equal(2, result.PagesPrinted); + Assert.Equal( + [RenderKind.DeviceContext, RenderKind.Bitmap, RenderKind.DeviceContext, RenderKind.Bitmap], + document.Calls.Select(call => call.Kind)); + + // Letter on a Letter sheet fills it, so the bitmap is asked for at the sheet's 100 dpi. + Assert.All(document.Calls.Where(call => call.Kind == RenderKind.Bitmap), call => Assert.Equal(100, call.Dpi)); + Assert.All(controller.Pages, sheet => Assert.Equal(Color.Black.ToArgb(), sheet.GetPixel(sheet.Width / 2, sheet.Height / 2).ToArgb())); + } + + /// + /// A real PDF printed through the bitmap fallback still carries its text on every sheet. + /// + [Fact] + public void Bitmap_fallback_of_a_real_pdf_puts_ink_on_every_sheet() + { + Assert.Equal(PdfLoadStatus.Ok, new PdfiumEngine().TryLoad(FixtureFactory.CreatePdf(2), null, out IPdfDocument? real)); + using var document = new FakePdfDocument(real!) { RefuseDeviceContext = true }; + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(document, [0, 1], TestPrinters.Settings(), "Fallback", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.All(controller.Pages, sheet => Assert.True(Pixels.CountDark(sheet) > 50, "Expected the page's text on every sheet.")); + } + + /// + /// A printer that cannot be opened when the job starts (deleted, unreachable, refused) makes the job fail fast with + /// PrinterUnavailable and the standard message, instead of throwing or hanging. + /// + [Fact] + public async Task Printer_offline_returns_PrinterUnavailable_without_hanging() + { + PrinterSettings settings = TestPrinters.Settings(); + using var controller = new FakePrintController { ThrowOnStartPrint = new InvalidPrinterException(settings) }; + + PrintResult result = await Task.Run( + () => PrintJob.Run(FakePdfDocument.Letter(2), [0, 1], settings, "Offline", ScaleMode.FitToPage, CancellationToken.None, controller)) + .WaitAsync(NoHang, TestContext.Current.CancellationToken); + + Assert.Equal(PrintStatus.PrinterUnavailable, result.Status); + Assert.Equal(Messages.PrinterUnavailable(), result.Message); + Assert.Equal(0, result.PagesPrinted); + Assert.Equal(1, controller.StartPrintCalls); + } + + /// A print system error when the job opens (StartDoc failing) is PrinterUnavailable too. + [Fact] + public void Print_system_error_at_the_start_returns_PrinterUnavailable() + { + using var controller = new FakePrintController { ThrowOnStartPrint = new Win32Exception(1801) }; + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(1), [0], TestPrinters.Settings(), "Refused", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.PrinterUnavailable, result.Status); + Assert.Equal(0, result.PagesPrinted); + } + + /// + /// A printer that fails part-way through reports PrinterUnavailable and counts no pages: the job + /// ends aborted, and the print system withdraws an aborted job, so the pages drawn before the + /// failure normally never come out. + /// + [Fact] + public void Printer_failing_mid_job_returns_PrinterUnavailable_with_no_pages_counted() + { + using var controller = new FakePrintController { ThrowOnStartPage = new Win32Exception(), ThrowOnStartPageNumber = 3 }; + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(4), [0, 1, 2, 3], TestPrinters.Settings(), "Jam", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.PrinterUnavailable, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.True(controller.EndedWithCancel); + } + + /// + /// A cancel mid-job ends the job normally, but if closing it then fails, the pages may never + /// print: that is a failure with no pages counted, not a Cancelled result claiming two pages. + /// + [Fact] + public void Cancelled_job_that_then_fails_to_close_is_a_failure_with_no_pages_counted() + { + using var cancellation = new CancellationTokenSource(); + var document = new FakePdfDocument(Enumerable.Repeat(new SizeF(612, 792), 4).ToArray()) + { + BeforeRender = pageIndex => + { + if (pageIndex == 1) + { + cancellation.Cancel(); + } + }, + }; + using var controller = new FakePrintController { ThrowOnEndPrint = new Win32Exception() }; + + PrintResult result = PrintJob.Run(document, [0, 1, 2, 3], TestPrinters.Settings(), "Cancel then fail", ScaleMode.FitToPage, cancellation.Token, controller); + + Assert.Equal(PrintStatus.PrinterUnavailable, result.Status); + Assert.Equal(0, result.PagesPrinted); + Assert.False(controller.EndedWithCancel); + } + + /// Any other exception from the print system becomes UnknownError, with its text for whoever looks after the program. + [Fact] + public void Unexpected_print_system_exception_becomes_UnknownError_with_its_details() + { + using var controller = new FakePrintController { ThrowOnStartPrint = new InvalidOperationException("Spooler said no in an unexpected way.") }; + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(1), [0], TestPrinters.Settings(), "Odd", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.UnknownError, result.Status); + Assert.StartsWith(Messages.UnknownError(), result.Message); + Assert.Contains("Spooler said no in an unexpected way.", result.Message); + } + + /// + /// The print system cancelling the job by itself (for example a Save As box closed without + /// saving) is reported as Cancelled, never as Ok, because no page was sent. + /// + [Fact] + public void Print_system_cancelling_the_job_is_Cancelled_not_Ok() + { + using var controller = new FakePrintController { CancelOnStartPrint = true }; + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(2), [0, 1], TestPrinters.Settings(), "Closed", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Cancelled, result.Status); + Assert.Equal(0, result.PagesPrinted); + } + + /// + /// A page that cannot be drawn either way stops the job with UnknownError naming the page. The job + /// is aborted so no half-drawn sheet is printed, and since an aborted job is withdrawn from the + /// queue, no pages are counted. + /// + [Fact] + public void Page_that_cannot_be_drawn_stops_the_job_with_a_message_naming_it() + { + var document = new FakePdfDocument(Enumerable.Repeat(new SizeF(612, 792), 4).ToArray()) + { + RefuseDeviceContext = true, + BitmapFailure = pageIndex => pageIndex == 2 ? new InvalidOperationException("PDFium could not load page 3; the page may be damaged.") : null, + }; + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(document, [0, 1, 2, 3], TestPrinters.Settings(), "Damaged", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.UnknownError, result.Status); + Assert.Equal(Messages.PageFailed(3, "PDFium could not load page 3; the page may be damaged."), result.Message); + Assert.Equal(0, result.PagesPrinted); + Assert.True(controller.EndedWithCancel); + } + + /// + /// A page too large for the bitmap fallback ends as UnknownError with a plain message about the + /// page size, not a crash (the fallback may run out of memory, notably in 32-bit processes). + /// + [Theory] + [InlineData(typeof(OutOfMemoryException))] + [InlineData(typeof(ArgumentException))] + public void Page_too_large_for_the_bitmap_fallback_returns_UnknownError_with_a_plain_message(Type failure) + { + var document = new FakePdfDocument(new SizeF(612, 792), new SizeF(14400, 14400)) + { + RefuseDeviceContext = true, + BitmapFailure = pageIndex => pageIndex == 1 ? (Exception)Activator.CreateInstance(failure)! : null, + }; + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(document, [0, 1], TestPrinters.Settings(), "Poster", ScaleMode.ActualSize, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.UnknownError, result.Status); + Assert.Equal(Messages.PageTooLarge(2), result.Message); + Assert.Equal(0, result.PagesPrinted); + Assert.True(controller.EndedWithCancel); + } + + /// + /// When the driver cannot make the copies itself (it reports a maximum below the request, as + /// Microsoft Print to PDF does with 1), the whole document is repeated in software, in order, and + /// the driver is asked for one copy only, so the result is three copies and not nine. The + /// caller's settings are left as they were. + /// + [Fact] + public void Copies_beyond_the_driver_maximum_repeat_the_document_in_software() + { + PrinterSettings settings = TestPrinters.Settings(copies: 3); + Assert.Equal(1, settings.MaximumCopies); + var document = FakePdfDocument.Letter(2); + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(document, [0, 1], settings, "Three copies", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Ok, result.Status); + Assert.Equal(6, result.PagesPrinted); + Assert.Equal(6, controller.Pages.Count); + Assert.Equal([0, 1, 0, 1, 0, 1], document.Calls.Select(call => call.PageIndex)); + Assert.Equal((short)1, controller.CopiesAtStart); + Assert.Equal(1, controller.StartPrintCalls); + Assert.Equal(3, settings.Copies); + } + + /// + /// The copy plan: the driver makes the copies when it can; otherwise the document is repeated in + /// software and the driver gets one copy. Never both, which would multiply the copies. + /// + [Theory] + [InlineData(1, 1, 1, 1)] + [InlineData(1, 999, 1, 1)] + [InlineData(3, 999, 1, 3)] + [InlineData(3, 3, 1, 3)] + [InlineData(3, 2, 3, 1)] + [InlineData(3, 1, 3, 1)] + [InlineData(3, 0, 3, 1)] + [InlineData(3, -1, 3, 1)] + [InlineData(32767, 1, 32767, 1)] + public void Copy_plan_lets_the_driver_copy_only_when_it_can(short requested, int driverMaximum, int expectedRepetitions, short expectedDriverCopies) + { + (int repetitions, short driverCopies) = PrintJob.PlanCopies(requested, driverMaximum); + + Assert.Equal(expectedRepetitions, repetitions); + Assert.Equal(expectedDriverCopies, driverCopies); + Assert.Equal(Math.Max((int)requested, 1), repetitions * driverCopies); + } + + /// An empty page list starts no job (a job with no pages would still print a blank sheet). + [Fact] + public void Empty_page_list_prints_nothing_and_returns_InvalidPageRange() + { + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(2), [], TestPrinters.Settings(), "Empty", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.InvalidPageRange, result.Status); + Assert.Equal(0, controller.StartPrintCalls); + } + + /// A page index the document does not have is PageNotFound, before any job starts. + [Theory] + [InlineData(-1)] + [InlineData(2)] + public void Page_outside_the_document_returns_PageNotFound_before_printing(int badPage) + { + using var controller = new FakePrintController(); + + PrintResult result = PrintJob.Run(FakePdfDocument.Letter(2), [0, badPage], TestPrinters.Settings(), "Bad page", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.PageNotFound, result.Status); + Assert.Equal(0, controller.StartPrintCalls); + } + + /// + /// In a mixed document each page is laid out on its own: the landscape page in the middle is + /// turned and fitted, and the portrait pages around it are not affected by it. + /// + [Fact] + public void Mixed_size_document_lays_out_each_page_on_its_own() + { + var document = new FakePdfDocument(new SizeF(595.28f, 841.89f), new SizeF(792, 612), new SizeF(595.28f, 841.89f)); + using var controller = new FakePrintController(850, 1100, 100); + + PrintResult result = PrintJob.Run(document, [0, 1, 2], TestPrinters.Settings(), "Mixed", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.Ok, result.Status); + RenderCall[] calls = document.Calls.ToArray(); + Assert.Equal(3, calls.Length); + + // A4 on Letter: limited by the height, centred across. Letter landscape: turned to fill the sheet. + Assert.Equal(new Rectangle(36, 0, 778, 1100), calls[0].DestinationPixels); + Assert.Equal(0, calls[0].QuarterTurns); + Assert.Equal(new Rectangle(0, 0, 850, 1100), calls[1].DestinationPixels); + Assert.Equal(3, calls[1].QuarterTurns); + Assert.Equal(calls[0].DestinationPixels, calls[2].DestinationPixels); + Assert.Equal(0, calls[2].QuarterTurns); + } + + /// Missing arguments are a programming error inside the library, reported as UnknownError rather than thrown. + [Fact] + public void Missing_arguments_return_UnknownError_instead_of_throwing() + { + using var controller = new FakePrintController(); + + PrintResult noDocument = PrintJob.Run(null!, [0], TestPrinters.Settings(), "x", ScaleMode.FitToPage, CancellationToken.None, controller); + PrintResult noPages = PrintJob.Run(FakePdfDocument.Letter(1), null!, TestPrinters.Settings(), "x", ScaleMode.FitToPage, CancellationToken.None, controller); + PrintResult noSettings = PrintJob.Run(FakePdfDocument.Letter(1), [0], null!, "x", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintStatus.UnknownError, noDocument.Status); + Assert.Equal(PrintStatus.UnknownError, noPages.Status); + Assert.Equal(PrintStatus.UnknownError, noSettings.Status); + Assert.Equal(0, controller.StartPrintCalls); + } + + /// A blank document name is replaced by a readable default for the print queue. + [Fact] + public void Blank_document_name_gets_a_default_queue_name() + { + using var controller = new FakePrintController(); + + PrintJob.Run(FakePdfDocument.Letter(1), [0], TestPrinters.Settings(), " ", ScaleMode.FitToPage, CancellationToken.None, controller); + + Assert.Equal(PrintJob.DefaultDocumentName, controller.DocumentNameAtStart); + } +} diff --git a/tests/PDFStream.NET.Tests/Printing/PrinterStatusCheckTests.cs b/tests/PDFStream.NET.Tests/Printing/PrinterStatusCheckTests.cs new file mode 100644 index 0000000..a36197c --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/PrinterStatusCheckTests.cs @@ -0,0 +1,201 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using PDFStream.NET.Printing; +using Xunit; + +namespace PDFStream.NET.Tests.Printing; + +/// +/// Tests the pre-flight printer status check: a queue that is paused, set to "Use printer offline", +/// not available or being deleted, or that cannot be opened (Print Spooler stopped included), is refused +/// with a message naming the cause. Offline reports, paper, toner and similar problems are not refused, +/// and a status that cannot be read never blocks printing. A fake probe supplies every state; two tests +/// use the real system. +/// +public sealed class PrinterStatusCheckTests +{ + private const string Printer = "Front Desk Laser"; + private const string PdfPrinter = "Microsoft Print to PDF"; + + /// Each blocking status bit (and the work-offline attribute) is PrinterUnavailable with its own message. + [Theory] + [InlineData(0x00000001u, 0u, "paused")] + [InlineData(0x00001000u, 0u, "not-available")] + [InlineData(0x00000004u, 0u, "pending-deletion")] + [InlineData(0u, 0x00000400u, "work-offline")] + public void Blocking_queue_state_is_PrinterUnavailable_naming_the_cause(uint status, uint attributes, string cause) + { + var probe = FakeStatusProbe.Reading(status, attributes); + + PrintStatus result = PrinterStatusCheck.Check(probe, Printer, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, result); + Assert.Equal(ExpectedMessage(cause), message); + Assert.Contains(Printer, message); + Assert.Equal([Printer], probe.Asked); + } + + /// + /// States a person fixes at the printer (paper, jams, toner, doors, intervention), offline reports, + /// and busy or informational states do not block: the job queues and prints once the printer is ready. + /// + [Theory] + + // Offline and server offline do not block. Network printers often report OFFLINE through SNMP + // status while they print perfectly well, and a printer that really is switched off simply queues + // the job until it comes back, so refusing would break working printing. + [InlineData(0x00000080u)] // offline + [InlineData(0x02000000u)] // server offline + [InlineData(0x00000002u)] // error + [InlineData(0x00000008u)] // paper jam + [InlineData(0x00000010u)] // paper out + [InlineData(0x00000020u)] // manual feed + [InlineData(0x00000040u)] // paper problem + [InlineData(0x00000100u)] // I/O active + [InlineData(0x00000200u)] // busy + [InlineData(0x00000400u)] // printing + [InlineData(0x00000800u)] // output bin full + [InlineData(0x00002000u)] // waiting + [InlineData(0x00004000u)] // processing + [InlineData(0x00008000u)] // initializing + [InlineData(0x00010000u)] // warming up + [InlineData(0x00020000u)] // toner low + [InlineData(0x00040000u)] // no toner + [InlineData(0x00080000u)] // page punt + [InlineData(0x00100000u)] // user intervention + [InlineData(0x00200000u)] // out of memory + [InlineData(0x00400000u)] // door open + [InlineData(0x00800000u)] // server unknown + [InlineData(0x01000000u)] // power save + [InlineData(0x04000000u)] // driver update needed + public void Non_blocking_status_bit_does_not_block(uint status) + { + PrintStatus result = PrinterStatusCheck.Check(FakeStatusProbe.Reading(status), Printer, out string message); + + Assert.Equal(PrintStatus.Ok, result); + Assert.Equal(Messages.Ok(), message); + } + + /// All the non-blocking bits at once, and every attribute except work offline, still do not block. + [Fact] + public void All_non_blocking_bits_together_do_not_block() + { + const uint blocking = 0x00000001u | 0x00000004u | 0x00001000u; + const uint workOffline = 0x00000400u; + + PrintStatus result = PrinterStatusCheck.Check(FakeStatusProbe.Reading(~blocking, ~workOffline), Printer, out _); + + Assert.Equal(PrintStatus.Ok, result); + } + + /// A blocking bit wins over any non-blocking ones set beside it. + [Fact] + public void Blocking_bit_with_paper_out_beside_it_still_blocks() + { + PrintStatus result = PrinterStatusCheck.Check(FakeStatusProbe.Reading(0x00000001u | 0x00000010u), Printer, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, result); + Assert.Equal(Messages.PrinterPaused(Printer), message); + } + + /// A probe that throws never blocks printing: an unreadable status is treated as fine. + [Theory] + [InlineData(typeof(Win32Exception))] + [InlineData(typeof(InvalidOperationException))] + [InlineData(typeof(DllNotFoundException))] + public void Probe_that_throws_does_not_block(Type failure) + { + var probe = new FakeStatusProbe(PrinterStatusReadOutcome.Read, status: 0x00000001u) { Throws = (Exception)Activator.CreateInstance(failure)! }; + + PrintStatus result = PrinterStatusCheck.Check(probe, Printer, out string message); + + Assert.Equal(PrintStatus.Ok, result); + Assert.Equal(Messages.Ok(), message); + } + + /// A queue that opened but whose status could not be read never blocks printing, whatever values came with it. + [Fact] + public void Unreadable_status_does_not_block() + { + PrintStatus result = PrinterStatusCheck.Check(new FakeStatusProbe(PrinterStatusReadOutcome.Unreadable, status: 0x00000001u), Printer, out _); + + Assert.Equal(PrintStatus.Ok, result); + } + + /// A stopped Print Spooler is PrinterUnavailable with a message that names the Print Spooler service. + [Fact] + public void Stopped_print_spooler_is_PrinterUnavailable_naming_the_spooler() + { + PrintStatus result = PrinterStatusCheck.Check(new FakeStatusProbe(PrinterStatusReadOutcome.SpoolerNotRunning), Printer, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, result); + Assert.Equal(Messages.SpoolerNotRunning(), message); + Assert.Contains("Print Spooler", message); + } + + /// + /// A printer queue that cannot be opened is PrinterUnavailable. The check only runs for a printer + /// found in the installed list, so a failed open means the installed queue itself is unusable. + /// + [Fact] + public void Printer_queue_that_cannot_be_opened_is_PrinterUnavailable() + { + PrintStatus result = PrinterStatusCheck.Check(new FakeStatusProbe(PrinterStatusReadOutcome.CannotOpen), Printer, out string message); + + Assert.Equal(PrintStatus.PrinterUnavailable, result); + Assert.Equal(Messages.PrinterCannotBeOpened(Printer), message); + Assert.Contains(Printer, message); + Assert.Contains("Print Spooler", message); + } + + /// The real probe reads Microsoft Print to PDF, which is a ready queue: not blocked. + [Fact] + public void Real_probe_reads_Microsoft_Print_to_PDF_as_not_blocked() + { + bool installed = SystemPrinterCatalog.Instance.GetInstalledPrinterNames().Contains(PdfPrinter, StringComparer.OrdinalIgnoreCase); + Assert.SkipUnless(installed, $"The '{PdfPrinter}' printer is not installed on this machine, so the real status probe cannot be checked."); + + PrinterStatusReadOutcome outcome = WinspoolPrinterStatusProbe.Instance.TryRead(PdfPrinter, out uint status, out uint attributes); + PrintStatus result = PrinterStatusCheck.Check(WinspoolPrinterStatusProbe.Instance, PdfPrinter, out string message); + + Assert.Equal(PrinterStatusReadOutcome.Read, outcome); + Assert.Equal(PrintStatus.Ok, result); + Assert.Equal(Messages.Ok(), message); + + // A local queue always carries the LOCAL attribute (0x40), which proves the attributes field + // was read from the right place in the structure, on 32-bit and 64-bit alike. + Assert.True((attributes & 0x40u) != 0, $"Expected the LOCAL attribute, got status 0x{status:X8}, attributes 0x{attributes:X8}."); + } + + /// The real probe on a printer that does not exist reports that it cannot be opened, instead of throwing. + [Fact] + public void Real_probe_on_an_unknown_printer_reports_it_cannot_be_opened() + { + PrinterStatusReadOutcome outcome = WinspoolPrinterStatusProbe.Instance.TryRead("No such printer " + Guid.NewGuid().ToString("N"), out _, out _); + + Assert.Equal(PrinterStatusReadOutcome.CannotOpen, outcome); + } + + /// + /// PRINTER_INFO_2 has 13 pointers before its DWORDs, so its layout differs between 32-bit and + /// 64-bit processes; the managed copy must match the native one in the running process. + /// + [Fact] + public void Printer_info_2_layout_matches_the_native_structure_for_this_process() + { + int pointers = 13 * IntPtr.Size; + + Assert.Equal(pointers + (8 * sizeof(uint)), Marshal.SizeOf()); + Assert.Equal(pointers, (int)Marshal.OffsetOf(nameof(WinspoolPrinterStatusProbe.PrinterInfo2.Attributes))); + Assert.Equal(pointers + (5 * sizeof(uint)), (int)Marshal.OffsetOf(nameof(WinspoolPrinterStatusProbe.PrinterInfo2.Status))); + } + + private static string ExpectedMessage(string cause) => cause switch + { + "paused" => Messages.PrinterPaused(Printer), + "not-available" => Messages.PrinterNotAvailable(Printer), + "pending-deletion" => Messages.PrinterPendingDeletion(Printer), + "work-offline" => Messages.PrinterWorkOffline(Printer), + _ => throw new ArgumentOutOfRangeException(nameof(cause), cause, null), + }; +} diff --git a/tests/PDFStream.NET.Tests/Printing/TestPrinters.cs b/tests/PDFStream.NET.Tests/Printing/TestPrinters.cs new file mode 100644 index 0000000..d57a212 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Printing/TestPrinters.cs @@ -0,0 +1,45 @@ +using System.Drawing.Printing; +using Xunit; + +namespace PDFStream.NET.Tests.Printing; + +/// Printer settings for tests that must not touch any real printer. +internal static class TestPrinters +{ + /// The installed printer the tests that need real printer settings use. It is never printed to. + public const string MicrosoftPrintToPdf = "Microsoft Print to PDF"; + + /// + /// Skips the calling test, with the reason shown in the test output, when "Microsoft Print to PDF" + /// is not installed. The facade validates the printer against the real print system before it runs + /// the job, so a test that reaches the job needs one real printer name (the job itself is faked). + /// + public static void RequireMicrosoftPrintToPdf() + { + bool installed = PDFStream.NET.Printing.SystemPrinterCatalog.Instance.GetInstalledPrinterNames() + .Contains(MicrosoftPrintToPdf, StringComparer.OrdinalIgnoreCase); + Assert.SkipUnless(installed, $"The '{MicrosoftPrintToPdf}' printer is not installed on this machine, so a print call cannot get as far as its job."); + } + + /// + /// Settings for a printer that is not installed, usable with . + /// + /// + /// The paper size and orientation are set explicitly because System.Drawing otherwise asks the + /// printer driver for them when it builds each page's event arguments, and there is no driver. + /// For such a printer reports 1, System.Drawing's + /// fallback when the driver cannot be asked. + /// + /// The copy count the caller asked for. + public static PrinterSettings Settings(short copies = 1) + { + var settings = new PrinterSettings + { + PrinterName = "PDFStream.NET test printer (not installed) " + Guid.NewGuid().ToString("N"), + Copies = copies, + }; + settings.DefaultPageSettings.Landscape = false; + settings.DefaultPageSettings.PaperSize = new PaperSize("Test sheet", 850, 1100); + return settings; + } +} diff --git a/tests/PDFStream.NET.Tests/Sample/FakeConsole.cs b/tests/PDFStream.NET.Tests/Sample/FakeConsole.cs new file mode 100644 index 0000000..8bb7277 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Sample/FakeConsole.cs @@ -0,0 +1,63 @@ +using PDFStream.NET.TestPrint; + +namespace PDFStream.NET.Tests.Sample; + +/// A console that records what was shown and counts key waits, so a test never blocks. +internal sealed class FakeConsole : IConsoleIo +{ + private readonly List _lines = new(); + + /// How many times the program asked for a key press. + public int KeyWaits { get; private set; } + + /// Everything shown so far, one line per row. + public string Text => string.Join(Environment.NewLine, _lines); + + /// + public void WriteLine(string text = "") => _lines.Add(text); + + /// + public void WaitForKey() => KeyWaits++; +} + +/// A scratch folder standing in for "the folder of the exe"; deleted when the test ends. +internal sealed class ProgramFolder : IDisposable +{ + /// Creates a new empty folder under the system temp folder. + public ProgramFolder() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "pdfstream.net-sample-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path); + } + + /// The folder path. + public string Path { get; } + + /// The settings file inside the folder. + public string SettingsPath => System.IO.Path.Combine(Path, SettingsFile.FileName); + + /// Writes a settings file with the given text. + public void WriteSettings(string json) => File.WriteAllText(SettingsPath, json); + + /// Creates a placeholder PDF (the print step is replaced in tests, so its content is never read). + public string CreateFile(string relativePath) + { + string full = System.IO.Path.Combine(Path, relativePath); + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(full)!); + File.WriteAllText(full, "%PDF-1.4 placeholder"); + return full; + } + + /// + public void Dispose() + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + // A leftover temp folder is harmless; never fail a test because of cleanup. + } + } +} diff --git a/tests/PDFStream.NET.Tests/Sample/TestPrintTests.cs b/tests/PDFStream.NET.Tests/Sample/TestPrintTests.cs new file mode 100644 index 0000000..5e8c8a2 --- /dev/null +++ b/tests/PDFStream.NET.Tests/Sample/TestPrintTests.cs @@ -0,0 +1,380 @@ +using System.Text.Json; +using PDFStream.NET.TestPrint; +using Xunit; + +namespace PDFStream.NET.Tests.Sample; + +/// Tests of the test-print sample's logic: settings file, dry run and plain-language messages. +public class TestPrintTests +{ + private static readonly string[] Printers = { "Microsoft Print to PDF", "Office Laser" }; + + /// Counts print calls and returns a canned result. + private sealed class PrintSpy + { + public int Calls { get; private set; } + public string? Path { get; private set; } + public PrintOptions? Options { get; private set; } + public PrintResult Result { get; init; } = PrintResult.Success(2); + + public PrintResult Print(string path, PrintOptions options) + { + Calls++; + Path = path; + Options = options; + return Result; + } + } + + private static TestPrintApp NewApp(FakeConsole io, ProgramFolder folder, PrintSpy spy, string[]? printers = null) => + new(io, folder.Path, () => printers ?? Printers, spy.Print); + + private static string Settings(string printer = "Office Laser", string pdf = "test.pdf", string extra = "", bool really = false) => + $$"""{ "PrinterName": "{{printer}}", "PdfFile": "{{pdf}}", {{extra}} "ReallyPrint": {{(really ? "true" : "false")}} }"""; + + [Fact] + public void Settings_file_is_created_with_comments_when_missing() + { + using ProgramFolder folder = new(); + + SettingsLoadResult result = SettingsFile.Load(folder.Path); + + Assert.Equal(SettingsOutcome.Created, result.Outcome); + Assert.True(File.Exists(folder.SettingsPath)); + Assert.Contains(folder.SettingsPath, result.Message); + + string[] lines = File.ReadAllLines(folder.SettingsPath); + foreach (string key in new[] { "PrinterName", "PdfFile", "Copies", "Pages", "OutputFile", "ReallyPrint" }) + { + int keyLine = Array.FindIndex(lines, l => l.TrimStart().StartsWith($"\"{key}\":", StringComparison.Ordinal)); + Assert.True(keyLine >= 0, $"Key {key} is missing from the starter file."); + + // The explanation sits above its key and starts with the key name. + int commentLine = Array.FindIndex(lines, l => l.TrimStart().StartsWith($"// {key}:", StringComparison.Ordinal)); + Assert.True(commentLine >= 0 && commentLine < keyLine, $"Key {key} has no comment line above it."); + } + + // The file it created reads back with the safe defaults. + TestPrintSettings back = SettingsFile.Parse(File.ReadAllText(folder.SettingsPath)); + Assert.Equal(string.Empty, back.PrinterName); + Assert.Equal("test.pdf", back.PdfFile); + Assert.Equal(1, back.Copies); + Assert.Equal(string.Empty, back.Pages); + Assert.Equal(string.Empty, back.OutputFile); + Assert.False(back.ReallyPrint); + + // A second load reads the file instead of creating it again. + Assert.Equal(SettingsOutcome.Loaded, SettingsFile.Load(folder.Path).Outcome); + } + + [Fact] + public void First_run_tells_the_user_where_the_file_is_lists_printers_and_waits() + { + using ProgramFolder folder = new(); + FakeConsole io = new(); + PrintSpy spy = new(); + + int exit = NewApp(io, folder, spy).RunAndWait(); + + Assert.Equal(0, exit); + Assert.Equal(0, spy.Calls); + Assert.Equal(1, io.KeyWaits); + Assert.Contains(folder.SettingsPath, io.Text); + Assert.Contains("Office Laser", io.Text); + Assert.Contains("double-click", io.Text); + } + + [Fact] + public void Settings_with_comments_and_trailing_commas_parse() + { + TestPrintSettings s = SettingsFile.Parse(""" + { + // which printer + "printername": "Office Laser", // keys may use any capitalisation + "PdfFile": "a.pdf", + "Copies": 3, + "Pages": "1-2", + "OutputFile": null, + "ReallyPrint": true, + } + """); + + Assert.Equal("Office Laser", s.PrinterName); + Assert.Equal("a.pdf", s.PdfFile); + Assert.Equal(3, s.Copies); + Assert.Equal("1-2", s.Pages); + Assert.Equal(string.Empty, s.OutputFile); + Assert.True(s.ReallyPrint); + } + + [Theory] + [InlineData("{ \"PrinterName\": ")] + [InlineData("not json at all")] + [InlineData("{ \"Copies\": \"two\" }")] + [InlineData("{ \"PdfFile\": \"C:\\Docs\\a.pdf\" }")] + [InlineData("")] + public void Bad_json_gives_plain_message_not_a_stack_trace(string content) + { + using ProgramFolder folder = new(); + folder.WriteSettings(content); + FakeConsole io = new(); + + SettingsLoadResult result = SettingsFile.Load(folder.Path); + int exit = NewApp(io, folder, new PrintSpy()).RunAndWait(); + + Assert.Equal(SettingsOutcome.Invalid, result.Outcome); + Assert.Equal(1, exit); + Assert.Equal(1, io.KeyWaits); + Assert.Contains(folder.SettingsPath, io.Text); + Assert.Contains("delete the file", io.Text); + Assert.DoesNotContain("Exception", io.Text); + Assert.DoesNotContain(" at ", io.Text); + } + + [Fact] + public void Relative_pdf_path_is_resolved_next_to_the_exe() + { + using ProgramFolder folder = new(); + string expected = folder.CreateFile(Path.Combine("docs", "a.pdf")); + folder.WriteSettings(Settings(pdf: "docs/a.pdf", really: true)); + PrintSpy spy = new(); + + NewApp(new FakeConsole(), folder, spy).Run(); + + Assert.Equal(1, spy.Calls); + Assert.Equal(Path.GetFullPath(expected), Path.GetFullPath(spy.Path!)); + + // An absolute path is left alone. + string absolute = Path.Combine(Path.GetTempPath(), "elsewhere", "b.pdf"); + Assert.Equal(absolute, TestPrintApp.ResolveNextToProgram(folder.Path, absolute)); + } + + [Theory] + [InlineData("\\\"docs/a.pdf\\\"")] + [InlineData("'docs/a.pdf'")] + [InlineData(" \\\"docs/a.pdf\\\" ")] + public void Quoted_pdf_path_is_unquoted_and_found(string jsonValue) + { + using ProgramFolder folder = new(); + string expected = folder.CreateFile(Path.Combine("docs", "a.pdf")); + folder.WriteSettings($$"""{ "PrinterName": "Office Laser", "PdfFile": "{{jsonValue}}", "ReallyPrint": true }"""); + FakeConsole io = new(); + PrintSpy spy = new(); + + int exit = NewApp(io, folder, spy).Run(); + + Assert.Equal(0, exit); + Assert.Equal(1, spy.Calls); + Assert.Equal(Path.GetFullPath(expected), Path.GetFullPath(spy.Path!)); + Assert.Contains("the PDF file was found", io.Text); + } + + [Theory] + [InlineData("\\\"out.pdf\\\"")] + [InlineData("'out.pdf'")] + public void Quoted_output_file_is_unquoted(string jsonValue) + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings($$"""{ "PrinterName": "Office Laser", "OutputFile": "{{jsonValue}}", "ReallyPrint": true }"""); + PrintSpy spy = new(); + + NewApp(new FakeConsole(), folder, spy).Run(); + + Assert.Equal(Path.Combine(folder.Path, "out.pdf"), spy.Options!.OutputFile); + } + + [Fact] + public void Quoted_printer_name_is_unquoted_and_only_one_pair_is_removed() + { + TestPrintSettings s = SettingsFile.Parse("""{ "PrinterName": "\"Office Laser\"", "PdfFile": "\"\"x.pdf\"\"", "OutputFile": "'a" }"""); + + Assert.Equal("Office Laser", s.PrinterName); + Assert.Equal("\"x.pdf\"", s.PdfFile); // one pair only; a leftover quote then shows up in the "not found" message + Assert.Equal("'a", s.OutputFile); // quotes that do not match are left alone + } + + [Fact] + public void Doubled_quotes_around_a_pasted_path_give_a_hint_about_the_quotes() + { + using ProgramFolder folder = new(); + folder.WriteSettings("""{ "PdfFile": ""C:/Docs/a.pdf"" }"""); + FakeConsole io = new(); + + int exit = NewApp(io, folder, new PrintSpy()).Run(); + + Assert.Equal(1, exit); + Assert.Contains("extra quote marks", io.Text); + Assert.Contains("single backslash", io.Text); + } + + [Fact] + public void Missing_printer_gives_plain_message_and_list_of_installed_printers() + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(printer: "No Such Printer", really: true)); + FakeConsole io = new(); + PrintSpy spy = new(); + + int exit = NewApp(io, folder, spy).RunAndWait(); + + Assert.Equal(1, exit); + Assert.Equal(0, spy.Calls); + Assert.Contains("No Such Printer", io.Text); + Assert.Contains("not installed", io.Text); + Assert.Contains("Microsoft Print to PDF", io.Text); + Assert.Contains("Office Laser", io.Text); + Assert.Contains("PrinterName", io.Text); + Assert.Equal(1, io.KeyWaits); + } + + [Fact] + public void Empty_printer_name_lists_the_installed_printers() + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(printer: "")); + FakeConsole io = new(); + + int exit = NewApp(io, folder, new PrintSpy()).Run(); + + Assert.Equal(1, exit); + Assert.Contains("PrinterName is empty", io.Text); + Assert.Contains("Microsoft Print to PDF", io.Text); + Assert.Contains("Office Laser", io.Text); + } + + [Fact] + public void No_installed_printers_says_so_in_plain_language() + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings()); + FakeConsole io = new(); + + NewApp(io, folder, new PrintSpy(), printers: Array.Empty()).Run(); + + Assert.Contains("Windows reports no installed printers", io.Text); + } + + [Fact] + public void ReallyPrint_false_does_not_print() + { + using ProgramFolder folder = new(); + string pdf = folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(extra: "\"Copies\": 2, \"Pages\": \"1-3\", \"OutputFile\": \"out.pdf\",")); + FakeConsole io = new(); + PrintSpy spy = new(); + + int exit = NewApp(io, folder, spy).RunAndWait(); + + Assert.Equal(0, exit); + Assert.Equal(0, spy.Calls); + Assert.Equal(1, io.KeyWaits); + Assert.Contains("DRY RUN", io.Text); + Assert.Contains("Nothing was printed", io.Text); + + // It shows exactly what would be sent. + Assert.Contains("Office Laser", io.Text); + Assert.Contains(pdf, io.Text); + Assert.Contains("2", io.Text); + Assert.Contains("1-3", io.Text); + Assert.Contains(Path.Combine(folder.Path, "out.pdf"), io.Text); + + // And how to really print. + Assert.Contains("\"ReallyPrint\": true", io.Text); + } + + [Fact] + public void Dry_run_reports_a_missing_pdf_and_a_missing_printer_together() + { + using ProgramFolder folder = new(); + folder.WriteSettings(Settings(printer: "Gone", pdf: "nope.pdf")); + FakeConsole io = new(); + PrintSpy spy = new(); + + int exit = NewApp(io, folder, spy).Run(); + + Assert.Equal(1, exit); + Assert.Equal(0, spy.Calls); + Assert.Contains("PDF file was not found", io.Text); + Assert.Contains(Path.Combine(folder.Path, "nope.pdf"), io.Text); + Assert.Contains("\"Gone\" is not installed", io.Text); + } + + [Fact] + public void Copies_below_one_is_explained() + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(extra: "\"Copies\": 0,", really: true)); + FakeConsole io = new(); + PrintSpy spy = new(); + + int exit = NewApp(io, folder, spy).Run(); + + Assert.Equal(1, exit); + Assert.Equal(0, spy.Calls); + Assert.Contains("Copies must be 1 or more", io.Text); + } + + [Fact] + public void ReallyPrint_true_prints_and_shows_message_and_page_count() + { + using ProgramFolder folder = new(); + string pdf = folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(extra: "\"Copies\": 2, \"Pages\": \"1-2\",", really: true)); + FakeConsole io = new(); + PrintSpy spy = new() { Result = PrintResult.Success(2) }; + + int exit = NewApp(io, folder, spy).RunAndWait(); + + Assert.Equal(0, exit); + Assert.Equal(1, spy.Calls); + Assert.Equal(pdf, spy.Path); + Assert.Equal("Office Laser", spy.Options!.PrinterName); + Assert.Equal(2, spy.Options.Copies); + Assert.Equal("1-2", spy.Options.Pages); + Assert.Null(spy.Options.OutputFile); + Assert.Contains("2 page(s)", io.Text); + Assert.Contains(spy.Result.Message, io.Text); + Assert.DoesNotContain("DRY RUN", io.Text); + Assert.Equal(1, io.KeyWaits); + } + + [Fact] + public void ReallyPrint_true_failure_is_shown_in_plain_language() + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(really: true)); + FakeConsole io = new(); + PrintSpy spy = new() { Result = PrintResult.Failure(PrintStatus.PrinterUnavailable, "The printer is paused. Resume it and try again.") }; + + int exit = NewApp(io, folder, spy).Run(); + + Assert.Equal(1, exit); + Assert.Contains("NOT printed", io.Text); + Assert.Contains("The printer is paused. Resume it and try again.", io.Text); + Assert.Contains("0 page(s)", io.Text); + } + + [Fact] + public void Unexpected_error_still_waits_for_a_key_and_is_plain() + { + using ProgramFolder folder = new(); + folder.CreateFile("test.pdf"); + folder.WriteSettings(Settings(really: true)); + FakeConsole io = new(); + TestPrintApp app = new(io, folder.Path, () => throw new InvalidOperationException("boom"), new PrintSpy().Print); + + int exit = app.RunAndWait(); + + Assert.Equal(1, exit); + Assert.Equal(1, io.KeyWaits); + Assert.Contains("unexpected", io.Text); + Assert.Contains("boom", io.Text); + Assert.DoesNotContain(" at ", io.Text); + } +}