### Install ducpy Package Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/overview.mdx Installs the ducpy Python package using pip or uv. This is the first step to using the library's functionalities. ```bash pip install ducpy ``` ```bash uv add ducpy ``` -------------------------------- ### Create New Duc File with Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/examples.mdx This example demonstrates how to create a new DUC file from scratch using the ducpy library. It involves defining app state, creating various graphical elements like text and shapes, and serializing them into a flatbuffers format. Dependencies include the ducpy library and its associated classes. ```python import ducpy as duc from ducpy.classes import DucElementClass, AppStateClass, BinaryFilesClass # Create app state app_state = AppStateClass.AppState() app_state.zoom = 1.0 app_state.scroll_x = 0 app_state.scroll_y = 0 app_state.view_background_color = "#ffffff" # Create elements elements = [] # Add a text element text = DucElementClass.DucElement() text.id = "text1" text.type = "text" text.text = "Hello, Duc File Format!" text.font_family = "Arial" text.font_size_v3 = 24.0 text.x_v3 = 100 text.y_v3 = 100 text.width_v3 = 300 text.height_v3 = 50 elements.append(text) # Add a rectangle rect = DucElementClass.DucElement() rect.id = "rect1" rect.type = "line" rect.x_v3 = 100 rect.y_v3 = 200 rect.width_v3 = 200 rect.height_v3 = 100 # Create points for rectangle p1 = DucElementClass.Point() p1.x_v3, p1.y_v3 = 100, 200 p2 = DucElementClass.Point() p2.x_v3, p2.y_v3 = 300, 200 p3 = DucElementClass.Point() p3.x_v3, p3.y_v3 = 300, 300 p4 = DucElementClass.Point() p4.x_v3, p4.y_v3 = 100, 300 p5 = DucElementClass.Point() p5.x_v3, p5.y_v3 = 100, 200 rect.points = [p1, p2, p3, p4, p5] elements.append(rect) # Create binary files container files = BinaryFilesClass.DucExternalFiles() # Save to file with open("new_drawing.duc", "wb") as f: duc.serialize.serialize_to_flatbuffers(elements, app_state, files, f) ``` -------------------------------- ### Run Development Server (npm, pnpm, yarn) Source: https://github.com/ducflair/duc/blob/main/apps/web/README.md This snippet shows commands to run the development server for the duc-docs Next.js application using different package managers. Ensure you have the necessary dependencies installed. ```bash npm run dev # or pnpm dev # or yarn dev ``` -------------------------------- ### Create Animation Frames with Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/examples.mdx This example outlines the creation of animation frames within a DUC file using ducpy. It involves setting up the app state, creating reusable functions to generate graphical elements like circles with animation-suitable properties, and preparing the data structure for serialization. Dependencies include ducpy, copy, and math. -------------------------------- ### Create Text Element in Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/classes.mdx Provides an example of creating a specific text element by initializing a DucElement and setting its type to 'text', along with text content and font properties. ```Python # Create a text element text_element = DucElementClass.DucElement() text_element.id = "text1" text_element.type = "text" text_element.text = "Hello, World!" text_element.font_family = "Arial" text_element.font_size_v3 = 16.0 ``` -------------------------------- ### Install duc2pdf CLI Tool using Cargo Source: https://github.com/ducflair/duc/blob/main/packages/ducpdf/src/duc2pdf/README.md This command installs the duc2pdf command-line interface tool globally using Cargo. This enables you to use duc2pdf directly from your terminal for file conversions. ```bash cargo install duc2pdf ``` -------------------------------- ### Read and Modify Duc File with Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/examples.mdx This example shows how to read an existing DUC file, modify its elements, and save the changes. It involves parsing a flatbuffers-formatted DUC file, iterating through elements to apply transformations (e.g., converting text to uppercase, increasing font size), and then re-serializing the modified data. Dependencies include the ducpy library. -------------------------------- ### Install ducpy Package (Bash) Source: https://github.com/ducflair/duc/blob/main/packages/ducpy/README.md This command installs the ducpy Python package using pip. Ensure you have pip installed and accessible in your environment. ```bash pip install ducpy ``` -------------------------------- ### Ducpy and NumPy Data Visualization Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/examples.mdx This Python script demonstrates how to use ducpy with NumPy to create a line chart visualization. It generates sine wave data using NumPy, scales and offsets it, and then creates ducpy elements (line, x-axis, y-axis) to represent the data. The final visualization is saved as a .duc file. It requires ducpy and NumPy libraries. ```python import ducpy as duc import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Scale data to fit in the drawing scale_x = 50 scale_y = 50 offset_x = 100 offset_y = 200 # Create app state and files app_state = duc.classes.AppStateClass.AppState() app_state.zoom = 1.0 files = duc.classes.BinaryFilesClass.DucExternalFiles() # Create elements list elements = [] # Create a line chart from NumPy data line = duc.classes.DucElementClass.DucElement() line.id = "sin_curve" line.type = "line" # Convert NumPy data to points points = [] for i in range(len(x)): point = duc.classes.DucElementClass.Point() point.x_v3 = offset_x + x[i] * scale_x point.y_v3 = offset_y - y[i] * scale_y # Negative to flip Y axis points.append(point) line.points = points elements.append(line) # Add axes x_axis = duc.classes.DucElementClass.DucElement() x_axis.id = "x_axis" x_axis.type = "line" x_axis_p1 = duc.classes.DucElementClass.Point() x_axis_p1.x_v3 = offset_x x_axis_p1.y_v3 = offset_y x_axis_p2 = duc.classes.DucElementClass.Point() x_axis_p2.x_v3 = offset_x + 10 * scale_x x_axis_p2.y_v3 = offset_y x_axis.points = [x_axis_p1, x_axis_p2] elements.append(x_axis) y_axis = duc.classes.DucElementClass.DucElement() y_axis.id = "y_axis" y_axis.type = "line" y_axis_p1 = duc.classes.DucElementClass.Point() y_axis_p1.x_v3 = offset_x y_axis_p1.y_v3 = offset_y + scale_y y_axis_p2 = duc.classes.DucElementClass.Point() y_axis_p2.x_v3 = offset_x y_axis_p2.y_v3 = offset_y - scale_y y_axis.points = [y_axis_p1, y_axis_p2] elements.append(y_axis) # Save the visualization with open("numpy_visualization.duc", "wb") as f: duc.serialize.serialize_to_flatbuffers(elements, app_state, files, f) ``` -------------------------------- ### Extract and Process Images from Duc File with Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/examples.mdx This example demonstrates how to extract images embedded within a DUC file, process them using Pillow, and save the modified images back into the DUC file. It parses the DUC file, identifies image elements, uses Pillow to open and manipulate image data, and updates the binary data within the DUC structure. Dependencies include ducpy, Pillow, and os. -------------------------------- ### Parse DUC Data in Rust Source: https://context7.com/ducflair/duc/llms.txt Demonstrates how to read and parse DUC files using Rust for efficient CAD data processing. It includes examples of accessing element properties and global state, and filtering elements by type. ```rust use duc::{parse_duc, DucElement, DucGlobalState}; fn main() -> Result<(), Box> { // Read DUC file let duc_bytes = std::fs::read("drawing.duc")?; // Parse the DUC data let parsed_data = parse_duc(&duc_bytes)?; // Access elements for element in &parsed_data.elements { match element { DucElement::Rectangle(rect) => { println!("Rectangle at ({}, {})", rect.base.x.value, rect.base.y.value); }, DucElement::Text(text) => { println!("Text: {}", text.text); }, DucElement::Line(line) => { println!("Line with {} points", line.points.len()); }, _ => {} // Handle other element types if necessary } } // Access global state println!("View background: {}", parsed_data.global_state.view_background_color); println!("Main scope: {}", parsed_data.global_state.main_scope); // Filter elements by type let rectangles: Vec<_> = parsed_data.elements.iter() .filter_map(|e| match e { DucElement::Rectangle(r) => Some(r), _ => None }) .collect(); println!("Found {} rectangles", rectangles.len()); Ok(()) } ``` -------------------------------- ### Generate Animation Frames with Ducpy Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/examples.mdx This Python script generates 10 animation frames. Each frame consists of a circle with an increasing radius and is saved as a .duc file using flatbuffers serialization. It requires the ducpy library and assumes the existence of `create_circle`, `app_state`, and `files` objects. ```python import duc # Generate 10 animation frames for frame in range(10): elements = [] # Create a circle with increasing radius radius = 50 + frame * 10 circle = duc.create_circle(300, 300, radius) elements.append(circle) # Save each frame as a separate file with open(f"animation_frame_{frame}.duc", "wb") as f: duc.serialize.serialize_to_flatbuffers(elements, app_state, files, f) ``` -------------------------------- ### Convert duc File to PDF using duc2pdf CLI Tool Source: https://github.com/ducflair/duc/blob/main/packages/ducpdf/src/duc2pdf/README.md This command shows how to use the installed duc2pdf CLI tool to convert a 'duc' file to a PDF file. It takes the input 'duc' file path and the desired output PDF file path as arguments. ```bash duc2pdf input.duc output.pdf ``` -------------------------------- ### Import and Use Callout Component from fumadocs-ui Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/typescript/api.mdx Demonstrates how to import and utilize the 'Callout' component from the 'fumadocs-ui' library. This component is used to display important informational messages, such as warnings, within the documentation. It requires the 'fumadocs-ui' package to be installed. ```javascript import { Callout } from 'fumadocs-ui/components/callout'; This page is subject to change as the project is still in development. ``` -------------------------------- ### Create and Configure AppState in Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/classes.mdx Shows how to instantiate and configure the AppState class, which stores information about the application's state when a duc file was saved. This includes zoom level, scroll position, and view background color. ```Python from ducpy.classes import AppStateClass # Create an AppState object app_state = AppStateClass.AppState() # Set properties app_state.zoom = 1.0 app_state.scroll_x = 0.0 app_state.scroll_y = 0.0 app_state.view_background_color = "#ffffff" ``` -------------------------------- ### Create Layers and Blocks in TypeScript Source: https://context7.com/ducflair/duc/llms.txt Demonstrates how to create layer objects with properties like visibility, color, and overrides, and how to define reusable block structures with attribute definitions. Elements can then be assigned to these layers, and block instances can be created with specific attributes and duplication arrays. ```typescript const mechanicalLayer = { id: nanoid(), label: 'Mechanical Components', description: 'All mechanical parts', isCollapsed: false, isPlot: true, isVisible: true, locked: false, readonly: false, opacity: 1, labelingColor: '#e74c3c', overrides: { stroke: { content: { preference: 'solid', src: '#000000', visible: true, opacity: 1 }, width: px(1), style: { preference: 'solid', dash: [] }, placement: 'center' }, background: { content: { preference: 'solid', src: 'transparent', visible: false, opacity: 0 } } } }; const element = { /* ... */ }; element.layerId = mechanicalLayer.id; const boltBlock = { id: nanoid(), label: 'M10 Bolt', description: 'Standard M10 bolt symbol', version: 1, attributeDefinitions: { 'size': { tag: 'SIZE', prompt: 'Bolt size', defaultValue: 'M10', isConstant: false } }, metadata: { source: 'library', usageCount: 0, createdAt: Date.now(), updatedAt: Date.now() } }; const boltInstance = { id: nanoid(), blockId: boltBlock.id, version: 1, attributeValues: { 'size': 'M12' }, elementOverrides: {}, duplicationArray: { rows: 3, cols: 2, rowSpacing: px(20), colSpacing: px(15) } }; ``` -------------------------------- ### Create Image Element in Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/classes.mdx Shows how to create an image element by initializing a DucElement and setting its type to 'image', referencing an embedded binary file using its file_id. ```Python # Create an image element image_element = DucElementClass.DucElement() image_element.id = "image1" image_element.type = "image" image_element.file_id = "file_id" ``` -------------------------------- ### Create Line Element with Points in Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/classes.mdx Demonstrates the creation of a line element, setting its type to 'line' and defining its shape by adding a list of Point objects, each with x and y coordinates. ```Python # Create a line element line_element = DucElementClass.DucElement() line_element.id = "line1" line_element.type = "line" # Add points to the line point1 = DucElementClass.Point() point1.x_v3 = 100.0 point1.y_v3 = 100.0 point2 = DucElementClass.Point() point2.x_v3 = 200.0 point2.y_v3 = 200.0 line_element.points = [point1, point2] ``` -------------------------------- ### Create and Configure DucElement in Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/classes.mdx Demonstrates how to create a base DucElement object and set its fundamental properties like ID, type, and position. This class serves as the foundation for all other element types in a duc file. ```Python from ducpy.classes import DucElementClass # Access the DucElement class element = DucElementClass.DucElement() # Set properties element.id = "unique_id" element.type = "text" element.x_v3 = 100.0 element.y_v3 = 200.0 element.width_v3 = 300.0 element.height_v3 = 150.0 ``` -------------------------------- ### Create CAD Elements Programmatically in TypeScript Source: https://context7.com/ducflair/duc/llms.txt Illustrates how to programmatically create CAD elements, such as rectangles and dimensions, using TypeScript. This approach allows for building complex drawings from code, defining detailed properties and styling for each element. ```typescript import { nanoid } from 'nanoid'; // Helper to create precision values const px = (val: number) => ({ value: val, scoped: val }); // Create a styled rectangle const rectangle = { type: 'rectangle', id: nanoid(), x: px(10), y: px(10), width: px(100), height: px(60), angle: 0, scope: 'mm', label: 'Container', description: 'Main container box', isVisible: true, seed: Math.floor(Math.random() * 1000000), version: 1, versionNonce: 1, updated: Date.now(), index: null, isPlot: false, isAnnotative: false, isDeleted: false, groupIds: [], regionIds: [], blockIds: [], instanceId: null, layerId: null, frameId: null, boundElements: null, zIndex: 1, link: null, locked: false, roundness: px(5), blending: undefined, background: [{ content: { preference: 'solid', src: '#3498db', visible: true, opacity: 0.3, tiling: undefined, hatch: undefined, imageFilter: undefined } }], stroke: [{ content: { preference: 'solid', src: '#2c3e50', visible: true, opacity: 1, tiling: undefined, hatch: undefined, imageFilter: undefined }, width: px(2), style: { preference: 'solid', cap: undefined, join: undefined, dash: [], dashLineOverride: undefined, dashCap: undefined, miterLimit: undefined }, placement: 'center', strokeSides: undefined }], opacity: 1 }; // Create a dimension element const dimension = { type: 'dimension', id: nanoid(), dimensionType: 'linear', definitionPoints: { origin1: { x: 10, y: 10 }, origin2: { x: 110, y: 10 }, location: { x: 60, y: 0 } }, obliqueAngle: 0, textOverride: null, textPosition: null // ... base properties and styles }; ``` -------------------------------- ### Parse and Serialize duc File using Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/overview.mdx Demonstrates basic usage of the ducpy package for parsing a duc file into Python objects and then serializing those objects back into a duc file. It utilizes the 'parse' and 'serialize' modules. ```python # Import the ducpy package import ducpy as duc # Parse a duc file with open('example.duc', 'rb') as f: duc_data = duc.parse.parse_duc_flatbuffers(f) # Access elements, app state, and files elements = duc_data['elements'] app_state = duc_data['appState'] files = duc_data['files'] # Serialize a duc file with open('output.duc', 'wb') as f: duc.serialize.serialize_to_flatbuffers(elements, app_state, files, f) ``` -------------------------------- ### Convert duc File to PDF using duc2pdf Library Source: https://github.com/ducflair/duc/blob/main/packages/ducpdf/src/duc2pdf/README.md This Rust code snippet demonstrates how to use the duc2pdf crate as a library to convert a 'duc' file to a PDF file. It imports the necessary functions and calls the 'convert' function, handling potential errors. ```rust use duc2pdf::* // Convert duc file to PDF let result = duc2pdf::convert("input.duc", "output.pdf").unwrap(); ``` -------------------------------- ### Python: Parse and Serialize DUC Source: https://context7.com/ducflair/duc/llms.txt Provides Python bindings for working with DUC files, enabling parsing and serialization within Python applications for automated workflows and analysis. ```APIDOC ## Python: Parse and Serialize DUC ### Description This section outlines the use of Python bindings for the DUC file format. It allows developers to parse DUC files into Python objects and serialize Python data structures back into DUC binary format, facilitating integration into Python-based CAD tools and workflows. ### Method `ducpy.parse(file_path: str) => object` `ducpy.serialize(data: object, file_path: str, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file_path** (str) - Path to the DUC file for parsing or the output path for serialization. - **data** (object) - The structured data object to serialize (specific structure depends on `ducpy` implementation). ### Request Example ```python import ducpy as duc # Example for parsing (assuming ducpy.parse exists and returns a dict-like object) duc_data = duc.parse('path/to/your/drawing.duc') print(duc_data['elements']) # Example for serialization (assuming ducpy.serialize exists) output_data = { ... } # Your structured CAD data duc.serialize(output_data, 'path/to/output.duc') ``` ### Response #### Success Response (200) - **parse**: Returns a Python object representing the parsed DUC data. - **serialize**: Writes the serialized DUC data to the specified file path. #### Response Example ```python # Successful parsing might return a dictionary or a custom object. # print(duc_data['elements']) would output a list of element dictionaries. # Serialization is typically a file operation, success is indicated by file creation. ``` ``` -------------------------------- ### Create and Configure DucExternalFiles in Python Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/classes.mdx Illustrates the creation and population of the DucExternalFiles class, used to manage binary data like images embedded within a duc file. It details how to add file entries with their IDs, MIME types, and raw data. ```Python from ducpy.classes import BinaryFilesClass # Create a DucExternalFiles object files = BinaryFilesClass.DucExternalFiles() # Add a binary file file_data = BinaryFilesClass.DucExternalFileData() file_data.id = "file_id" file_data.mime_type = "image/png" file_data.data = b'...' files.entries[file_data.id] = file_data ``` -------------------------------- ### Convert DUC to PDF Source: https://context7.com/ducflair/duc/llms.txt Converts a DUC file to PDF format. Supports basic conversion, advanced options like cropping, scaling, and metadata. ```APIDOC ## Convert DUC to PDF ### Description Converts a DUC file into a PDF document. This function allows for basic conversion as well as advanced options for customization, including cropping, scaling, and setting PDF metadata. ### Method `convertDucToPdf(ducData: Uint8Array, options?: PdfConversionOptions) => Promise` `convertDucToPdfCrop(ducData: Uint8Array, offsetX: number, offsetY: number, width: number, height: number) => Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ducData** (Uint8Array) - The DUC file data as a byte array. - **options** (PdfConversionOptions) - Optional configuration object for advanced conversion: - **offsetX** (number) - Horizontal offset for the drawing. - **offsetY** (number) - Vertical offset for the drawing. - **width** (number) - The desired width of the output PDF. - **height** (number) - The desired height of the output PDF. - **scale** (number) - Scaling factor for the drawing. - **zoom** (number) - Zoom level for the drawing. - **backgroundColor** (string) - Background color of the PDF (e.g., '#FFFFFF'). - **metadata** (object) - Metadata for the PDF document: - **title** (string) - Title of the document. - **author** (string) - Author of the document. - **subject** (string) - Subject of the document. - **offsetX** (number) - (for `convertDucToPdfCrop`) Horizontal offset for cropping. - **offsetY** (number) - (for `convertDucToPdfCrop`) Vertical offset for cropping. - **width** (number) - (for `convertDucToPdfCrop`) Width of the cropped area. - **height** (number) - (for `convertDucToPdfCrop`) Height of the cropped area. ### Request Example ```typescript import { convertDucToPdf, convertDucToPdfCrop } from 'ducpdf'; const ducData = new Uint8Array(await file.arrayBuffer()); // Basic conversion const pdfBytes = await convertDucToPdf(ducData); // Advanced conversion const pdfWithOptions = await convertDucToPdf(ducData, { offsetX: 100, offsetY: 200, width: 800, height: 600, scale: 1.5, zoom: 1.2, backgroundColor: '#FFFFFF', metadata: { title: 'Engineering Drawing', author: 'John Doe' } }); // Crop-specific conversion const croppedPdf = await convertDucToPdfCrop(ducData, 100, 200, 800, 600); ``` ### Response #### Success Response (200) - **pdfBytes** (ArrayBuffer) - The PDF document data as an ArrayBuffer. #### Response Example ```javascript // The result is an ArrayBuffer, which can be used to create a Blob. const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' }); const pdfUrl = URL.createObjectURL(pdfBlob); ``` ``` -------------------------------- ### Python: Parse and Serialize DUC Source: https://context7.com/ducflair/duc/llms.txt Provides Python bindings for working with DUC files, enabling parsing and serialization within Python environments. This is useful for automated workflows, analysis, or integration with other Python-based tools. ```python import ducpy as duc # Example usage (actual implementation details would follow) # duc_data = duc.parse_duc('drawing.duc') # serialized_duc = duc.serialize_duc(structured_data) ``` -------------------------------- ### Import Link Component from Fumadocs Core Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/roadmap/overview.mdx Imports the Link component from the 'fumadocs-core/link' module. This component is likely used for internal or external navigation within the documentation or application. ```javascript import Link from 'fumadocs-core/link'; ``` -------------------------------- ### Parse and Access DUC Data in Python Source: https://context7.com/ducflair/duc/llms.txt Reads a DUC file, parses its binary data into a Python dictionary, and provides methods to access element properties and global metadata. It also shows how to modify the parsed data and serialize it back to binary format. ```python with open('drawing.duc', 'rb') as f: duc_data = f.read() parsed = duc.parse(duc_data) # Access elements for element in parsed['elements']: print(f"Element {element['id']}: {element['type']}") print(f" Position: ({element['x']['value']}, {element['y']['value']})") print(f" Size: {element['width']['value']} x {element['height']['value']}") # Access metadata print(f"Scope: {parsed['globalState']['mainScope']}") print(f"Layers: {len(parsed['layers'])}") print(f"Blocks: {len(parsed['blocks'])}") # Modify data parsed['globalState']['viewBackgroundColor'] = '#F0F0F0' parsed['elements'].append({ 'type': 'text', 'id': 'text-1', 'text': 'Hello CAD', 'x': {'value': 50, 'scoped': 50}, 'y': {'value': 50, 'scoped': 50}, # ... other required properties }) # Serialize back output_bytes = duc.serialize(parsed, use_scoped_values=True) # Save modified file with open('modified.duc', 'wb') as f: f.write(output_bytes) ``` -------------------------------- ### Add duc2pdf Crate Dependency using Cargo Source: https://github.com/ducflair/duc/blob/main/packages/ducpdf/src/duc2pdf/README.md This command adds the duc2pdf crate as a dependency to your Rust project using the Cargo package manager. This allows you to use its functionalities within your code. ```bash cargo add duc2pdf ``` -------------------------------- ### Custom Duc File Serialization with FlatBuffers Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/serializing.mdx Enables custom serialization of duc file components into FlatBuffers. This function allows for manual construction of the FlatBuffers object by serializing elements, app state, and files individually and then combining them. Requires 'flatbuffers' and 'ducpy' libraries. ```python import flatbuffers from ducpy.serialize import ( serialize_duc_element, serialize_app_state, serialize_binary_files ) from ducpy.Duc.ExportedDataState import ExportedDataStateStart, ExportedDataStateEnd from ducpy.Duc.ExportedDataState import ExportedDataStateAddElements, ExportedDataStateAddAppState, ExportedDataStateAddFiles # Create a builder builder = flatbuffers.Builder(0) # Serialize components elements_vector = [] for element in elements: elements_vector.append(serialize_duc_element(builder, element)) elements_offset = builder.CreateVector(elements_vector) app_state_offset = serialize_app_state(builder, app_state) files_offset = serialize_binary_files(builder, files) # Start building the root object ExportedDataStateStart(builder) ExportedDataStateAddElements(builder, elements_offset) ExportedDataStateAddAppState(builder, app_state_offset) ExportedDataStateAddFiles(builder, files_offset) # Set additional properties if needed if type_str: type_offset = builder.CreateString(type_str) ExportedDataStateAddType(builder, type_offset) if version: ExportedDataStateAddVersion(builder, version) if source: source_offset = builder.CreateString(source) ExportedDataStateAddSource(builder, source_offset) # Finish building data_offset = ExportedDataStateEnd(builder) builder.Finish(data_offset) # Get the serialized data buf = builder.Output() # Write to a file with open('custom_output.duc', 'wb') as f: f.write(buf) ``` -------------------------------- ### Serialize Individual Duc Components to FlatBuffers Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/serializing.mdx Provides functions to serialize individual components of a duc file, such as a single DucElement, the application state, or binary files, into FlatBuffers format. Uses the 'ducpy.serialize' module and 'flatbuffers'. ```python from ducpy.serialize import serialize_duc_element # Serialize a single element builder = flatbuffers.Builder(0) element_offset = serialize_duc_element(builder, element) ``` ```python from ducpy.serialize import serialize_app_state # Serialize the application state builder = flatbuffers.Builder(0) app_state_offset = serialize_app_state(builder, app_state) ``` ```python from ducpy.serialize import serialize_binary_files # Serialize binary files builder = flatbuffers.Builder(0) files_offset = serialize_binary_files(builder, files) ``` -------------------------------- ### Serialize Complete Duc File to FlatBuffers Source: https://github.com/ducflair/duc/blob/main/apps/web/content/docs/python/serializing.mdx Serializes a complete duc file by combining elements, application state, and external files into a FlatBuffers binary format and writing it to a file. Requires the 'ducpy' library. ```python from ducpy import serialize # Prepare your data elements = [...] # List of DucElement objects app_state = ... # AppState object files = ... # DucExternalFiles object # Serialize to a file with open('output.duc', 'wb') as f: serialize.serialize_to_flatbuffers(elements, app_state, files, f) ``` -------------------------------- ### Parse DUC File Source: https://context7.com/ducflair/duc/llms.txt Parses a DUC binary file into a structured data object containing all CAD elements, styles, and metadata. Supports file input and options for forcing measurement units. ```APIDOC ## Parse DUC File ### Description Parses a DUC binary file into a structured data object with all CAD elements, styles, and metadata. This function is essential for reading and interpreting DUC files. ### Method `parseDuc(file: File | Blob, options?: object, config?: { forceScope: 'px' | 'mm' | 'cm' | 'in' }) => Promise ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (File | Blob) - The DUC file to parse. - **options** (object) - Optional configuration options (details not specified in source). - **config** ({ forceScope: 'px' | 'mm' | 'cm' | 'in' }) - Optional configuration to force measurement units. E.g., `{ forceScope: 'mm' }`. ### Request Example ```typescript import { parseDuc } from 'ducjs'; const file = new File([ducBinaryData], 'drawing.duc'); const restoredState = await parseDuc(file, null, { forceScope: 'mm' }); console.log('Elements:', restoredState.elements); ``` ### Response #### Success Response (200) - **restoredState** (object) - An object containing the parsed DUC data, including `elements`, `globalState`, `layers`, `blocks`, etc. #### Response Example ```json { "elements": [ // ... DucElement[] ], "localState": { /* ... */ }, "globalState": { /* ... */ }, "blocks": [ /* ... */ ], "blockInstances": [ /* ... */ ], "groups": [ /* ... */ ], "layers": [ /* ... */ ], "regions": [ /* ... */ ], "standards": [ /* ... */ ], "files": { /* ... */ }, "dictionary": { /* ... */ }, "versionGraph": { /* ... */ }, "id": "string" } ``` ``` -------------------------------- ### Convert DUC to PDF - TypeScript/JavaScript Source: https://context7.com/ducflair/duc/llms.txt Converts DUC data to PDF format. Supports basic conversion, advanced options like cropping, scaling, offsets, and metadata. The output is a Uint8Array of PDF bytes. ```typescript import { convertDucToPdf, convertDucToPdfCrop } from 'ducpdf'; // Basic conversion const ducData = new Uint8Array(await file.arrayBuffer()); const pdfBytes = await convertDucToPdf(ducData); // Save PDF const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' }); const pdfUrl = URL.createObjectURL(pdfBlob); // Advanced conversion with options const pdfWithOptions = await convertDucToPdf(ducData, { offsetX: 100, offsetY: 200, width: 800, height: 600, scale: 1.5, zoom: 1.2, backgroundColor: '#FFFFFF', metadata: { title: 'Engineering Drawing', author: 'John Doe', subject: 'Mechanical Design' } }); // Crop-specific conversion const croppedPdf = await convertDucToPdfCrop( ducData, 100, // offsetX 200, // offsetY 800, // width 600 // height ); ``` -------------------------------- ### Query and Filter CAD Elements in TypeScript Source: https://context7.com/ducflair/duc/llms.txt Shows how to parse DUC files using 'ducjs' and then filter elements based on type, layer, visibility, spatial region, label pattern, group membership, and complex combined conditions. This includes finding unlocked dimensions on visible layers. ```typescript import { parseDuc } from 'ducjs'; const parsed = await parseDuc(file); // Filter by element type const allText = parsed.elements.filter(e => e.type === 'text'); const allDimensions = parsed.elements.filter(e => e.type === 'dimension'); // Filter by layer const layerId = 'layer-123'; const layerElements = parsed.elements.filter(e => e.layerId === layerId); // Filter by visibility const visibleElements = parsed.elements.filter(e => e.isVisible && !e.isDeleted); // Find elements in a region const inRegion = (element, x1, y1, x2, y2) => { const ex = element.x.value; const ey = element.y.value; return ex >= x1 && ex <= x2 && ey >= y1 && ey <= y2; }; const selectedElements = parsed.elements.filter(e => inRegion(e, 0, 0, 100, 100) ); // Find elements by label pattern const searchResults = parsed.elements.filter(e => e.label?.toLowerCase().includes('bolt') ); // Get all elements in a group const groupId = 'group-456'; const groupElements = parsed.elements.filter(e => e.groupIds.includes(groupId) ); // Complex query: find unlocked dimensions on visible layers const editableDimensions = parsed.elements.filter(e => { if (e.type !== 'dimension') return false; if (e.locked || e.isDeleted) return false; if (e.layerId) { const layer = parsed.layers.find(l => l.id === e.layerId); if (!layer || !layer.isVisible || layer.locked) return false; } return true; }); ``` -------------------------------- ### Serialize to DUC Binary Source: https://context7.com/ducflair/duc/llms.txt Converts a structured CAD data object back into the DUC binary format. This is used to save or export CAD data in the DUC format. ```APIDOC ## Serialize to DUC Binary ### Description Converts a structured CAD data object back into the DUC binary format. This function is crucial for saving modifications or creating new DUC files. ### Method `serializeDuc(cadData: object, useScopedValues: boolean, passThroughElementIds: string[], config?: { forceScope: 'px' | 'mm' | 'cm' | 'in' }) => Promise ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cadData** (object) - The structured CAD data object to serialize. Must conform to the expected DUC data structure. - **useScopedValues** (boolean) - Determines if scoped values should be used during serialization. - **passThroughElementIds** (string[]) - An array of element IDs to pass through during serialization. - **config** ({ forceScope: 'px' | 'mm' | 'cm' | 'in' }) - Optional configuration to force measurement units. E.g., `{ forceScope: 'mm' }`. ### Request Example ```typescript import { serializeDuc } from 'ducjs'; const cadData = { /* ... your CAD data structure ... */ }; const ducBinary = await serializeDuc(cadData, true, [], { forceScope: 'mm' }); const blob = new Blob([ducBinary], { type: 'application/duc' }); const url = URL.createObjectURL(blob); ``` ### Response #### Success Response (200) - **ducBinary** (Uint8Array) - The serialized DUC data as a byte array. #### Response Example ```javascript // The result is a Uint8Array, which can be used to create a Blob or File. // Example of saving to a blob: const blob = new Blob([ducBinary], { type: 'application/duc' }); ``` ```