Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

CAD → PDF: one page per paper-space layout, through its viewports (#172)

cre8ive-marketing8b23a8604cb7
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 7add95c5..2a942458 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -850,10 +850,16 @@ and writes the files; Filee's own renderer draws them with SkiaSharp (one drawin
some 3D and underlay data) are not written; degenerate dimensions it cannot measure are left out of DWG output
instead of failing the file.
- **What is drawn**: model space seen from the top (Z is dropped). If model space has nothing visible, the active
- layout (paper space) is drawn instead; viewports inside it are not followed. The page is fitted to the extents of
+ layout (paper space) is drawn instead (for a PDF, every layout, see below). The page is fitted to the extents of
what is actually drawn — the header's EXTMIN/EXTMAX are ignored, so drawings far from the origin still fill it.
- PDF: an ISO A3 sheet (A4 or Letter when the preset asks for it), landscape when the drawing is wider than tall,
10 mm margins (or the preset's margin). Vector paths, text as text with embedded fonts.
+ - PDF of a drawing with paper-space layouts (#172): **one page per layout** with something on it, in tab order,
+ each fitted like the one-page PDF to the layout's drawing and viewport frames. Inside each viewport model space
+ is drawn at the viewport's scale (height ÷ view height) around its view centre, clipped to the frame, under the
+ layout's own drawing (title block, notes). Not followed: twisted views (drawn untwisted), layers frozen per
+ viewport, non-rectangular viewports and the layout's plot settings (paper size, plot scale). Images and SVG stay
+ one picture of model space.
- SVG: the drawing's aspect ratio with a 420 mm (A3) long edge at 96 px/inch, white background, text as `<text>`.
- Images: the same page rendered at the preset's render resolution (150 dpi → 2480 px on the long edge, at most
12 000 px / 80 MP), then the preset's image options (resize, grayscale, quality, DPI) as for other images.
diff --git a/src/Filee.Engines/Cad/CadConverter.cs b/src/Filee.Engines/Cad/CadConverter.cs
index 9b68c647..517a7f05 100644
--- a/src/Filee.Engines/Cad/CadConverter.cs
+++ b/src/Filee.Engines/Cad/CadConverter.cs
@@ -17,7 +17,8 @@ namespace Filee.Engines.Cad;
/// <remarks>
/// Rendering draws model space as seen from the top (the active layout when model space is empty), fitted to the
/// page: PDF on an A3 sheet (A4 / Letter when the preset says so), SVG and images with the drawing's aspect ratio
-/// on a white background. See docs/ENGINES.md for what is and is not drawn.
+/// on a white background. A PDF of a drawing with paper-space layouts has one page per layout instead, with model
+/// space shown through each layout's viewports. See docs/ENGINES.md for what is and is not drawn.
/// </remarks>
public sealed class CadConverter(ILogger? logger = null) : IConverter, IImageTransformer
{
@@ -66,7 +67,11 @@ public sealed class CadConverter(ILogger? logger = null) : IConverter, IImageTra
var scene = CadSceneBuilder.Build(document, cancellationToken);
Report(step.InputPath, scene);
- if (scene.Items.Count == 0)
+ // A PDF follows the layouts like a plot of every sheet; images and SVG stay one picture of model space.
+ var sheets = step.To == "pdf" ? CadSceneBuilder.BuildLayouts(document, cancellationToken) : [];
+ if (sheets.Count > 0)
+ _logger.LogInformation("{File}: {Count} layout(s), one PDF page each", step.InputPath, sheets.Count);
+ if (scene.Items.Count == 0 && sheets.Count == 0)
throw new InvalidDataException(scene.Skipped.Count > 0
? $"The drawing only contains objects Filee cannot draw ({string.Join(", ", scene.Skipped.Keys)})."
: "The drawing has nothing visible to draw: model space and the layout are empty, or every entity is on a layer that is off, frozen or not plotted.");
@@ -80,7 +85,12 @@ public sealed class CadConverter(ILogger? logger = null) : IConverter, IImageTra
{
case "pdf":
using (var stream = File.Create(output))
- CadRenderer.WritePdf(scene, step.Preset.Pdf, Path.GetFileNameWithoutExtension(step.InputPath), stream);
+ {
+ if (sheets.Count > 0)
+ CadRenderer.WritePdf(sheets, scene, step.Preset.Pdf, Path.GetFileNameWithoutExtension(step.InputPath), stream);
+ else
+ CadRenderer.WritePdf(scene, step.Preset.Pdf, Path.GetFileNameWithoutExtension(step.InputPath), stream);
+ }
break;
case "svg":
using (var stream = File.Create(output))
diff --git a/src/Filee.Engines/Cad/CadRenderer.cs b/src/Filee.Engines/Cad/CadRenderer.cs
index 3e404972..444d3279 100644
--- a/src/Filee.Engines/Cad/CadRenderer.cs
+++ b/src/Filee.Engines/Cad/CadRenderer.cs
@@ -46,6 +46,19 @@ internal sealed class PageLayout
return new SKPoint((float)q.X, (float)q.Y);
}
+ /// <summary>
+ /// The same page seen through a viewport: model space at <paramref name="scale"/> paper units per model unit, with
+ /// <paramref name="viewCenter"/> landing on the paper point <paramref name="paperCenter"/>. Line weights stay in
+ /// millimetres of paper.
+ /// </summary>
+ public PageLayout Through(double scale, Vec2 viewCenter, Vec2 paperCenter)
+ {
+ var center = ToPage(paperCenter);
+ var modelScale = Scale * scale;
+ return new PageLayout(Width, Height, UnitsPerMm, modelScale,
+ center.X - viewCenter.X * modelScale, center.Y + viewCenter.Y * modelScale);
+ }
+
/// <summary>The WCS point shown at page position (x, y).</summary>
public Vec2 FromPage(double x, double y) => new((x - _offsetX) / Scale, -(y - _offsetY) / Scale);
@@ -140,6 +153,44 @@ internal static class CadRenderer
document.Close();
}
+ /// <summary>
+ /// Writes a vector PDF with one page per layout (#172): each page is fitted like a one-page PDF to the layout's
+ /// drawing and viewport frames; inside each frame model space is drawn at the viewport's scale, clipped to it,
+ /// under the layout's own drawing (title block, notes).
+ /// </summary>
+ public static void WritePdf(IReadOnlyList<LayoutSheet> sheets, CadScene model, PdfOptions options, string title, Stream output)
+ {
+ var metadata = new SKDocumentPdfMetadata
+ {
+ Title = title,
+ Creator = "Filee",
+ Producer = "Filee (SkiaSharp)",
+ RasterDpi = 300,
+ Creation = DateTime.Now,
+ Modified = DateTime.Now,
+ };
+ using var document = SKDocument.CreatePdf(output, metadata);
+ foreach (var sheet in sheets)
+ {
+ var page = PageLayout.ForPdf(sheet.Extents, options);
+ var canvas = document.BeginPage(page.Width, page.Height);
+ foreach (var view in sheet.Viewports)
+ {
+ var corner1 = page.Point(new Vec2(view.Frame.MinX, view.Frame.MinY));
+ var corner2 = page.Point(new Vec2(view.Frame.MaxX, view.Frame.MaxY));
+ canvas.Save();
+ canvas.ClipRect(new SKRect(Math.Min(corner1.X, corner2.X), Math.Min(corner1.Y, corner2.Y),
+ Math.Max(corner1.X, corner2.X), Math.Max(corner1.Y, corner2.Y)));
+ var center = new Vec2((view.Frame.MinX + view.Frame.MaxX) / 2, (view.Frame.MinY + view.Frame.MaxY) / 2);
+ Draw(canvas, model, page.Through(view.Scale, view.ViewCenter, center), background: false);
+ canvas.Restore();
+ }
+ Draw(canvas, sheet.Paper, page, background: false);
+ document.EndPage();
+ }
+ document.Close();
+ }
+
/// <summary>Writes an SVG (pixel units at 96 dpi) with a white background.</summary>
public static void WriteSvg(CadScene scene, Stream output)
{
diff --git a/src/Filee.Engines/Cad/CadScene.cs b/src/Filee.Engines/Cad/CadScene.cs
index 4dba8c0d..0cf13899 100644
--- a/src/Filee.Engines/Cad/CadScene.cs
+++ b/src/Filee.Engines/Cad/CadScene.cs
@@ -96,3 +96,28 @@ internal sealed class CadScene
/// <summary>Which space was drawn: "model" or the layout name.</summary>
public string Space { get; set; } = "model";
}
+
+/// <summary>A paper-space layout to print as one page: its own drawing and its viewports onto model space.</summary>
+internal sealed record LayoutSheet(string Name, CadScene Paper, IReadOnlyList<ViewportView> Viewports)
+{
+ /// <summary>What the page has to show: the layout's own drawing and every viewport's frame.</summary>
+ public Box2 Extents
+ {
+ get
+ {
+ var box = Paper.Extents;
+ foreach (var view in Viewports)
+ {
+ box.Add(new Vec2(view.Frame.MinX, view.Frame.MinY));
+ box.Add(new Vec2(view.Frame.MaxX, view.Frame.MaxY));
+ }
+ return box;
+ }
+ }
+}
+
+/// <summary>
+/// A viewport on a layout: its frame in paper units, the model-space point at its centre and how many paper units one
+/// model unit takes (the viewport's scale).
+/// </summary>
+internal readonly record struct ViewportView(Box2 Frame, Vec2 ViewCenter, double Scale);
diff --git a/src/Filee.Engines/Cad/CadSceneBuilder.cs b/src/Filee.Engines/Cad/CadSceneBuilder.cs
index 57b440f4..80e310c0 100644
--- a/src/Filee.Engines/Cad/CadSceneBuilder.cs
+++ b/src/Filee.Engines/Cad/CadSceneBuilder.cs
@@ -4,6 +4,7 @@
using ACadSharp;
using ACadSharp.Entities;
+using ACadSharp.Objects;
using ACadSharp.Tables;
using SkiaSharp;
using AcadColor = ACadSharp.Color;
@@ -58,6 +59,39 @@ internal sealed partial class CadSceneBuilder
return builder._scene;
}
+ /// <summary>
+ /// The paper-space layouts that have something on them, in tab order (#172): each one's own entities (title block,
+ /// notes) and the viewports that show model space. Empty when the drawing has none, so it is drawn as before.
+ /// </summary>
+ public static List<LayoutSheet> BuildLayouts(CadDocument document, CancellationToken cancellationToken)
+ {
+ var sheets = new List<LayoutSheet>();
+ foreach (var layout in document.Layouts
+ .Where(l => l.Name != Layout.ModelLayoutName && l.AssociatedBlock is not null)
+ .OrderBy(l => l.TabOrder))
+ {
+ var builder = new CadSceneBuilder(document, cancellationToken);
+ builder._scene.Space = layout.Name;
+ builder.DrawEntities(layout.AssociatedBlock!.Entities, DrawContext.Root);
+ // The viewport that is the sheet itself (RepresentsPaper) shows no model space. Twisted views are drawn
+ // untwisted.
+ var views = layout.AssociatedBlock.Entities.OfType<Viewport>()
+ .Where(v => !v.RepresentsPaper && v.Width > 0 && v.Height > 0 && v.ViewHeight > 0)
+ .Select(v =>
+ {
+ var frame = Box2.Empty;
+ frame.Add(new Vec2(v.Center.X - v.Width / 2, v.Center.Y - v.Height / 2));
+ frame.Add(new Vec2(v.Center.X + v.Width / 2, v.Center.Y + v.Height / 2));
+ return new ViewportView(frame, new Vec2(v.ViewCenter.X, v.ViewCenter.Y), v.Height / v.ViewHeight);
+ })
+ .Where(v => !v.Frame.IsEmpty)
+ .ToList();
+ if (builder._scene.Items.Count > 0 || views.Count > 0)
+ sheets.Add(new LayoutSheet(layout.Name, builder._scene, views));
+ }
+ return sheets;
+ }
+
private static BlockRecord? TryGetPaperSpace(CadDocument document) =>
document.BlockRecords.TryGetValue(BlockRecord.PaperSpaceName, out var paper) ? paper : null;
diff --git a/tests/Filee.Engines.Tests/CadLayoutTests.cs b/tests/Filee.Engines.Tests/CadLayoutTests.cs
new file mode 100644
index 00000000..aa3d18b5
--- /dev/null
+++ b/tests/Filee.Engines.Tests/CadLayoutTests.cs
@@ -0,0 +1,112 @@
+// CAD → PDF with one page per paper-space layout (issue #172): each layout's own drawing, and model space through its
+// viewports at their scale, clipped to them.
+
+using ACadSharp;
+using ACadSharp.Entities;
+using ACadSharp.Objects;
+using ACadSharp.Tables;
+using CSMath;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Cad;
+using PDFtoImage;
+using PdfSharp.Pdf.IO;
+using SkiaSharp;
+
+#pragma warning disable CA1416
+
+namespace Filee.Engines.Tests;
+
+public class CadLayoutTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ /// <summary>
+ /// Model space: a blue 100 × 100 square at the origin and a blue circle far right at (1000, 0). Two layouts on
+ /// 420 × 297 paper, each with a border and one viewport: "Plan" shows the square at 1:1, "Detail" the circle at 2:1.
+ /// </summary>
+ private static CadDocument TwoSheets()
+ {
+ var doc = new CadDocument();
+ var drawing = new Layer("Drawing") { Color = CadBuilder.Visible };
+ doc.Layers.Add(drawing);
+ foreach (var (a, b) in new[] { ((0, 0), (100, 0)), ((100, 0), (100, 100)), ((100, 100), (0, 100)), ((0, 100), (0, 0)) })
+ CadBuilder.Add(doc, drawing, new Line(new XYZ(a.Item1, a.Item2, 0), new XYZ(b.Item1, b.Item2, 0)));
+ CadBuilder.Add(doc, drawing, new Circle(new XYZ(1000, 0, 0), 20));
+
+ AddSheet(doc, "Plan", 1, new XY(50, 50), viewHeight: 150);
+ AddSheet(doc, "Detail", 2, new XY(1000, 0), viewHeight: 75);
+ return doc;
+ }
+
+ private static void AddSheet(CadDocument doc, string name, int tab, XY viewCenter, double viewHeight)
+ {
+ var layout = new Layout(name) { TabOrder = tab };
+ doc.Layouts.Add(layout);
+ var block = layout.AssociatedBlock;
+ // The sheet border (title block) in paper space, and one 200 × 150 viewport in the middle of the sheet.
+ block.Entities.Add(new LwPolyline(new LwPolyline.Vertex(0, 0), new LwPolyline.Vertex(420, 0), new LwPolyline.Vertex(420, 297),
+ new LwPolyline.Vertex(0, 297)) { IsClosed = true });
+ block.Entities.Add(new Viewport
+ {
+ Center = new XYZ(210, 148.5, 0), Width = 200, Height = 150, ViewCenter = viewCenter, ViewHeight = viewHeight,
+ });
+ }
+
+ [Fact]
+ public void Each_layout_with_something_on_it_is_a_sheet_in_tab_order()
+ {
+ var sheets = CadSceneBuilder.BuildLayouts(TwoSheets(), TestContext.Current.CancellationToken);
+
+ Assert.Equal(["Plan", "Detail"], sheets.Select(s => s.Name));
+ var detail = Assert.Single(sheets[1].Viewports);
+ Assert.Equal(2, detail.Scale, 9); // 150 paper units show 75 model units
+ Assert.Equal((110.0, 73.5, 310.0, 223.5), (detail.Frame.MinX, detail.Frame.MinY, detail.Frame.MaxX, detail.Frame.MaxY));
+ Assert.Equal(420, sheets[0].Extents.Width, 9);
+
+ // A drawing without layouts of its own (only the empty default one) keeps its single page.
+ Assert.Empty(CadSceneBuilder.BuildLayouts(CadBuilder.Sample(), TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public async Task A_pdf_has_one_page_per_layout_with_model_space_in_the_viewports()
+ {
+ var dxf = CadBuilder.SaveDxf(TwoSheets(), fx.NewFolder(), "sheets.dxf");
+
+ var job = await fx.ConvertAsync([dxf], new Preset { TargetFormat = "pdf" });
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var pdf = job.Outputs.Single();
+ using (var document = PdfReader.Open(pdf, PdfDocumentOpenMode.Import))
+ Assert.Equal(2, document.PageCount);
+
+ // Blue model-space lines show up inside the viewport (the middle of the sheet) on both pages, and nowhere
+ // outside it: the square's far corner and the circle are clipped to their frames.
+ for (var page = 0; page < 2; page++)
+ {
+ Assert.True(Blue(pdf, page, 0.27, 0.26, 0.73, 0.74) > 20, $"page {page + 1}: model space in the viewport");
+ Assert.Equal(0, Blue(pdf, page, 0.02, 0.02, 0.25, 0.24)); // outside the frame, only the black border
+ }
+ }
+
+ [Fact]
+ public async Task Images_and_svg_stay_one_picture_of_model_space()
+ {
+ var dxf = CadBuilder.SaveDxf(TwoSheets(), fx.NewFolder(), "sheets.dxf");
+
+ var job = await fx.ConvertAsync([dxf], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Single(job.Outputs);
+ }
+
+ /// <summary>Blue pixels of a rendered page in a box given as fractions of the page.</summary>
+ private static int Blue(string pdf, int page, double left, double top, double right, double bottom)
+ {
+ using var bitmap = Conversion.ToImage(File.ReadAllBytes(pdf), page, null, new RenderOptions(Dpi: 40, BackgroundColor: SKColors.White));
+ var count = 0;
+ for (var y = (int)(top * bitmap.Height); y < (int)(bottom * bitmap.Height); y++)
+ for (var x = (int)(left * bitmap.Width); x < (int)(right * bitmap.Width); x++)
+ if (bitmap.GetPixel(x, y) is { Blue: > 150, Red: < 100 })
+ count++;
+ return count;
+ }
+}