diff --git a/README.md b/README.md index c091c16e..6aafd2ea 100644 --- a/README.md +++ b/README.md @@ -99,10 +99,11 @@ rvtio sheets project.rvt sheets.json The catalog has the sheet number, name, issue date, by-lines and scale, the viewports of each sheet and the elements each sheet owns, plus the text and whole-number project/shared parameters of each sheet (`--params`, `--csv`, `--where NAME=VALUE` with `!=`/`~` and `*`/`?` wildcards). Page size, view placement, the displayed view and 2D content are not decoded; every limit is reported in the catalog itself. See [sheets and viewports](docs/sheets.md). -Print the plan of a level to PDF — walls with their stored width, column footprints and grids, on the smallest paper that holds the drawing at the scale: +Print the plan of a level to PDF or SVG — walls with their stored width, column footprints and grids, on the smallest paper that holds the drawing at the scale: ```sh rvtio print project.rvt plan.pdf --level "Уровень 1" --scale 100 +rvtio print project.rvt plan.svg --level "Уровень 1" --scale 100 ``` `--list-levels` prints the levels that can be printed. A sheet prints from its decoded linework (page border, title block frame, rules) on the paper it spans: diff --git a/docs/printing.md b/docs/printing.md index 27ba9362..d4b43571 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -1,6 +1,6 @@ # Printing a plan -`rvtio print` renders the plan of one level of a Revit project to a PDF page without Revit. This is the first view +`rvtio print` renders the plan of one level of a Revit project to a PDF page or an SVG drawing without Revit. This is the first view renderer of the sheet printing work described in [issue #18](https://github.com/IOExtend/RvtIO/issues/18): it draws the model geometry the reader decodes, not the linework Revit generates for a view. It is a working drawing of the level, not yet a printed sheet. @@ -14,6 +14,9 @@ rvtio print project.rvt --list-levels # the plan of one level at 1:100 on the smallest paper that holds it rvtio print project.rvt plan.pdf --level 355 --scale 100 +# the same level plan exported as SVG (1 user unit = 1 mm, UTF-8 XML with scale and sheet metadata) +rvtio print project.rvt plan.svg --level 355 --scale 100 + # a fixed paper size rvtio print project.rvt plan.pdf --level "Уровень 1" --scale 200 --paper A3 ``` @@ -44,8 +47,11 @@ of its level. A plan view is a `DBViewPlan` of the file whose name matches a printable level (or whose stored elevation equals the level's); a section or an elevation is left out until its renderer exists. -The library API is `RvtIO.Print.PlanPrinter`: `Levels(document)` returns the printable levels, and -`Render(document, levelId, scale, options)` returns a `PdfDocument` with one page. +The library API is `RvtIO.Print.PlanPrinter`: `Levels(document)` returns the printable levels, +`Render(document, levelId, scale, options)` returns a `PdfDocument` with one page, and +`RenderSvg(document, levelId, scale, options)` returns the level plan as SVG text. +`WriteSvg(document, output, levelId, scale, options)` writes the same SVG as UTF-8 and leaves the destination stream open. +PDF and SVG share geometry, scale, and paper layout. Use finite, non-negative margins that leave a positive area on the paper. ## Images diff --git a/docs/public-api.md b/docs/public-api.md index 063aa99e..2fddcf6d 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -168,7 +168,7 @@ See [sheets and viewports](sheets.md) for what is decoded, what the limits are a | Type | Use | |---|---| -| `PlanPrinter` | `Levels(document)` lists the levels a plan can be printed for; `Render(document, levelId, scale, options)` returns a `PdfDocument` with the plan of one level: walls with their stored width, column footprints, clipped grids. | +| `PlanPrinter` | `Levels(document)` lists the printable levels. `Render(document, levelId, scale, options)` returns a `PdfDocument` with the plan of one level, including walls with their stored width, column footprints, and clipped grids. `RenderSvg(document, ...)` returns the same level plan as SVG text. `WriteSvg(document, output, ...)` writes it as UTF-8 to a stream. | | `PlanPrintOptions` | `PaperSize` (null picks the smallest paper that holds the drawing), `MarginMillimetres`, `FallbackWallWidthMillimetres`, `DrawFrame`. | | `PlanLevel`, `PlanView` | A printable level (id, name, elevation) and a printable plan view (id, name, level, scale). | | `ViewPrinter` | `Render(document, viewIds, options)` prints views into one PDF document, one page per view: a plan, an elevation or a section (`PlanPrinter.Views`, `ElevationPrinter.Views`), a 3D view (an isometric massing page) and a rendering (its image page). `OtherViews(document)` lists the 3D views and the renderings. | diff --git a/src/RvtIO.Cli/PrintCommand.cs b/src/RvtIO.Cli/PrintCommand.cs index 5ba6af91..00832f57 100644 --- a/src/RvtIO.Cli/PrintCommand.cs +++ b/src/RvtIO.Cli/PrintCommand.cs @@ -8,8 +8,8 @@ namespace RvtIO.Cli; /// -/// rvtio print <file.rvt> <out.pdf> [--level <id|name>] [--view <id|name>] [--sheet <id|number>] [--where FILTER] [--scale <n>] -/// [--paper A4|A3|A2|A1|A0]: renders the plan of one level, or one or more plan views at their own scales, to a PDF +/// rvtio print <file.rvt> <out.pdf|out.svg> [--level <id|name>] [--view <id|name>] [--sheet <id|number>] [--where FILTER] [--scale <n>] +/// [--paper A4|A3|A2|A1|A0]: renders the plan of one level to PDF or SVG (.svg), or one or more plan views or sheets at their own scales to PDF /// (see ). --list-levels and --list-views print what can be printed instead. /// --where NAME=VALUE (also != and ~ for contains, * and ? wildcards, repeatable) keeps /// only the sheets whose parameters match; it needs --sheet, --all-sheets or --list-sheets. @@ -89,7 +89,10 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (whereFilters.Count > 0 && sheetTexts.Count == 0 && !allSheets && !listSheets) return Usage(error, "--where selects sheets; it needs --sheet, --all-sheets or --list-sheets."); bool listing = listLevels || listViews || listSheets; - if (!listing && outputPath == null) return Usage(error, "print requires the output PDF path."); + if (!listing && outputPath == null) return Usage(error, "print requires the output PDF path (or .svg for a level plan)."); + bool svgOutput = outputPath != null && outputPath.EndsWith(".svg", StringComparison.OrdinalIgnoreCase); + if (svgOutput && (allSheets || allViews || sheetTexts.Count > 0 || viewTexts.Count > 0 || whereFilters.Count > 0)) + return Usage(error, "SVG output supports level plan rendering only (--level, --scale, --paper); use a .pdf path for views and sheets."); // File identity also catches when a link in the output path points to the input model. if (outputPath != null && FileIdentity.SameFile(outputPath, file)) { @@ -194,6 +197,39 @@ IReadOnlyList ListedComposed() => try { + if (svgOutput) + { + if (levels.Count == 0) + { + error.WriteLine("No level with a wall or column was found; nothing to print."); + return RvtExitCodes.DecodeError; + } + int? levelId = ResolveLevelId(levelText, levels); + if (levelText != null && levelId == null) + { + error.WriteLine($"No printable level is named or numbered '{levelText}'. --list-levels shows them."); + return RvtExitCodes.Usage; + } + + PdfPageSize svgPaper; + double effectiveScale; + string temporarySvg = outputPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var fs = File.Create(temporarySvg)) + PlanPrinter.WriteSvg(document, fs, levelId, scale, new PlanPrintOptions { PaperSize = paper }, + out svgPaper, out effectiveScale); + File.Move(temporarySvg, outputPath!, overwrite: true); + } + catch + { + if (File.Exists(temporarySvg)) File.Delete(temporarySvg); + throw; + } + error.WriteLine($"[print] 1 page(s), first {svgPaper.WidthMillimetres:0} x {svgPaper.HeightMillimetres:0} mm (1:{effectiveScale:0}) -> {outputPath}"); + return RvtExitCodes.Success; + } + PdfDocument pdf; if (allSheets) { @@ -277,22 +313,11 @@ IReadOnlyList ListedComposed() => error.WriteLine("No level with a wall or column was found; nothing to print."); return RvtExitCodes.DecodeError; } - int? levelId = null; - if (levelText != null) + int? levelId = ResolveLevelId(levelText, levels); + if (levelText != null && levelId == null) { - foreach (PlanLevel level in levels) - { - if (int.TryParse(levelText, NumberStyles.None, CultureInfo.InvariantCulture, out int id) && id == level.LevelId) - levelId = level.LevelId; - else if (string.Equals(level.Name, levelText, StringComparison.OrdinalIgnoreCase)) - levelId = level.LevelId; - if (levelId != null) break; - } - if (levelId == null) - { - error.WriteLine($"No printable level is named or numbered '{levelText}'. --list-levels shows them."); - return RvtExitCodes.Usage; - } + error.WriteLine($"No printable level is named or numbered '{levelText}'. --list-levels shows them."); + return RvtExitCodes.Usage; } pdf = PlanPrinter.Render(document, levelId, scale, new PlanPrintOptions { PaperSize = paper }); } @@ -406,10 +431,22 @@ internal static ExplicitSheetSelection SelectExplicitSheets( return new ExplicitSheetSelection(sheetIds, composedIds, null); } + private static int? ResolveLevelId(string? levelText, IReadOnlyList levels) + { + if (levelText == null) return null; + bool byId = int.TryParse(levelText, NumberStyles.None, CultureInfo.InvariantCulture, out int id); + foreach (PlanLevel level in levels) + { + if ((byId && id == level.LevelId) || string.Equals(level.Name, levelText, StringComparison.OrdinalIgnoreCase)) + return level.LevelId; + } + return null; + } + private static int Usage(TextWriter error, string problem) { error.WriteLine(problem); - error.WriteLine("Usage: rvtio print [--level ] [--view ] [--sheet ] " + error.WriteLine("Usage: rvtio print [--level ] [--view ] [--sheet ] " + "[--where FILTER] [--all-views] [--all-sheets] [--scale ] [--paper A4|A3|A2|A1|A0] " + "[--list-levels] [--list-views] [--list-sheets]"); return RvtExitCodes.Usage; diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index fd4357f4..d0aa1c63 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -67,10 +67,10 @@ Report options (read the file and print or write a report instead of exporting): --list-category list the elements of one category sheets [output.json] [--r22-layout] [--where FILTER] [--params] [--csv] [--json] write the sheet catalog (sheets, viewports, parameters, limits not decoded) as JSON - print [--level ] [--view ] [--sheet ] [--where FILTER] [--scale ] + print [--level ] [--view ] [--sheet ] [--where FILTER] [--scale ] [--all-views] [--all-sheets] [--paper A4|A3|A2|A1|A0] [--list-levels] [--list-views] [--list-sheets] - render the plan of one level, one or more views (plans and elevations) or all of + render the plan of one level (to PDF or SVG), one or more views (plans and elevations) or all of them, or one or more sheets, to PDF Developer options (measurement and comparison dumps, not a stable interface): diff --git a/src/RvtIO/Print/PlanPrinter.cs b/src/RvtIO/Print/PlanPrinter.cs index bc6381e3..9c1a09f9 100644 --- a/src/RvtIO/Print/PlanPrinter.cs +++ b/src/RvtIO/Print/PlanPrinter.cs @@ -11,7 +11,7 @@ public sealed class PlanPrintOptions /// The paper size; null chooses the smallest of A4 to A0 that holds the drawing at the view scale. public PdfPageSize? PaperSize { get; set; } - /// The margin around the drawing, in millimetres. + /// The non-negative, finite margin around the drawing, in millimetres. public double MarginMillimetres { get; set; } = 10; /// The width in millimetres a wall is drawn with when neither the wall nor its type stores one. @@ -149,6 +149,7 @@ public static IReadOnlyList Views(RvtDocument document) /// The paper and margin; null uses the defaults. /// The document has no level with a wall or column, or the level has /// nothing with a location line to draw. + /// The scale is not positive, or the paper and margin cannot fit the plan. public static PdfDocument Render(RvtDocument document, int? levelId = null, int scale = 100, PlanPrintOptions? options = null) { @@ -156,27 +157,90 @@ public static PdfDocument Render(RvtDocument document, int? levelId = null, int ArgumentOutOfRangeException.ThrowIfNegativeOrZero(scale); options ??= new PlanPrintOptions(); - if (levelId == null) - { - int? best = null; - int bestCount = 0; - var counts = new Dictionary(); - foreach (var element in document.Elements) - { - if (!IsWallOrColumn(element) || !HasDrawableGeometry(element)) continue; - if (LevelOf(element) is not int level) continue; - counts[level] = counts.TryGetValue(level, out int count) ? count + 1 : 1; - if (counts[level] > bestCount) { best = level; bestCount = counts[level]; } - } - if (best == null) throw new InvalidOperationException("The document has no level with a wall or column."); - levelId = best; - } - + int resolvedLevelId = ResolveLevelId(document, levelId); var pdf = new PdfDocument { Font = PdfFonts.TryFind(out _), Compress = true }; - AddPlanPage(pdf, document, levelId.Value, scale, document.GetElement(levelId.Value)?.Name, options); + AddPlanPage(pdf, document, resolvedLevelId, scale, document.GetElement(resolvedLevelId)?.Name, options); return pdf; } + /// Prints the plan of a level to a UTF-8 SVG document sharing the geometry, layout, and scale rules of + /// . + /// The opened document. + /// The level to print; null prints the level with the most walls and columns. + /// The view scale denominator: 100 prints 1:100, one model metre to ten millimetres of paper. + /// The paper and margin; null uses the defaults. + /// The document has no level with a wall or column, or the level has + /// nothing with a location line to draw. + /// The scale is not positive, or the paper and margin cannot fit the plan. + public static string RenderSvg(RvtDocument document, int? levelId = null, int scale = 100, + PlanPrintOptions? options = null) + { + using var stream = new MemoryStream(); + WriteSvg(document, stream, levelId, scale, options); + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } + + /// Prints the plan of a level as UTF-8 SVG XML to (leaving the stream open). + /// The opened document. + /// Writable destination stream. + /// The level to print; null prints the level with the most walls and columns. + /// The view scale denominator: 100 prints 1:100, one model metre to ten millimetres of paper. + /// The paper and margin; null uses the defaults. + /// The document has no level with a wall or column, or the level has + /// nothing with a location line to draw. + /// The scale is not positive, or the paper and margin cannot fit the plan. + public static void WriteSvg(RvtDocument document, Stream output, int? levelId = null, int scale = 100, + PlanPrintOptions? options = null) => + WriteSvg(document, output, levelId, scale, options, out _, out _); + + internal static void WriteSvg(RvtDocument document, Stream output, int? levelId, int scale, + PlanPrintOptions? options, out PdfPageSize paper, out double effectiveScale) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(output); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(scale); + options ??= new PlanPrintOptions(); + + int resolvedLevelId = ResolveLevelId(document, levelId); + string? title = document.GetElement(resolvedLevelId)?.Name; + var layout = ComputePageLayout(document, resolvedLevelId, scale, options); + paper = layout.Paper; + effectiveScale = layout.EffectiveScale; + + using var svg = new SvgPlanCanvas( + output, + layout.Paper, + resolvedLevelId, + title, + scale, + layout.EffectiveScale, + options.MarginMillimetres, + layout.OffsetX, + layout.OffsetY, + layout.Content.MinX, + layout.Content.MinY, + layout.Content.MaxX, + layout.Content.MaxY); + DrawPlanSurface(svg, layout, title, options); + } + + private static int ResolveLevelId(RvtDocument document, int? levelId) + { + if (levelId.HasValue) return levelId.Value; + + int? best = null; + int bestCount = 0; + var counts = new Dictionary(); + foreach (var element in document.Elements) + { + if (!IsWallOrColumn(element) || !HasDrawableGeometry(element)) continue; + if (LevelOf(element) is not int level) continue; + counts[level] = counts.TryGetValue(level, out int count) ? count + 1 : 1; + if (counts[level] > bestCount) { best = level; bestCount = counts[level]; } + } + return best ?? throw new InvalidOperationException("The document has no level with a wall or column."); + } + /// Prints one view to a one-page PDF document, at the view's own scale. /// The opened document. /// The element id of the view; it must be one of . @@ -513,7 +577,50 @@ void Grow(double x, double y) return type?.LookupParameter(BuiltInParameter.ALL_MODEL_TYPE_MARK)?.Value as string; } + internal sealed record PlanLayout( + PlanContent Content, + PdfPageSize Paper, + double EffectiveScale, + double OffsetX, + double OffsetY); + + internal static PlanLayout ComputePageLayout(RvtDocument document, int levelId, int scale, PlanPrintOptions options) + { + double margin = options.MarginMillimetres; + if (!double.IsFinite(margin) || margin < 0) + throw new ArgumentOutOfRangeException(nameof(options), "The plan margin must be finite and non-negative."); + + PlanContent content = CollectLevel(document, levelId) + ?? throw new InvalidOperationException("The level has no wall or column with a location line to draw."); + double contentWidth = (content.MaxX - content.MinX) / scale; + double contentHeight = (content.MaxY - content.MinY) / scale; + PdfPageSize paper = options.PaperSize ?? SmallestPaper(contentWidth + 2 * margin, contentHeight + 2 * margin); + double usableWidth = paper.WidthMillimetres - 2 * margin; + double usableHeight = paper.HeightMillimetres - 2 * margin; + if (!double.IsFinite(usableWidth) || !double.IsFinite(usableHeight) || usableWidth <= 0 || usableHeight <= 0) + throw new ArgumentOutOfRangeException(nameof(options), "The paper must leave a positive, finite area inside the margins."); + + double effectiveScale = scale; + if (contentWidth > usableWidth || contentHeight > usableHeight) + { + double factor = Math.Min(usableWidth / Math.Max(contentWidth, 1e-9), + usableHeight / Math.Max(contentHeight, 1e-9)); + effectiveScale = scale / factor; + } + if (!double.IsFinite(effectiveScale)) + throw new ArgumentOutOfRangeException(nameof(options), "The plan cannot fit on the paper at a finite scale."); + + double offsetX = (paper.WidthMillimetres - (content.MaxX - content.MinX) / effectiveScale) / 2; + double offsetY = (paper.HeightMillimetres - (content.MaxY - content.MinY) / effectiveScale) / 2; + return new PlanLayout(content, paper, effectiveScale, offsetX, offsetY); + } + internal static void DrawContent(PdfPage page, PlanContent content, double scale, double originX, + double originY, double floorFill = 0.9, + IReadOnlyList<(double X, double Y, double Dx, double Dy, string Name)>? sectionMarks = null) => + DrawContent(new PdfPlanCanvas(page), content, scale, originX, originY, floorFill, sectionMarks); + + internal static void DrawContent(IPlanCanvas canvas, PlanContent content, double scale, double originX, double originY, double floorFill = 0.9, IReadOnlyList<(double X, double Y, double Dx, double Dy, string Name)>? sectionMarks = null) { @@ -521,18 +628,18 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double ToY(double y) => (y - content.MinY) / scale + originY; foreach (var floor in content.FloorLoops) - page.DrawPolyline(floor.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, floorFill); + canvas.DrawPolyline(floor.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, floorFill); foreach (var room in content.Rooms) - page.DrawPolyline(room.Polygon.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, + canvas.DrawPolyline(room.Polygon.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0, true, RoomFill(room.Name)); foreach (var grid in content.Grids) { - page.DrawLine(ToX(grid.X1), ToY(grid.Y1), ToX(grid.X2), ToY(grid.Y2), 0.18, 0.45); - if (page.Owner.Font == null || grid.Name.Length == 0) continue; - Bubble(page, ToX(grid.X1), ToY(grid.Y1), grid.Name); - Bubble(page, ToX(grid.X2), ToY(grid.Y2), grid.Name); + canvas.DrawLine(ToX(grid.X1), ToY(grid.Y1), ToX(grid.X2), ToY(grid.Y2), 0.18, 0.45); + if (!canvas.CanDrawText || grid.Name.Length == 0) continue; + Bubble(canvas, ToX(grid.X1), ToY(grid.Y1), grid.Name); + Bubble(canvas, ToX(grid.X2), ToY(grid.Y2), grid.Name); } var wallById = new Dictionary(); @@ -551,7 +658,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double bx = wall.X1 + ux * to, by = wall.Y1 + uy * to; // The wall is poche: the stretch between its two sides is filled, the way a printed plan fills a cut // wall, and the four edges are inked over it. - page.DrawPolyline( + canvas.DrawPolyline( [ (ToX(ax + nx), ToY(ay + ny)), (ToX(bx + nx), ToY(by + ny)), (ToX(bx - nx), ToY(by - ny)), (ToX(ax - nx), ToY(ay - ny)), @@ -567,12 +674,12 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double length = Math.Sqrt(dx * dx + dy * dy); if (length < 1e-6) continue; double ux = dx / length, uy = dy / length; - page.DrawLine(ToX(wall.X1 + ux * from), ToY(wall.Y1 + uy * from), + canvas.DrawLine(ToX(wall.X1 + ux * from), ToY(wall.Y1 + uy * from), ToX(wall.X1 + ux * to), ToY(wall.Y1 + uy * to), 0.15, 0.35); } // The room names and areas, at the centre of the footprint, in plan millimetres. - if (page.Owner.Font != null) + if (canvas.CanDrawText) { foreach (var room in content.Rooms) { @@ -585,17 +692,17 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale // The room tag of the reference plan: the number and the area in a rounded white box at the middle of // the room (the legend carries the names). double boxWidth = 16, boxHeight = 5.2; - page.DrawPolyline(RoundedBox(pageX - boxWidth / 2, pageY - boxHeight / 2, boxWidth, boxHeight, 1.2), + canvas.DrawPolyline(RoundedBox(pageX - boxWidth / 2, pageY - boxHeight / 2, boxWidth, boxHeight, 1.2), 0.18, true, 1); - page.DrawText(room.Number, pageX - boxWidth / 2 + 2, pageY - 1.1, 2.4); + canvas.DrawText(room.Number, pageX - boxWidth / 2 + 2, pageY - 1.1, 2.4); if (room.AreaSquareFeet > 0) - page.DrawText($"{room.AreaSquareFeet * 0.092903:0} m²", pageX + boxWidth / 2 - 2, pageY - 1, + canvas.DrawText($"{room.AreaSquareFeet * 0.092903:0} m²", pageX + boxWidth / 2 - 2, pageY - 1, 2, PdfTextAlignment.Right); } } foreach (var outline in content.Furniture) - page.DrawPolyline(outline.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0.12, true, + canvas.DrawPolyline(outline.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0.12, true, new PdfColor(0.55, 0.55, 0.55)); // A door is drawn as its leaf and the quarter arc it sweeps: the leaf stands at one jamb, perpendicular to the @@ -603,7 +710,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double centerX = (content.MinX + content.MaxX) / 2, centerY = (content.MinY + content.MaxY) / 2; // The marks of the doors and windows, in a small circle beside the opening. - if (page.Owner.Font != null) + if (canvas.CanDrawText) { foreach (var tag in content.Tags) { @@ -613,7 +720,7 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double tagY = ToY(tag.MidY + tag.Ny * side * distance); // A door is tagged with its mark in a circle, a window with its type mark in a hexagon, a leader line // from the opening to the tag, as a plan draws them. - page.DrawLine(ToX(tag.MidX), ToY(tag.MidY), tagX, tagY, 0.1, 0.5); + canvas.DrawLine(ToX(tag.MidX), ToY(tag.MidY), tagX, tagY, 0.1, 0.5); var shape = new List<(double X, double Y)>(6); double radius = tag.IsWindow ? 2.6 : 2.2; for (int i = 0; i < (tag.IsWindow ? 6 : 20); i++) @@ -623,8 +730,8 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale : i * Math.PI * 2 / 20; shape.Add((tagX + radius * Math.Cos(angle), tagY + radius * Math.Sin(angle))); } - page.DrawPolyline(shape, 0.12, true, 1); - page.DrawText(tag.Text, tagX, tagY - 0.9, tag.IsWindow ? 1.6 : 1.8, PdfTextAlignment.Center); + canvas.DrawPolyline(shape, 0.12, true, 1); + canvas.DrawText(tag.Text, tagX, tagY - 0.9, tag.IsWindow ? 1.6 : 1.8, PdfTextAlignment.Center); } } @@ -642,66 +749,54 @@ internal static void DrawContent(PdfPage page, PlanContent content, double scale double midX = (hx + ex) / 2, midY = (hy + ey) / 2; double side = (centerX - midX) * nx + (centerY - midY) * ny >= 0 ? 1 : -1; double tipX = hx + nx * side * width, tipY = hy + ny * side * width; - page.DrawLine(ToX(hx), ToY(hy), ToX(tipX), ToY(tipY), 0.18); + canvas.DrawLine(ToX(hx), ToY(hy), ToX(tipX), ToY(tipY), 0.18); double a0 = Math.Atan2(tipY - hy, tipX - hx) * 180 / Math.PI; double a1 = Math.Atan2(ey - hy, ex - hx) * 180 / Math.PI; while (a1 < a0) a1 += 360; if (a1 - a0 > 270) a1 -= 360; - page.DrawArc(ToX(hx), ToY(hy), width / scale, a0, a1, 0.15, 0.4); + canvas.DrawArc(ToX(hx), ToY(hy), width / scale, a0, a1, 0.15, 0.4); } - DimChains(page, content, ToX, ToY); + DimChains(canvas, content, ToX, ToY); foreach (var opening in content.OpeningLoops) - page.DrawPolyline(opening.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0.18, true); + canvas.DrawPolyline(opening.Select(point => (ToX(point.X), ToY(point.Y))).ToList(), 0.18, true); foreach (var column in content.Columns) - page.DrawRectangle(ToX(column.X), ToY(column.Y), column.Width / scale, column.Height / scale, 0.2, 1); + canvas.DrawRectangle(ToX(column.X), ToY(column.Y), column.Width / scale, column.Height / scale, 0.2, 1); - if (sectionMarks is { Count: > 0 }) DrawSectionMarks(page, content, scale, originX, originY, sectionMarks); + if (sectionMarks is { Count: > 0 }) DrawSectionMarks(canvas, content, scale, originX, originY, sectionMarks); } /// Draws the plan of a level as one page of the document. internal static void AddPlanPage(PdfDocument pdf, RvtDocument document, int levelId, int scale, string? title, PlanPrintOptions options) { - PlanContent content = CollectLevel(document, levelId) - ?? throw new InvalidOperationException("The level has no wall or column with a location line to draw."); - double contentWidth = (content.MaxX - content.MinX) / scale; - double contentHeight = (content.MaxY - content.MinY) / scale; - PdfPageSize paper = options.PaperSize ?? SmallestPaper(contentWidth + 2 * options.MarginMillimetres, - contentHeight + 2 * options.MarginMillimetres); - double usableWidth = paper.WidthMillimetres - 2 * options.MarginMillimetres; - double usableHeight = paper.HeightMillimetres - 2 * options.MarginMillimetres; - double effectiveScale = scale; - if (contentWidth > usableWidth || contentHeight > usableHeight) - { - double factor = Math.Min(usableWidth / Math.Max(contentWidth, 1e-9), - usableHeight / Math.Max(contentHeight, 1e-9)); - effectiveScale = scale / factor; - } - double offsetX = (paper.WidthMillimetres - (content.MaxX - content.MinX) / effectiveScale) / 2; - double offsetY = (paper.HeightMillimetres - (content.MaxY - content.MinY) / effectiveScale) / 2; + var layout = ComputePageLayout(document, levelId, scale, options); + PdfPage page = pdf.AddPage(layout.Paper); + DrawPlanSurface(new PdfPlanCanvas(page), layout, title, options); + } - PdfPage page = pdf.AddPage(paper); + private static void DrawPlanSurface(IPlanCanvas canvas, PlanLayout layout, string? title, PlanPrintOptions options) + { if (options.DrawFrame) { double m = options.MarginMillimetres; - page.DrawRectangle(m, m, paper.WidthMillimetres - 2 * m, paper.HeightMillimetres - 2 * m, 0.25); + canvas.DrawRectangle(m, m, layout.Paper.WidthMillimetres - 2 * m, layout.Paper.HeightMillimetres - 2 * m, 0.25); } - DrawContent(page, content, effectiveScale, offsetX, offsetY); + DrawContent(canvas, layout.Content, layout.EffectiveScale, layout.OffsetX, layout.OffsetY); // A title inside the frame: the level or view name and the scale. Drawn only when a font with the name's - // characters was found; the standard font cannot write Cyrillic. - if (pdf.Font != null && !string.IsNullOrEmpty(title)) + // characters was found; the standard PDF font cannot write Cyrillic. + if (canvas.CanDrawText && !string.IsNullOrEmpty(title)) { double margin = options.MarginMillimetres; - page.DrawText(title, margin + 3, paper.HeightMillimetres - margin - 8, 4.5); + canvas.DrawText(title, margin + 3, layout.Paper.HeightMillimetres - margin - 8, 4.5); // The scale the drawing is printed at: a plan reduced to fit a small page no longer prints at its nominal // scale, and the title must not claim it does. - int printedScale = (int)Math.Round(effectiveScale); - page.DrawText($"1:{printedScale}", margin + 3, paper.HeightMillimetres - margin - 15, 3.5, + int printedScale = (int)Math.Round(layout.EffectiveScale); + canvas.DrawText($"1:{printedScale}", margin + 3, layout.Paper.HeightMillimetres - margin - 15, 3.5, PdfTextAlignment.Left, 0.35); } } @@ -730,7 +825,7 @@ void Corner(double cx, double cy, double from) /// Draws the section marks of a plan: the trace of each section plane across the drawing, a tick at both /// ends and a bubble with the letter of the view, as a plan shows where it is cut. - private static void DrawSectionMarks(PdfPage page, PlanContent content, double scale, double originX, + private static void DrawSectionMarks(IPlanCanvas canvas, PlanContent content, double scale, double originX, double originY, IReadOnlyList<(double X, double Y, double Dx, double Dy, string Name)> marks) { double ToX(double x) => (x - content.MinX) / scale + originX; @@ -767,21 +862,21 @@ bool inside(double value, double direction, double low, double high) double x1 = px + dx * tMin, y1 = py + dy * tMin; double x2 = px + dx * tMax, y2 = py + dy * tMax; if (Math.Abs(x2 - x1) + Math.Abs(y2 - y1) < 10) continue; - page.DrawLine(x1, y1, x2, y2, 0.22, 0.2); + canvas.DrawLine(x1, y1, x2, y2, 0.22, 0.2); index++; string label = mark.Name.Length > 0 ? mark.Name[..1].ToUpperInvariant() : index.ToString(); foreach (var (x, y, otherX, otherY) in new[] { (x1, y1, x2, y2), (x2, y2, x1, y1) }) { double angle = Math.Atan2(y - otherY, x - otherX); // A short tick across the trace and the bubble at its end. - page.DrawLine(x - Math.Sin(angle) * 1.4, y + Math.Cos(angle) * 1.4, x + Math.Sin(angle) * 1.4, + canvas.DrawLine(x - Math.Sin(angle) * 1.4, y + Math.Cos(angle) * 1.4, x + Math.Sin(angle) * 1.4, y - Math.Cos(angle) * 1.4, 0.22, 0.2); - Bubble(page, x, y, label); + Bubble(canvas, x, y, label); } } } - private static void Bubble(PdfPage page, double x, double y, string name) + private static void Bubble(IPlanCanvas canvas, double x, double y, string name) { const double radius = 3.5; var points = new List<(double X, double Y)>(24); @@ -790,16 +885,16 @@ private static void Bubble(PdfPage page, double x, double y, string name) double angle = i * Math.PI * 2 / 24; points.Add((x + radius * Math.Cos(angle), y + radius * Math.Sin(angle))); } - page.DrawPolyline(points, 0.18, true, 1); - page.DrawText(name, x, y - 1.4, 3, PdfTextAlignment.Center); + canvas.DrawPolyline(points, 0.18, true, 1); + canvas.DrawText(name, x, y - 1.4, 3, PdfTextAlignment.Center); } /// Draws the dimension chains between the grid lines: a horizontal chain across the top of the plan and a /// vertical chain down its right side, each between neighbouring grids with the distance in millimetres. - private static void DimChains(PdfPage page, PlanContent content, Func toX, + private static void DimChains(IPlanCanvas canvas, PlanContent content, Func toX, Func toY) { - if (page.Owner.Font == null) return; + if (!canvas.CanDrawText) return; var xs = new List(); var ys = new List(); foreach (var grid in content.Grids) @@ -840,28 +935,28 @@ static List Dedupe(List values) double top = toY(wallMaxY + 550); if (xs.Count >= 2) { - page.DrawLine(toX(xs[0]), top, toX(xs[^1]), top, 0.15, 0.3); + canvas.DrawLine(toX(xs[0]), top, toX(xs[^1]), top, 0.15, 0.3); for (int i = 0; i < xs.Count; i++) { double x = toX(xs[i]); - page.DrawLine(x - 1.5, top - 1.5, x + 1.5, top + 1.5, 0.15, 0.3); + canvas.DrawLine(x - 1.5, top - 1.5, x + 1.5, top + 1.5, 0.15, 0.3); if (i == 0) continue; double millimetres = xs[i] - xs[i - 1]; - page.DrawText($"{millimetres:0}", (x + toX(xs[i - 1])) / 2, top + 1.2, 2.2, + canvas.DrawText($"{millimetres:0}", (x + toX(xs[i - 1])) / 2, top + 1.2, 2.2, PdfTextAlignment.Center, 0.25); } } double right = toX(wallMaxX + 550); if (ys.Count >= 2) { - page.DrawLine(right, toY(ys[0]), right, toY(ys[^1]), 0.15, 0.3); + canvas.DrawLine(right, toY(ys[0]), right, toY(ys[^1]), 0.15, 0.3); for (int i = 0; i < ys.Count; i++) { double y = toY(ys[i]); - page.DrawLine(right - 1.5, y - 1.5, right + 1.5, y + 1.5, 0.15, 0.3); + canvas.DrawLine(right - 1.5, y - 1.5, right + 1.5, y + 1.5, 0.15, 0.3); if (i == 0) continue; double millimetres = ys[i] - ys[i - 1]; - page.DrawTextRotated($"{millimetres:0}", right - 1.2, (y + toY(ys[i - 1])) / 2, 2.2, 90, + canvas.DrawTextRotated($"{millimetres:0}", right - 1.2, (y + toY(ys[i - 1])) / 2, 2.2, 90, PdfTextAlignment.Center, 0.25); } } @@ -870,28 +965,28 @@ static List Dedupe(List values) double bottom = toY(wallMinY - 550); if (xs.Count >= 2) { - page.DrawLine(toX(xs[0]), bottom, toX(xs[^1]), bottom, 0.15, 0.3); + canvas.DrawLine(toX(xs[0]), bottom, toX(xs[^1]), bottom, 0.15, 0.3); for (int i = 0; i < xs.Count; i++) { double x = toX(xs[i]); - page.DrawLine(x - 1.5, bottom - 1.5, x + 1.5, bottom + 1.5, 0.15, 0.3); + canvas.DrawLine(x - 1.5, bottom - 1.5, x + 1.5, bottom + 1.5, 0.15, 0.3); if (i == 0) continue; double millimetres = xs[i] - xs[i - 1]; - page.DrawText($"{millimetres:0}", (x + toX(xs[i - 1])) / 2, bottom - 3.4, 2.2, + canvas.DrawText($"{millimetres:0}", (x + toX(xs[i - 1])) / 2, bottom - 3.4, 2.2, PdfTextAlignment.Center, 0.25); } } double left = toX(wallMinX - 550); if (ys.Count >= 2) { - page.DrawLine(left, toY(ys[0]), left, toY(ys[^1]), 0.15, 0.3); + canvas.DrawLine(left, toY(ys[0]), left, toY(ys[^1]), 0.15, 0.3); for (int i = 0; i < ys.Count; i++) { double y = toY(ys[i]); - page.DrawLine(left - 1.5, y - 1.5, left + 1.5, y + 1.5, 0.15, 0.3); + canvas.DrawLine(left - 1.5, y - 1.5, left + 1.5, y + 1.5, 0.15, 0.3); if (i == 0) continue; double millimetres = ys[i] - ys[i - 1]; - page.DrawTextRotated($"{millimetres:0}", left - 0.8, (y + toY(ys[i - 1])) / 2, 2.2, 90, + canvas.DrawTextRotated($"{millimetres:0}", left - 0.8, (y + toY(ys[i - 1])) / 2, 2.2, 90, PdfTextAlignment.Center, 0.25); } } diff --git a/src/RvtIO/Print/PlanSvgWriter.cs b/src/RvtIO/Print/PlanSvgWriter.cs new file mode 100644 index 00000000..24782c4c --- /dev/null +++ b/src/RvtIO/Print/PlanSvgWriter.cs @@ -0,0 +1,358 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using RvtIO.Pdf; + +namespace RvtIO.Print; + +/// Shared 2D vector drawing surface in page millimetres (lower-left origin, +y up) consumed by +/// so PDF and SVG output share the exact same geometry, layout, and annotations. +internal interface IPlanCanvas +{ + bool CanDrawText { get; } + void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres = 0.25, double gray = 0); + void DrawArc(double centerX, double centerY, double radius, double startDegrees, double endDegrees, + double widthMillimetres = 0.25, double gray = 0); + void DrawRectangle(double x, double y, double width, double height, double widthMillimetres = 0.25, + double? fillGray = null); + void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widthMillimetres = 0.25, + bool closed = false, double? fillGray = null); + void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widthMillimetres, bool closed, + PdfColor? fillColor); + void DrawText(string text, double x, double y, double heightMillimetres = 3, + PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0); + void DrawTextRotated(string text, double x, double y, double heightMillimetres, double degrees, + PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0); +} + +internal sealed class PdfPlanCanvas(PdfPage page) : IPlanCanvas +{ + public bool CanDrawText => page.Owner.Font != null; + + public void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres = 0.25, double gray = 0) => + page.DrawLine(x1, y1, x2, y2, widthMillimetres, gray); + + public void DrawArc(double centerX, double centerY, double radius, double startDegrees, double endDegrees, + double widthMillimetres = 0.25, double gray = 0) => + page.DrawArc(centerX, centerY, radius, startDegrees, endDegrees, widthMillimetres, gray); + + public void DrawRectangle(double x, double y, double width, double height, double widthMillimetres = 0.25, + double? fillGray = null) => + page.DrawRectangle(x, y, width, height, widthMillimetres, fillGray); + + public void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widthMillimetres = 0.25, + bool closed = false, double? fillGray = null) => + page.DrawPolyline(points, widthMillimetres, closed, fillGray); + + public void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widthMillimetres, bool closed, + PdfColor? fillColor) => + page.DrawPolyline(points, widthMillimetres, closed, fillColor); + + public void DrawText(string text, double x, double y, double heightMillimetres = 3, + PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0) => + page.DrawText(text, x, y, heightMillimetres, alignment, gray); + + public void DrawTextRotated(string text, double x, double y, double heightMillimetres, double degrees, + PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0) => + page.DrawTextRotated(text, x, y, heightMillimetres, degrees, alignment, gray); +} + +/// Writes well-formed UTF-8 SVG XML in page millimetres (1 user unit = 1 mm, upper-left origin, +y down). +internal sealed class SvgPlanCanvas : IPlanCanvas, IDisposable +{ + private const string SvgNs = "http://www.w3.org/2000/svg"; + private const string RvtioNs = "https://ioextend.github.io/rvtio/svg"; + private const string FontFamily = "Arial, 'Segoe UI', Tahoma, 'DejaVu Sans', sans-serif"; + + private readonly XmlWriter _xml; + private readonly double _pageWidthMm; + private readonly double _pageHeightMm; + + public bool CanDrawText => true; + + public SvgPlanCanvas( + Stream output, + PdfPageSize paper, + int levelId, + string? title, + int nominalScale, + double effectiveScale, + double marginMm, + double offsetXMm, + double offsetYMm, + double modelMinXMm, + double modelMinYMm, + double modelMaxXMm, + double modelMaxYMm) + { + _pageWidthMm = paper.WidthMillimetres; + _pageHeightMm = paper.HeightMillimetres; + + _xml = XmlWriter.Create(output, new XmlWriterSettings + { + Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + Indent = true, + IndentChars = " ", + CloseOutput = false, + CheckCharacters = true, + }); + + string widthText = Num(_pageWidthMm); + string heightText = Num(_pageHeightMm); + + _xml.WriteStartDocument(); + _xml.WriteStartElement("svg", SvgNs); + _xml.WriteAttributeString("width", widthText + "mm"); + _xml.WriteAttributeString("height", heightText + "mm"); + _xml.WriteAttributeString("viewBox", $"0 0 {widthText} {heightText}"); + _xml.WriteAttributeString("data-scale", Num(effectiveScale)); + _xml.WriteAttributeString("data-nominal-scale", nominalScale.ToString(CultureInfo.InvariantCulture)); + _xml.WriteAttributeString("data-width-mm", widthText); + _xml.WriteAttributeString("data-height-mm", heightText); + _xml.WriteAttributeString("data-level-id", levelId.ToString(CultureInfo.InvariantCulture)); + + _xml.WriteStartElement("title", SvgNs); + _xml.WriteString(SanitizeXml(string.IsNullOrEmpty(title) ? $"Level {levelId.ToString(CultureInfo.InvariantCulture)}" : title)); + _xml.WriteEndElement(); + + _xml.WriteStartElement("metadata", SvgNs); + _xml.WriteStartElement("rvtio", "plan", RvtioNs); + _xml.WriteAttributeString("levelId", levelId.ToString(CultureInfo.InvariantCulture)); + if (!string.IsNullOrEmpty(title)) + _xml.WriteAttributeString("levelName", SanitizeXml(title)); + _xml.WriteAttributeString("nominalScale", nominalScale.ToString(CultureInfo.InvariantCulture)); + _xml.WriteAttributeString("scale", Num(effectiveScale)); + _xml.WriteAttributeString("printedScale", ((int)Math.Round(effectiveScale)).ToString(CultureInfo.InvariantCulture)); + _xml.WriteAttributeString("widthMm", widthText); + _xml.WriteAttributeString("heightMm", heightText); + _xml.WriteAttributeString("marginMm", Num(marginMm)); + _xml.WriteAttributeString("offsetXMm", Num(offsetXMm)); + _xml.WriteAttributeString("offsetYMm", Num(offsetYMm)); + _xml.WriteAttributeString("modelMinXMm", Num(modelMinXMm)); + _xml.WriteAttributeString("modelMinYMm", Num(modelMinYMm)); + _xml.WriteAttributeString("modelMaxXMm", Num(modelMaxXMm)); + _xml.WriteAttributeString("modelMaxYMm", Num(modelMaxYMm)); + _xml.WriteEndElement(); + _xml.WriteEndElement(); + + // White paper sheet matching the PDF background. + _xml.WriteStartElement("rect", SvgNs); + _xml.WriteAttributeString("x", "0"); + _xml.WriteAttributeString("y", "0"); + _xml.WriteAttributeString("width", widthText); + _xml.WriteAttributeString("height", heightText); + _xml.WriteAttributeString("fill", "#ffffff"); + _xml.WriteEndElement(); + } + + public void DrawLine(double x1, double y1, double x2, double y2, double widthMillimetres = 0.25, double gray = 0) + { + if (widthMillimetres < 0) return; + _xml.WriteStartElement("line", SvgNs); + _xml.WriteAttributeString("x1", Num(SvgX(x1))); + _xml.WriteAttributeString("y1", Num(SvgY(y1))); + _xml.WriteAttributeString("x2", Num(SvgX(x2))); + _xml.WriteAttributeString("y2", Num(SvgY(y2))); + _xml.WriteAttributeString("stroke", GrayHex(gray)); + _xml.WriteAttributeString("stroke-width", Num(widthMillimetres)); + _xml.WriteAttributeString("stroke-linecap", "butt"); + _xml.WriteEndElement(); + } + + public void DrawArc(double centerX, double centerY, double radius, double startDegrees, double endDegrees, + double widthMillimetres = 0.25, double gray = 0) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(radius); + if (endDegrees < startDegrees) (startDegrees, endDegrees) = (endDegrees, startDegrees); + double span = endDegrees - startDegrees; + if (span <= 0) return; + + if (span >= 359.999) + { + _xml.WriteStartElement("circle", SvgNs); + _xml.WriteAttributeString("cx", Num(SvgX(centerX))); + _xml.WriteAttributeString("cy", Num(SvgY(centerY))); + _xml.WriteAttributeString("r", Num(radius)); + _xml.WriteAttributeString("fill", "none"); + _xml.WriteAttributeString("stroke", GrayHex(gray)); + _xml.WriteAttributeString("stroke-width", Num(widthMillimetres)); + _xml.WriteEndElement(); + return; + } + + double a0 = startDegrees * Math.PI / 180; + double a1 = endDegrees * Math.PI / 180; + double sx = SvgX(centerX + radius * Math.Cos(a0)); + double sy = SvgY(centerY + radius * Math.Sin(a0)); + double ex = SvgX(centerX + radius * Math.Cos(a1)); + double ey = SvgY(centerY + radius * Math.Sin(a1)); + string r = Num(radius); + string largeArc = span > 180 ? "1" : "0"; + // Y-up counter-clockwise sweep maps to sweep-flag=0 in SVG's Y-down coordinates. + string d = $"M {Num(sx)} {Num(sy)} A {r} {r} 0 {largeArc} 0 {Num(ex)} {Num(ey)}"; + + _xml.WriteStartElement("path", SvgNs); + _xml.WriteAttributeString("d", d); + _xml.WriteAttributeString("fill", "none"); + _xml.WriteAttributeString("stroke", GrayHex(gray)); + _xml.WriteAttributeString("stroke-width", Num(widthMillimetres)); + _xml.WriteEndElement(); + } + + public void DrawRectangle(double x, double y, double width, double height, double widthMillimetres = 0.25, + double? fillGray = null) + { + if (width <= 0 || height <= 0) return; + bool stroke = widthMillimetres > 0; + if (!stroke && fillGray == null) return; + + _xml.WriteStartElement("rect", SvgNs); + _xml.WriteAttributeString("x", Num(SvgX(x))); + _xml.WriteAttributeString("y", Num(SvgY(y + height))); + _xml.WriteAttributeString("width", Num(width)); + _xml.WriteAttributeString("height", Num(height)); + _xml.WriteAttributeString("fill", fillGray is double fill ? GrayHex(fill) : "none"); + if (stroke) + { + _xml.WriteAttributeString("stroke", "#000000"); + _xml.WriteAttributeString("stroke-width", Num(widthMillimetres)); + } + else + { + _xml.WriteAttributeString("stroke", "none"); + } + _xml.WriteEndElement(); + } + + public void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widthMillimetres = 0.25, + bool closed = false, double? fillGray = null) => + DrawPolyline(points, widthMillimetres, closed, + fillGray is double fill ? new PdfColor(fill, fill, fill) : null); + + public void DrawPolyline(IReadOnlyList<(double X, double Y)> points, double widthMillimetres, bool closed, + PdfColor? fillColor) + { + ArgumentNullException.ThrowIfNull(points); + if (points.Count < 2) return; + bool stroke = widthMillimetres > 0; + if (!stroke && fillColor == null) return; + + var pts = new StringBuilder(points.Count * 16); + for (int i = 0; i < points.Count; i++) + { + if (i > 0) pts.Append(' '); + pts.Append(Num(SvgX(points[i].X))).Append(',').Append(Num(SvgY(points[i].Y))); + } + + _xml.WriteStartElement(closed ? "polygon" : "polyline", SvgNs); + _xml.WriteAttributeString("points", pts.ToString()); + _xml.WriteAttributeString("fill", fillColor is PdfColor color ? ColorHex(color) : "none"); + if (stroke) + { + _xml.WriteAttributeString("stroke", "#000000"); + _xml.WriteAttributeString("stroke-width", Num(widthMillimetres)); + _xml.WriteAttributeString("stroke-linejoin", "miter"); + } + else + { + _xml.WriteAttributeString("stroke", "none"); + } + _xml.WriteEndElement(); + } + + public void DrawText(string text, double x, double y, double heightMillimetres = 3, + PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0) + { + if (string.IsNullOrEmpty(text)) return; + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(heightMillimetres); + WriteTextElement(text, x, y, heightMillimetres, 0, alignment, gray); + } + + public void DrawTextRotated(string text, double x, double y, double heightMillimetres, double degrees, + PdfTextAlignment alignment = PdfTextAlignment.Left, double gray = 0) + { + if (string.IsNullOrEmpty(text)) return; + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(heightMillimetres); + WriteTextElement(text, x, y, heightMillimetres, degrees, alignment, gray); + } + + public void Dispose() + { + _xml.WriteEndElement(); // + _xml.WriteEndDocument(); + _xml.Flush(); + _xml.Dispose(); + } + + private void WriteTextElement(string text, double x, double y, double heightMillimetres, double degrees, + PdfTextAlignment alignment, double gray) + { + string sx = Num(SvgX(x)); + string sy = Num(SvgY(y)); + string anchor = alignment switch + { + PdfTextAlignment.Center => "middle", + PdfTextAlignment.Right => "end", + _ => "start", + }; + + _xml.WriteStartElement("text", SvgNs); + _xml.WriteAttributeString("x", sx); + _xml.WriteAttributeString("y", sy); + if (degrees != 0) + _xml.WriteAttributeString("transform", $"rotate({Num(-degrees)} {sx} {sy})"); + _xml.WriteAttributeString("font-family", FontFamily); + _xml.WriteAttributeString("font-size", Num(heightMillimetres)); + _xml.WriteAttributeString("fill", GrayHex(gray)); + _xml.WriteAttributeString("text-anchor", anchor); + _xml.WriteString(SanitizeXml(text)); + _xml.WriteEndElement(); + } + + private double SvgX(double xMm) => xMm; + private double SvgY(double yMm) => _pageHeightMm - yMm; + + private static string Num(double value) + { + double rounded = Math.Round(value, 4); + if (rounded == 0) rounded = 0; + return rounded.ToString("0.####", CultureInfo.InvariantCulture); + } + + private static string GrayHex(double gray) => ColorHex(new PdfColor(gray, gray, gray)); + + private static string ColorHex(PdfColor color) + { + byte r = (byte)Math.Clamp((int)Math.Round(color.R * 255), 0, 255); + byte g = (byte)Math.Clamp((int)Math.Round(color.G * 255), 0, 255); + byte b = (byte)Math.Clamp((int)Math.Round(color.B * 255), 0, 255); + return $"#{r:x2}{g:x2}{b:x2}"; + } + + private static string SanitizeXml(string text) + { + foreach (Rune rune in text.EnumerateRunes()) + { + if (!XmlConvert.IsXmlChar((char)Math.Min(rune.Value, 0xFFFF)) && rune.IsBmp) + goto Rebuild; + if (!IsValidXmlRune(rune.Value)) + goto Rebuild; + } + return text; + + Rebuild: + var sb = new StringBuilder(text.Length); + foreach (Rune rune in text.EnumerateRunes()) + { + if (IsValidXmlRune(rune.Value)) + sb.Append(rune.ToString()); + } + return sb.ToString(); + } + + private static bool IsValidXmlRune(int codePoint) => + codePoint is 0x9 or 0xA or 0xD + || (codePoint >= 0x20 && codePoint <= 0xD7FF) + || (codePoint >= 0xE000 && codePoint <= 0xFFFD) + || (codePoint >= 0x10000 && codePoint <= 0x10FFFF); +} diff --git a/tests/RvtIO.Tests/PlanSvgTests.cs b/tests/RvtIO.Tests/PlanSvgTests.cs new file mode 100644 index 00000000..52451194 --- /dev/null +++ b/tests/RvtIO.Tests/PlanSvgTests.cs @@ -0,0 +1,350 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using RvtIO.BuiltIns; +using RvtIO.Model; +using RvtIO.Parsing; +using RvtIO.Pdf; +using RvtIO.Print; +using Xunit; + +namespace RvtIO.Tests; + +public class PlanSvgTests +{ + private static readonly XNamespace SvgNs = "http://www.w3.org/2000/svg"; + private static readonly XNamespace RvtioNs = "https://ioextend.github.io/rvtio/svg"; + private const double PtToMm = 25.4 / 72.0; + + private static void Add(Element element, BuiltInParameter id, StorageType storage, object value) => + element.Parameters.Add(BipHelpers.MakeBipParam((int)id, id.ToString(), storage, value)); + + private static Element Level(int id, string name, double elevationFeet) + { + var level = new Element { Id = id, Name = name, CategoryId = (int)BuiltInCategory.OST_Levels }; + Add(level, BuiltInParameter.LEVEL_ELEV, StorageType.Double, elevationFeet); + return level; + } + + private static Element Wall(int id, int levelId, double x1, double y1, double x2, double y2, double widthFeet = 1.0) + { + var wall = new Element + { + Id = id, + CategoryId = (int)BuiltInCategory.OST_Walls, + Location = new LocationCurve + { + CurveType = "Line", + StartPoint = [x1, y1, 0], + EndPoint = [x2, y2, 0], + }, + }; + Add(wall, BuiltInParameter.LEVEL_PARAM, StorageType.ElementId, levelId); + Add(wall, BuiltInParameter.WALL_ATTR_WIDTH_PARAM, StorageType.Double, widthFeet); + return wall; + } + + private static Element Column(int id, int levelId, double minX, double minY, double maxX, double maxY) + { + var column = new Element + { + Id = id, + CategoryId = (int)BuiltInCategory.OST_Columns, + BoundingBox = [minX, minY, 0, maxX, maxY, 10], + }; + Add(column, BuiltInParameter.LEVEL_PARAM, StorageType.ElementId, levelId); + return column; + } + + private static Element Grid(int id, string name, double x1, double y1, double x2, double y2) => new() + { + Id = id, + Name = name, + CategoryId = (int)BuiltInCategory.OST_Grids, + Location = new LocationCurve { CurveType = "Line", StartPoint = [x1, y1, 0], EndPoint = [x2, y2, 0] }, + }; + + private static Element Door(int id, int hostId, double centerXFeet, string mark) + { + var door = new Element + { + Id = id, + CategoryId = (int)BuiltInCategory.OST_Doors, + HostId = hostId, + OwnSingleFamilyCutout = (300, hostId, + new double[] { 1, 0, 0, 0, 1, 0, 0, 0, 1, centerXFeet, 0, 0 }, + new FamilyCutLoopData( + [[-0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 3.0], [-0.5, 0.0, 3.0]], + [0.0, 1.0, 0.0], 0)), + }; + Add(door, BuiltInParameter.ALL_MODEL_MARK, StorageType.String, mark); + return door; + } + + private static RvtDocument SamplePlanDocument(string levelName = "Уровень 1") => + RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(10, levelName, 0), + Wall(100, 10, 0, 0, 20, 0, widthFeet: 1.0), + Wall(101, 10, 20, 0, 20, 12, widthFeet: 1.0), + Door(200, 100, 8.0, "D-1"), + Column(300, 10, 4, 4, 5, 5), + Grid(400, "А", -50, 0, 50, 0), + Grid(401, "1", 0, -50, 0, 50), + ], + }); + + [Fact] + public void RenderSvg_MatchesPdfCoordinatesLayoutPaperAndScale() + { + var document = SamplePlanDocument("Level 1"); + var options = new PlanPrintOptions { PaperSize = PdfPageSize.A3.Landscape }; + + PdfDocument pdf = PlanPrinter.Render(document, levelId: 10, scale: 100, options); + string svgText = PlanPrinter.RenderSvg(document, levelId: 10, scale: 100, options); + + using var ms = new MemoryStream(); + pdf.Save(ms); + string pdfStream = PdfTestContent.Read(ms.ToArray()); + + XDocument xml = XDocument.Parse(svgText); + XElement svg = xml.Root!; + Assert.Equal("svg", svg.Name.LocalName); + Assert.Equal("420mm", svg.Attribute("width")?.Value); + Assert.Equal("297mm", svg.Attribute("height")?.Value); + Assert.Equal("0 0 420 297", svg.Attribute("viewBox")?.Value); + Assert.Equal("100", svg.Attribute("data-scale")?.Value); + Assert.Equal("100", svg.Attribute("data-nominal-scale")?.Value); + Assert.Equal("420", svg.Attribute("data-width-mm")?.Value); + Assert.Equal("297", svg.Attribute("data-height-mm")?.Value); + + XElement meta = svg.Descendants(RvtioNs + "plan").Single(); + Assert.Equal("10", meta.Attribute("levelId")?.Value); + Assert.Equal("100", meta.Attribute("scale")?.Value); + Assert.Equal("420", meta.Attribute("widthMm")?.Value); + Assert.Equal("297", meta.Attribute("heightMm")?.Value); + + double H = 297.0; + var svgPolygons = svg.Elements(SvgNs + "polygon").ToList(); + var svgLines = svg.Elements(SvgNs + "line").ToList(); + var svgRects = svg.Elements(SvgNs + "rect").ToList(); + var svgPaths = svg.Elements(SvgNs + "path").ToList(); + + // Background + frame + column = 3 rects (white sheet + frame border + column). + Assert.Equal(3, svgRects.Count); + XElement colSvg = svgRects[2]; + double colSvgX = double.Parse(colSvg.Attribute("x")!.Value, CultureInfo.InvariantCulture); + double colSvgY = double.Parse(colSvg.Attribute("y")!.Value, CultureInfo.InvariantCulture); + double colSvgW = double.Parse(colSvg.Attribute("width")!.Value, CultureInfo.InvariantCulture); + double colSvgH = double.Parse(colSvg.Attribute("height")!.Value, CultureInfo.InvariantCulture); + + // Extract column rectangle (third "re" after page border/frame? First "re" in PDF content is frame, column is later "re B"). + var pdfRectMatches = Regex.Matches(pdfStream, @"([\d.-]+) ([\d.-]+) ([\d.-]+) ([\d.-]+) re B"); + Assert.True(pdfRectMatches.Count >= 1); + var lastRect = pdfRectMatches[^1]; + double pdfColX = double.Parse(lastRect.Groups[1].Value, CultureInfo.InvariantCulture) * PtToMm; + double pdfColY = double.Parse(lastRect.Groups[2].Value, CultureInfo.InvariantCulture) * PtToMm; + double pdfColW = double.Parse(lastRect.Groups[3].Value, CultureInfo.InvariantCulture) * PtToMm; + double pdfColH = double.Parse(lastRect.Groups[4].Value, CultureInfo.InvariantCulture) * PtToMm; + + Assert.Equal(pdfColX, colSvgX, 2); + Assert.Equal(H - (pdfColY + pdfColH), colSvgY, 2); + Assert.Equal(pdfColW, colSvgW, 2); + Assert.Equal(pdfColH, colSvgH, 2); + + // Walls cut by the door: 2 stretches on wall 100 + 1 wall 101 -> 3 wall poche polygons (#b8b8b8 = 0.72 gray). + var wallPolygons = svgPolygons.Where(p => p.Attribute("fill")?.Value == "#b8b8b8").ToList(); + Assert.Equal(3, wallPolygons.Count); + + // Compare first wall polygon vertices against PDF polygon vertices! + var pdfWallMatch = Regex.Match(pdfStream, + @"0\.72 0\.72 0\.72 rg\s+([\d.-]+) ([\d.-]+) m ([\d.-]+) ([\d.-]+) l ([\d.-]+) ([\d.-]+) l ([\d.-]+) ([\d.-]+) l h B"); + Assert.True(pdfWallMatch.Success); + double pdfWx0 = double.Parse(pdfWallMatch.Groups[1].Value, CultureInfo.InvariantCulture) * PtToMm; + double pdfWy0 = double.Parse(pdfWallMatch.Groups[2].Value, CultureInfo.InvariantCulture) * PtToMm; + string[] firstSvgVerts = wallPolygons[0].Attribute("points")!.Value.Split(' ')[0].Split(','); + double svgWx0 = double.Parse(firstSvgVerts[0], CultureInfo.InvariantCulture); + double svgWy0 = double.Parse(firstSvgVerts[1], CultureInfo.InvariantCulture); + Assert.Equal(pdfWx0, svgWx0, 2); + Assert.Equal(H - pdfWy0, svgWy0, 2); + + // Door leaf + quarter arc + grids present. + Assert.Single(svgPaths); + Assert.Contains(" A ", svgPaths[0].Attribute("d")!.Value); + Assert.True(svgLines.Count >= 3); // 2 grids + door leaf + } + + [Fact] + public void RenderSvg_AutoFitsOversizedPlanAndRecordsEffectiveScaleInMetadataAndText() + { + // A huge 200 ft (~61 m) wall at 1:100 (~610 mm) will be scaled down to fit A4 Landscape (297x210). + var doc = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = [Level(1, "Большой план", 0), Wall(100, 1, 0, 0, 200, 0)], + }); + + string svg = PlanPrinter.RenderSvg(doc, levelId: 1, scale: 100, new PlanPrintOptions { PaperSize = PdfPageSize.A4.Landscape }); + XDocument xml = XDocument.Parse(svg); + XElement root = xml.Root!; + + double nominal = double.Parse(root.Attribute("data-nominal-scale")!.Value, CultureInfo.InvariantCulture); + double effective = double.Parse(root.Attribute("data-scale")!.Value, CultureInfo.InvariantCulture); + Assert.Equal(100, nominal); + Assert.True(effective > 200, $"Expected downscaled effective scale > 200, got {effective}"); + Assert.Equal("297", root.Attribute("data-width-mm")?.Value); + Assert.Equal("210", root.Attribute("data-height-mm")?.Value); + + string scaleText = root.Elements(SvgNs + "text").Select(t => t.Value).First(v => v.StartsWith("1:", StringComparison.Ordinal)); + Assert.Equal($"1:{(int)Math.Round(effective)}", scaleText); + } + + [Fact] + public void RenderSvg_SupportsCyrillicXmlSpecialCharactersAndControlCharSanitization() + { + const string trickyLevel = "План <Этаж 1> & \"Корпус\" 'А'\u0001"; + const string trickyGrid = "Ось & <1>"; + var doc = RvtDocument.FromInfo(new RevitFileInfo + { + Elements = + [ + Level(10, trickyLevel, 0), + Wall(100, 10, 0, 0, 20, 0), + Door(200, 100, 10.0, "Д<1>&\"2\""), + Grid(400, trickyGrid, -20, 0, 40, 0), + ], + }); + + string svg = PlanPrinter.RenderSvg(doc, levelId: 10, scale: 100); + XDocument xml = XDocument.Parse(svg); + var texts = xml.Root!.Elements(SvgNs + "text").Select(t => t.Value).ToList(); + + Assert.Contains("План <Этаж 1> & \"Корпус\" 'А'", texts); + Assert.Contains("Ось & <1>", texts); + Assert.Contains("Д<1>&\"2\"", texts); + Assert.Contains("1:100", texts); + Assert.Equal("План <Этаж 1> & \"Корпус\" 'А'", xml.Root!.Element(SvgNs + "title")!.Value); + } + + [Fact] + public void RenderSvg_ThrowsOnEmptyPlanOrMissingLevel() + { + var emptyDoc = RvtDocument.FromInfo(new RevitFileInfo { Elements = [Level(1, "Пустой", 0)] }); + Assert.Throws(() => PlanPrinter.RenderSvg(emptyDoc)); + Assert.Throws(() => PlanPrinter.RenderSvg(emptyDoc, levelId: 1)); + + var missingLevelDoc = SamplePlanDocument(); + Assert.Throws(() => PlanPrinter.RenderSvg(missingLevelDoc, levelId: 9999)); + Assert.Throws(() => PlanPrinter.RenderSvg(missingLevelDoc, levelId: 10, scale: 0)); + } + + [Fact] + public void WriteSvg_MatchesTheStringApiAndLeavesTheStreamOpen() + { + var doc = SamplePlanDocument(); + var options = new PlanPrintOptions { MarginMillimetres = 0 }; + using var output = new MemoryStream(); + + PlanPrinter.WriteSvg(doc, output, options: options); + + Assert.True(output.CanWrite); + Assert.Equal(PlanPrinter.RenderSvg(doc, null, options: options), + System.Text.Encoding.UTF8.GetString(output.ToArray())); + } + + [Theory] + [InlineData(0, 297, 10)] + [InlineData(210, -1, 10)] + [InlineData(double.NaN, 297, 10)] + [InlineData(210, double.PositiveInfinity, 10)] + [InlineData(210, 297, -1)] + [InlineData(210, 297, double.NaN)] + [InlineData(210, 297, double.PositiveInfinity)] + [InlineData(210, 297, 105)] + [InlineData(297, 210, 106)] + [InlineData(double.Epsilon, 297, 0)] + public void PlanPrinting_RejectsInvalidLayoutBeforeWritingSvg(double width, double height, double margin) + { + var doc = SamplePlanDocument(); + var options = new PlanPrintOptions { PaperSize = new PdfPageSize(width, height), MarginMillimetres = margin }; + using var output = new MemoryStream(); + + Assert.Throws("options", () => PlanPrinter.WriteSvg(doc, output, options: options)); + Assert.Equal(0, output.Length); + Assert.Throws("options", () => PlanPrinter.Render(doc, options: options)); + } + + [Fact] + public void CliPrintCommand_WritesValidSvgAndHandlesErrors() + { + string dir = Path.Combine(Path.GetTempPath(), "rvtio-print-svg-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + // Missing level & empty document on a readable compound file: use CliExitCodeTests helper. + string rvt = Path.Combine(dir, "minimal.rvt"); + CliExitCodeTests.WriteSyntheticRvt(rvt); + string emptySvg = Path.Combine(dir, "empty.svg"); + var err = new StringWriter(); + int exitEmpty = RvtIO.Cli.PrintCommand.Run([rvt, emptySvg], TextWriter.Null, err); + Assert.Equal(RvtExitCodes.DecodeError, exitEmpty); + Assert.False(File.Exists(emptySvg)); + + // View/sheet flags are refused when .svg is requested (level plan scope only). + string viewSvg = Path.Combine(dir, "view.svg"); + var errView = new StringWriter(); + int exitView = RvtIO.Cli.PrintCommand.Run([rvt, viewSvg, "--view", "Level 1"], TextWriter.Null, errView); + Assert.Equal(RvtExitCodes.Usage, exitView); + Assert.Contains("level plan", errView.ToString()); + } + finally + { + Directory.Delete(dir, true); + } + } + + [SkippableFact] + public void SampleRvtFilesFromTestRoots_RenderMatchingPdfAndSvgPlansAndRejectMissingLevel() + { + string? firstRvt = TestFiles.Roots() + .SelectMany(root => Directory.EnumerateFiles(root, "*.rvt", SearchOption.AllDirectories)) + .OrderBy(p => p, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(); + if (firstRvt is null) + throw new SkipException("No .rvt fixture files found under RVTIO_TEST_FILES."); + + var doc = RvtDocument.Open(firstRvt); + var levels = PlanPrinter.Levels(doc); + if (levels.Count == 0) + throw new SkipException("Sample .rvt has no printable level."); + + string dir = Path.Combine(Path.GetTempPath(), "rvtio-print-svg-sample-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + string pdfPath = Path.Combine(dir, "plan.pdf"); + string svgPath = Path.Combine(dir, "plan.svg"); + string levelArg = levels[0].LevelId.ToString(CultureInfo.InvariantCulture); + + var pdfErr = new StringWriter(); + Assert.Equal(RvtExitCodes.Success, RvtIO.Cli.PrintCommand.Run([firstRvt, pdfPath, "--level", levelArg, "--scale", "100"], TextWriter.Null, pdfErr)); + var svgErr = new StringWriter(); + Assert.Equal(RvtExitCodes.Success, RvtIO.Cli.PrintCommand.Run([firstRvt, svgPath, "--level", levelArg, "--scale", "100"], TextWriter.Null, svgErr)); + + XDocument xml = XDocument.Parse(File.ReadAllText(svgPath)); + Assert.Equal("svg", xml.Root!.Name.LocalName); + Assert.Equal(levelArg, xml.Root.Attribute("data-level-id")?.Value); + + string missingSvg = Path.Combine(dir, "missing.svg"); + var missingErr = new StringWriter(); + Assert.Equal(RvtExitCodes.Usage, RvtIO.Cli.PrintCommand.Run([firstRvt, missingSvg, "--level", "NoSuchLevel_999"], TextWriter.Null, missingErr)); + Assert.False(File.Exists(missingSvg)); + Assert.Contains("No printable level", missingErr.ToString()); + } + finally + { + Directory.Delete(dir, true); + } + } +}