diff --git a/OpenNest.Tests/Reporting/ReportPdf.cs b/OpenNest.Tests/Reporting/ReportPdf.cs index d7598d8b..c442e1b9 100644 --- a/OpenNest.Tests/Reporting/ReportPdf.cs +++ b/OpenNest.Tests/Reporting/ReportPdf.cs @@ -30,12 +30,12 @@ public static class ReportPdf /// Visual-row text of one page; bbox coordinates avoid platform-specific -layout order. public static string Text(string path, int page) => - LayoutPage(Run("pdftotext", "-bbox", "-f", Page(page), "-l", Page(page), path, "-")); + LayoutPage(Run("-bbox", "-f", Page(page), "-l", Page(page), path, "-")); /// Every page's visual-row text, in order. public static string[] Pages(string path) { - var html = Run("pdftotext", "-bbox", path, "-"); + var html = Run("-bbox", path, "-"); return Regex.Matches(html, @"]*>.*?", RegexOptions.Singleline) .Select(match => LayoutPage(match.Value)).ToArray(); } @@ -62,7 +62,7 @@ public static class ReportPdf /// public static List PartCards(string path) { - var html = Run("pdftotext", "-bbox", path, "-"); + var html = Run("-bbox", path, "-"); var cards = new List<(int Page, double Top, int Column, string Text)>(); var started = false; var pages = Regex.Matches(html, @"]*>.*?", RegexOptions.Singleline).Select(match => match.Value).ToList(); @@ -128,7 +128,7 @@ public static class ReportPdf /// Words with page-space boxes (points, Y down). public static List<(double Left, double Top, double Right, double Bottom, string Text)> Words(string path, int page) => - ParseWords(Run("pdftotext", "-bbox", "-f", Page(page), "-l", Page(page), path, "-")); + ParseWords(Run("-bbox", "-f", Page(page), "-l", Page(page), path, "-")); private static List<(double Left, double Top, double Right, double Bottom, string Text)> ParseWords(string xml) { @@ -142,8 +142,73 @@ public static class ReportPdf private static double Number(string value) => double.Parse(value, CultureInfo.InvariantCulture); - private static string Run(string tool, params string[] arguments) + /// Names the pdftotext to run, instead of the first on PATH that accepts -bbox. + public const string ToolVariable = "OPENNEST_PDFTOTEXT"; + + private static readonly Lazy<(string Tool, string Problem)> PdfToText = new(FindPdfToText); + + /// + /// The pdftotext the text assertions run. PATH can hold more than one: Git for Windows + /// ships Xpdf's, which has no -bbox, and a shell that puts Git first hides Poppler's. + /// So the search takes the first that offers -bbox rather than the first it meets. + /// + private static (string Tool, string Problem) FindPdfToText() { + var named = Environment.GetEnvironmentVariable(ToolVariable); + if (!string.IsNullOrWhiteSpace(named)) + return (named, null); + + var name = OperatingSystem.IsWindows() ? "pdftotext.exe" : "pdftotext"; + var found = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty) + .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(folder => Path.Combine(folder.Trim('"'), name)) + .Where(File.Exists) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + var tool = FirstWithBbox(found, Help); + if (tool != null) + return (tool, null); + + return found.Count == 0 + ? (null, null) + : (null, $"No pdftotext on PATH accepts -bbox (found {string.Join(", ", found)}). " + + $"Install Poppler, or name its pdftotext in {ToolVariable}."); + } + + /// The first candidate whose help text offers -bbox, or null when none does. + internal static string FirstWithBbox(IEnumerable candidates, Func help) => + candidates.FirstOrDefault(candidate => Regex.IsMatch(help(candidate), @"(?m)^\s*-bbox(?![\w-])")); + + /// What a pdftotext prints for -h, on either stream; empty when it cannot run. + private static string Help(string tool) + { + try + { + var info = new ProcessStartInfo(tool) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + info.ArgumentList.Add("-h"); + using var process = Process.Start(info)!; + var error = process.StandardError.ReadToEndAsync(); + var output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + return output + error.Result; + } + catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or IOException or InvalidOperationException) + { + return string.Empty; + } + } + + private static string Run(params string[] arguments) + { + var (tool, problem) = PdfToText.Value; + Assert.True(problem == null, problem); + Skip.If(tool == null, "pdftotext (poppler-utils) is not installed."); + var info = new ProcessStartInfo(tool) { RedirectStandardOutput = true, @@ -156,9 +221,10 @@ public static class ReportPdf { process = Process.Start(info)!; } - catch (System.ComponentModel.Win32Exception) + catch (System.ComponentModel.Win32Exception exception) { - Skip.If(true, $"{tool} (poppler-utils) is not installed."); + // Only a pdftotext named in the variable gets here: one found on PATH exists. + Assert.Fail($"{tool} ({ToolVariable}) cannot start: {exception.Message}"); throw; } using (process) diff --git a/OpenNest.Tests/Reporting/ReportPdfToolTests.cs b/OpenNest.Tests/Reporting/ReportPdfToolTests.cs new file mode 100644 index 00000000..5305529c --- /dev/null +++ b/OpenNest.Tests/Reporting/ReportPdfToolTests.cs @@ -0,0 +1,47 @@ +namespace OpenNest.Tests.Reporting; + +/// +/// The report tests need a pdftotext with -bbox. PATH can list one without it first (Git for +/// Windows ships Xpdf's), so the search must pass over it. +/// +public class ReportPdfToolTests +{ + private const string XpdfHelp = """ + pdftotext version 4.00 + Usage: pdftotext [options] [] + -f : first page to convert + -layout : maintain original physical layout + """; + + private const string PopplerHelp = """ + pdftotext version 25.07.0 + Usage: pdftotext [options] [] + -f : first page to convert + -bbox : output bounding box for each word and page size to html. Sets -htmlmeta + -bbox-layout : like -bbox but with extra layout bounding box data. Sets -htmlmeta + """; + + [Fact] + public void FirstWithBbox_PassesOverAToolWithoutTheOption() + { + var help = new Dictionary + { + ["git/pdftotext"] = XpdfHelp, + ["broken/pdftotext"] = string.Empty, + ["poppler/pdftotext"] = PopplerHelp, + ["later/pdftotext"] = PopplerHelp, + }; + + Assert.Equal("poppler/pdftotext", ReportPdf.FirstWithBbox(help.Keys, tool => help[tool])); + } + + [Fact] + public void FirstWithBbox_IsNullWhenNoToolHasTheOption() + { + // -bbox-layout alone is not the option the tests pass. + var onlyLayout = " -bbox-layout : like -bbox but with extra layout bounding box data."; + + Assert.Null(ReportPdf.FirstWithBbox(new[] { "a", "b" }, tool => tool == "a" ? XpdfHelp : onlyLayout)); + Assert.Null(ReportPdf.FirstWithBbox(Array.Empty(), _ => PopplerHelp)); + } +} diff --git a/docs/nest-reports.md b/docs/nest-reports.md index 7f0ab59b..647acffb 100644 --- a/docs/nest-reports.md +++ b/docs/nest-reports.md @@ -284,7 +284,11 @@ The writer tests read page sizes and content streams with PDFsharp. Text assertions use Poppler's `pdftotext -bbox` coordinates to rebuild visual rows; `-layout` can return columns in a different order on Windows. Part cards are read column by column (`ReportPdf.PartCards`), each ending at its "Plates:" line. They are skipped, -not passed, when poppler-utils is absent. The Windows release workflow installs +not passed, when poppler-utils is absent. The tests run the first `pdftotext` on +`PATH` whose help offers `-bbox`, so an older one listed first (Git for Windows +ships Xpdf's) does not hide Poppler's; they fail, naming what they found, when +every `pdftotext` on `PATH` lacks it. Set `OPENNEST_PDFTOTEXT` to a full path to +choose one outright. The Windows release workflow installs an SHA-256-pinned Poppler binary because the runner's built-in `pdftotext` lacks `-bbox`; no PDF text test is skipped for that reason in a release candidate. For manual inspection also use `pdfinfo`,