Skip to content

API Reference

v2

PyGerber hight level rendering API version 2.

This API utilizes Parser2 for parsing and SvgRenderer2, RasterRenderer2 for rendering output files. It is designed to be more limited and easier to use than the previous. For more advanced uses users will have to fall back to the lower level APIs and manual interaction with the parser and renderers.

ColorScheme

Bases: FrozenGeneralModel

Set of colors which should be used for rendering.

ColorScheme class contains set of colors which should be used for different parts of rendered image. At the same time it also works as a container for predefined color schemes commonly used for parts of PCB.

Predefined colors

All predefined colors have two variants - normal one and one with "*_ALPHA" suffix. Those without suffix have solid background and are not intended for constructing multi-layer images out of them ie. they are not suitable for rendering a project consisting of separate copper, silk, pase mask and composing them into single image. For cases when rendered images are intended for stacking "*_ALPHA" schemes should be used, as background and transparent parts of image will be truly transparent.

Source code in src\pygerber\backend\rasterized_2d\color_scheme.py
class ColorScheme(FrozenGeneralModel):
    r"""Set of colors which should be used for rendering.

    ColorScheme class contains set of colors which should be used for different parts
    of rendered image. At the same time it also works as a container for predefined
    color schemes commonly used for parts of PCB.

    !!! info "Predefined colors"

        All predefined colors have two variants - normal one and one with "\*_ALPHA"
        suffix. Those without suffix have solid background and are not intended for
        constructing multi-layer images out of them ie. they are not suitable for
        rendering a project consisting of separate copper, silk, pase mask and composing
        them into single image. For cases when rendered images are intended for stacking
        "\*_ALPHA" schemes should be used, as background and transparent parts of image
        will be truly transparent.

    """

    SILK: ClassVar[ColorScheme]
    """Default color of silk layer.

    This schema provided non-transparent background, which results in images which
    can not be used for stacking on top of other layers, as they would completely
    obscure them."""

    SILK_ALPHA: ClassVar[ColorScheme]
    """Default color of silk layer with alpha channel.

    This schema provides transparent background. Images using this schema can be
    stacked on top of each other without obscuring layers below."""

    COPPER: ClassVar[ColorScheme]
    """Default color of copper layer.

    This schema provided non-transparent background, which results in images which
    can not be used for stacking on top of other layers, as they would completely
    obscure them."""

    COPPER_ALPHA: ClassVar[ColorScheme]
    """Default color of copper layer with alpha channel.

    This schema provides transparent background. Images using this schema can be
    stacked on top of each other without obscuring layers below."""

    PASTE_MASK: ClassVar[ColorScheme]
    """Default color of paste mask layer.

    This schema provided non-transparent background, which results in images which
    can not be used for stacking on top of other layers, as they would completely
    obscure them."""

    PASTE_MASK_ALPHA: ClassVar[ColorScheme]
    """Default color of paste mask layer with alpha channel.

    This schema provides transparent background. Images using this schema can be
    stacked on top of each other without obscuring layers below."""

    SOLDER_MASK: ClassVar[ColorScheme]
    """Default color of solder mask layer.

    This schema provided non-transparent background, which results in images which
    can not be used for stacking on top of other layers, as they would completely
    obscure them."""

    SOLDER_MASK_ALPHA: ClassVar[ColorScheme]
    """Default color of solder mask layer with alpha channel.

    This schema provides transparent background. Images using this schema can be
    stacked on top of each other without obscuring layers below."""

    DEFAULT_GRAYSCALE: ClassVar[ColorScheme]
    """Default color scheme for files which were not assigned other color scheme."""

    DEBUG_1: ClassVar[ColorScheme]
    """Debug color scheme."""

    DEBUG_1_ALPHA: ClassVar[ColorScheme]
    """Debug color scheme with alpha channel."""

    background_color: RGBA
    """Color used as empty image background."""

    clear_color: RGBA
    """Color used for clear draws."""

    solid_color: RGBA
    """Color used for solid draws."""

    clear_region_color: RGBA
    """Color used for clear region draws."""

    solid_region_color: RGBA
    """Color used for solid region draws."""

    debug_1_color: RGBA = RGBA.from_hex("#ababab")
    """Color used for debug elements."""

    debug_2_color: RGBA = RGBA.from_hex("#7d7d7d")
    """Color used for debug elements."""

    def get_grayscale_to_rgba_color_map(self) -> dict[int, tuple[int, int, int, int]]:
        """Return grayscale to RGBA color map."""
        return {
            Polarity.Dark.get_2d_rasterized_color(): self.solid_color.as_rgba_int(),
            Polarity.Clear.get_2d_rasterized_color(): self.clear_color.as_rgba_int(),
            Polarity.DarkRegion.get_2d_rasterized_color(): self.solid_region_color.as_rgba_int(),  # noqa: E501
            Polarity.ClearRegion.get_2d_rasterized_color(): self.clear_region_color.as_rgba_int(),  # noqa: E501
            Polarity.Background.get_2d_rasterized_color(): self.background_color.as_rgba_int(),  # noqa: E501
            Polarity.DEBUG.get_2d_rasterized_color(): self.debug_1_color.as_rgba_int(),
            Polarity.DEBUG2.get_2d_rasterized_color(): self.debug_2_color.as_rgba_int(),
        }

SILK class-attribute

SILK: ColorScheme

Default color of silk layer.

This schema provided non-transparent background, which results in images which can not be used for stacking on top of other layers, as they would completely obscure them.

SILK_ALPHA class-attribute

SILK_ALPHA: ColorScheme

Default color of silk layer with alpha channel.

This schema provides transparent background. Images using this schema can be stacked on top of each other without obscuring layers below.

COPPER class-attribute

COPPER: ColorScheme

Default color of copper layer.

This schema provided non-transparent background, which results in images which can not be used for stacking on top of other layers, as they would completely obscure them.

COPPER_ALPHA class-attribute

COPPER_ALPHA: ColorScheme

Default color of copper layer with alpha channel.

This schema provides transparent background. Images using this schema can be stacked on top of each other without obscuring layers below.

PASTE_MASK class-attribute

PASTE_MASK: ColorScheme

Default color of paste mask layer.

This schema provided non-transparent background, which results in images which can not be used for stacking on top of other layers, as they would completely obscure them.

PASTE_MASK_ALPHA class-attribute

PASTE_MASK_ALPHA: ColorScheme

Default color of paste mask layer with alpha channel.

This schema provides transparent background. Images using this schema can be stacked on top of each other without obscuring layers below.

SOLDER_MASK class-attribute

SOLDER_MASK: ColorScheme

Default color of solder mask layer.

This schema provided non-transparent background, which results in images which can not be used for stacking on top of other layers, as they would completely obscure them.

SOLDER_MASK_ALPHA class-attribute

SOLDER_MASK_ALPHA: ColorScheme

Default color of solder mask layer with alpha channel.

This schema provides transparent background. Images using this schema can be stacked on top of each other without obscuring layers below.

DEFAULT_GRAYSCALE class-attribute

DEFAULT_GRAYSCALE: ColorScheme

Default color scheme for files which were not assigned other color scheme.

DEBUG_1 class-attribute

DEBUG_1: ColorScheme

Debug color scheme.

DEBUG_1_ALPHA class-attribute

DEBUG_1_ALPHA: ColorScheme

Debug color scheme with alpha channel.

background_color instance-attribute

background_color: RGBA

Color used as empty image background.

clear_color instance-attribute

clear_color: RGBA

Color used for clear draws.

solid_color instance-attribute

solid_color: RGBA

Color used for solid draws.

clear_region_color instance-attribute

clear_region_color: RGBA

Color used for clear region draws.

solid_region_color instance-attribute

solid_region_color: RGBA

Color used for solid region draws.

debug_1_color class-attribute instance-attribute

debug_1_color: RGBA = from_hex('#ababab')

Color used for debug elements.

debug_2_color class-attribute instance-attribute

debug_2_color: RGBA = from_hex('#7d7d7d')

Color used for debug elements.

get_grayscale_to_rgba_color_map

get_grayscale_to_rgba_color_map() -> (
    dict[int, tuple[int, int, int, int]]
)

Return grayscale to RGBA color map.

Source code in src\pygerber\backend\rasterized_2d\color_scheme.py
def get_grayscale_to_rgba_color_map(self) -> dict[int, tuple[int, int, int, int]]:
    """Return grayscale to RGBA color map."""
    return {
        Polarity.Dark.get_2d_rasterized_color(): self.solid_color.as_rgba_int(),
        Polarity.Clear.get_2d_rasterized_color(): self.clear_color.as_rgba_int(),
        Polarity.DarkRegion.get_2d_rasterized_color(): self.solid_region_color.as_rgba_int(),  # noqa: E501
        Polarity.ClearRegion.get_2d_rasterized_color(): self.clear_region_color.as_rgba_int(),  # noqa: E501
        Polarity.Background.get_2d_rasterized_color(): self.background_color.as_rgba_int(),  # noqa: E501
        Polarity.DEBUG.get_2d_rasterized_color(): self.debug_1_color.as_rgba_int(),
        Polarity.DEBUG2.get_2d_rasterized_color(): self.debug_2_color.as_rgba_int(),
    }

FileTypeEnum

Bases: Enum

Enumeration of possible Gerber file types.

If file type is not listed here you can request adding it by creating an issue on https://github.com/Argmaster/pygerber/issues

Source code in src\pygerber\gerberx3\api\_v2.py
@unique
class FileTypeEnum(Enum):
    """Enumeration of possible Gerber file types.

    If file type is not listed here you can request adding it by creating an issue on
    https://github.com/Argmaster/pygerber/issues
    """

    COPPER = "COPPER"
    MASK = "MASK"
    PASTE = "PASTE"
    SILK = "SILK"
    EDGE = "EDGE"

    PLATED = "PLATED"
    NON_PLATED = "NON_PLATED"
    PROFILE = "PROFILE"
    SOLDERMASK = "SOLDERMASK"
    LEGEND = "LEGEND"
    COMPONENT = "COMPONENT"
    GLUE = "GLUE"
    CARBONMASK = "CARBONMASK"
    GOLDMASK = "GOLDMASK"
    HEATSINKMASK = "HEATSINKMASK"
    PEELABLEMASK = "PEELABLEMASK"
    SILVERMASK = "SILVERMASK"
    TINMASK = "TINMASK"
    DEPTHROUT = "DEPTHROUT"
    VCUT = "VCUT"
    VIAFILL = "VIAFILL"
    PADS = "PADS"

    OTHER = "OTHER"
    UNDEFINED = "UNDEFINED"

    INFER_FROM_EXTENSION = "INFER_FROM_EXTENSION"
    INFER_FROM_ATTRIBUTES = "INFER_FROM_ATTRIBUTES"
    INFER = "INFER"

    @classmethod
    def infer_from_attributes(cls, file_function: Optional[str] = None) -> FileTypeEnum:
        """Infer file type from file extension."""
        if file_function is None:
            return cls.UNDEFINED

        function, *_ = file_function.split(",")
        function = function.upper()

        try:
            return FileTypeEnum(function)
        except (ValueError, TypeError, KeyError):
            return cls.UNDEFINED

    @classmethod
    def infer_from_extension(cls, extension: str) -> FileTypeEnum:
        if re.match(r"\.g[0-9]+", extension):
            return FileTypeEnum.COPPER

        if re.match(r"\.gp[0-9]+", extension):
            return FileTypeEnum.COPPER

        if re.match(r"\.gm[0-9]+", extension):
            return FileTypeEnum.COPPER

        return GERBER_EXTENSION_TO_FILE_TYPE_MAPPING.get(
            extension.lower(), FileTypeEnum.UNDEFINED
        )

infer_from_attributes classmethod

infer_from_attributes(
    file_function: Optional[str] = None,
) -> FileTypeEnum

Infer file type from file extension.

Source code in src\pygerber\gerberx3\api\_v2.py
@classmethod
def infer_from_attributes(cls, file_function: Optional[str] = None) -> FileTypeEnum:
    """Infer file type from file extension."""
    if file_function is None:
        return cls.UNDEFINED

    function, *_ = file_function.split(",")
    function = function.upper()

    try:
        return FileTypeEnum(function)
    except (ValueError, TypeError, KeyError):
        return cls.UNDEFINED

GerberFile dataclass

Generic representation of Gerber file.

This objects provides interface for loading and parsing Gerber files.

Source code in src\pygerber\gerberx3\api\_v2.py
@dataclass
class GerberFile:
    """Generic representation of Gerber file.

    This objects provides interface for loading and parsing Gerber files.
    """

    source_code: str
    file_type: FileTypeEnum

    @classmethod
    def from_file(
        cls,
        file_path: str | Path,
        file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
    ) -> Self:
        """Initialize object with Gerber source code loaded from file on disk."""
        file_path = Path(file_path)
        if file_type == FileTypeEnum.INFER_FROM_EXTENSION:
            file_type = FileTypeEnum.infer_from_extension(file_path.suffix)

        if file_type == FileTypeEnum.INFER:
            file_type = FileTypeEnum.infer_from_extension(file_path.suffix)
            if file_type == FileTypeEnum.UNDEFINED:
                file_type = FileTypeEnum.INFER_FROM_ATTRIBUTES

        return cls(file_path.read_text(encoding="utf-8"), file_type)

    @classmethod
    def from_str(
        cls,
        source_code: str,
        file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
    ) -> Self:
        """Initialize object with Gerber source code from string."""
        if file_type == FileTypeEnum.INFER_FROM_EXTENSION:
            file_type = FileTypeEnum.UNDEFINED
        return cls(source_code, file_type)

    @classmethod
    def from_buffer(
        cls,
        buffer: TextIO,
        file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
    ) -> Self:
        """Initialize object with Gerber source code from readable buffer."""
        if file_type == FileTypeEnum.INFER_FROM_EXTENSION:
            file_type = FileTypeEnum.UNDEFINED
        return cls(buffer.read(), file_type)

    def parse(
        self,
        *,
        on_parser_error: OnParserErrorEnum = OnParserErrorEnum.Ignore,
    ) -> ParsedFile:
        """Parse Gerber file."""
        tokens = Tokenizer().tokenize(self.source_code)
        parser = Parser2(
            Parser2Options(
                on_update_drawing_state_error=Parser2OnErrorAction(
                    on_parser_error.value,
                ),
            ),
        )
        command_buffer = parser.parse(tokens)

        if self.file_type in (FileTypeEnum.INFER_FROM_ATTRIBUTES, FileTypeEnum.INFER):
            file_type = FileTypeEnum.infer_from_attributes(
                parser.context.file_attributes.get(".FileFunction", None)
            )
        else:
            file_type = self.file_type

        return ParsedFile(
            GerberFileInfo.from_readonly_command_buffer(command_buffer),
            command_buffer,
            file_type,
        )

from_file classmethod

from_file(
    file_path: str | Path,
    file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
) -> Self

Initialize object with Gerber source code loaded from file on disk.

Source code in src\pygerber\gerberx3\api\_v2.py
@classmethod
def from_file(
    cls,
    file_path: str | Path,
    file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
) -> Self:
    """Initialize object with Gerber source code loaded from file on disk."""
    file_path = Path(file_path)
    if file_type == FileTypeEnum.INFER_FROM_EXTENSION:
        file_type = FileTypeEnum.infer_from_extension(file_path.suffix)

    if file_type == FileTypeEnum.INFER:
        file_type = FileTypeEnum.infer_from_extension(file_path.suffix)
        if file_type == FileTypeEnum.UNDEFINED:
            file_type = FileTypeEnum.INFER_FROM_ATTRIBUTES

    return cls(file_path.read_text(encoding="utf-8"), file_type)

from_str classmethod

from_str(
    source_code: str,
    file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
) -> Self

Initialize object with Gerber source code from string.

Source code in src\pygerber\gerberx3\api\_v2.py
@classmethod
def from_str(
    cls,
    source_code: str,
    file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
) -> Self:
    """Initialize object with Gerber source code from string."""
    if file_type == FileTypeEnum.INFER_FROM_EXTENSION:
        file_type = FileTypeEnum.UNDEFINED
    return cls(source_code, file_type)

from_buffer classmethod

from_buffer(
    buffer: TextIO,
    file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
) -> Self

Initialize object with Gerber source code from readable buffer.

Source code in src\pygerber\gerberx3\api\_v2.py
@classmethod
def from_buffer(
    cls,
    buffer: TextIO,
    file_type: FileTypeEnum = FileTypeEnum.UNDEFINED,
) -> Self:
    """Initialize object with Gerber source code from readable buffer."""
    if file_type == FileTypeEnum.INFER_FROM_EXTENSION:
        file_type = FileTypeEnum.UNDEFINED
    return cls(buffer.read(), file_type)

parse

parse(
    *,
    on_parser_error: OnParserErrorEnum = OnParserErrorEnum.Ignore
) -> ParsedFile

Parse Gerber file.

Source code in src\pygerber\gerberx3\api\_v2.py
def parse(
    self,
    *,
    on_parser_error: OnParserErrorEnum = OnParserErrorEnum.Ignore,
) -> ParsedFile:
    """Parse Gerber file."""
    tokens = Tokenizer().tokenize(self.source_code)
    parser = Parser2(
        Parser2Options(
            on_update_drawing_state_error=Parser2OnErrorAction(
                on_parser_error.value,
            ),
        ),
    )
    command_buffer = parser.parse(tokens)

    if self.file_type in (FileTypeEnum.INFER_FROM_ATTRIBUTES, FileTypeEnum.INFER):
        file_type = FileTypeEnum.infer_from_attributes(
            parser.context.file_attributes.get(".FileFunction", None)
        )
    else:
        file_type = self.file_type

    return ParsedFile(
        GerberFileInfo.from_readonly_command_buffer(command_buffer),
        command_buffer,
        file_type,
    )

GerberFileInfo dataclass

Container for information about Gerber file.

Source code in src\pygerber\gerberx3\api\_v2.py
@dataclass
class GerberFileInfo:
    """Container for information about Gerber file."""

    min_x_mm: Decimal
    """Minimum X coordinate in file in millimeters."""
    min_y_mm: Decimal
    """Minimum Y coordinate in file in millimeters."""
    max_x_mm: Decimal
    """Maximum X coordinate in file in millimeters."""
    max_y_mm: Decimal
    """Maximum T coordinate in file in millimeters."""

    width_mm: Decimal
    """Width of image in millimeters."""
    height_mm: Decimal
    """Height of image in millimeters."""

    @classmethod
    def from_readonly_command_buffer(cls, buffer: ReadonlyCommandBuffer2) -> Self:
        """Initialize object with information from command buffer."""
        bbox = buffer.get_bounding_box()
        return cls(
            bbox.min_x.as_millimeters(),
            bbox.min_y.as_millimeters(),
            bbox.max_x.as_millimeters(),
            bbox.max_y.as_millimeters(),
            bbox.width.as_millimeters(),
            bbox.height.as_millimeters(),
        )

min_x_mm instance-attribute

min_x_mm: Decimal

Minimum X coordinate in file in millimeters.

min_y_mm instance-attribute

min_y_mm: Decimal

Minimum Y coordinate in file in millimeters.

max_x_mm instance-attribute

max_x_mm: Decimal

Maximum X coordinate in file in millimeters.

max_y_mm instance-attribute

max_y_mm: Decimal

Maximum T coordinate in file in millimeters.

width_mm instance-attribute

width_mm: Decimal

Width of image in millimeters.

height_mm instance-attribute

height_mm: Decimal

Height of image in millimeters.

from_readonly_command_buffer classmethod

from_readonly_command_buffer(
    buffer: ReadonlyCommandBuffer2,
) -> Self

Initialize object with information from command buffer.

Source code in src\pygerber\gerberx3\api\_v2.py
@classmethod
def from_readonly_command_buffer(cls, buffer: ReadonlyCommandBuffer2) -> Self:
    """Initialize object with information from command buffer."""
    bbox = buffer.get_bounding_box()
    return cls(
        bbox.min_x.as_millimeters(),
        bbox.min_y.as_millimeters(),
        bbox.max_x.as_millimeters(),
        bbox.max_y.as_millimeters(),
        bbox.width.as_millimeters(),
        bbox.height.as_millimeters(),
    )

ImageFormatEnum

Bases: Enum

List of officially supported raster image formats.

Source code in src\pygerber\gerberx3\api\_v2.py
class ImageFormatEnum(Enum):
    """List of officially supported raster image formats."""

    PNG = "png"
    JPEG = "jpg"
    AUTO = "auto"

OnParserErrorEnum

Bases: Enum

Enumeration of possible actions to take on parser error.

Source code in src\pygerber\gerberx3\api\_v2.py
@unique
class OnParserErrorEnum(Enum):
    """Enumeration of possible actions to take on parser error."""

    Ignore = "ignore"
    """Ignore parser errors. Errors which occurred will not be signaled. May yield
    unexpected results for broken files, with missing draw commands or even more
    significant errors."""

    Warn = "warn"
    """Warn on parser error. Parser will log warning message about what went wrong.
    Best for supporting wide range of files without silently ignoring errors in code."""

    Raise = "raise"
    """Raise exception whenever parser encounters error. Will completely break out of
    parsing process, making it impossible to render slightly malformed files."""

Ignore class-attribute instance-attribute

Ignore = 'ignore'

Ignore parser errors. Errors which occurred will not be signaled. May yield unexpected results for broken files, with missing draw commands or even more significant errors.

Warn class-attribute instance-attribute

Warn = 'warn'

Warn on parser error. Parser will log warning message about what went wrong. Best for supporting wide range of files without silently ignoring errors in code.

Raise class-attribute instance-attribute

Raise = 'raise'

Raise exception whenever parser encounters error. Will completely break out of parsing process, making it impossible to render slightly malformed files.

ParsedFile dataclass

Wrapper around parsed Gerber file.

This objects allow actions like rendering and retrieving information about file contents.

Source code in src\pygerber\gerberx3\api\_v2.py
@dataclass
class ParsedFile:
    """Wrapper around parsed Gerber file.

    This objects allow actions like rendering and retrieving information about file
    contents.
    """

    _info: GerberFileInfo
    _command_buffer: ReadonlyCommandBuffer2
    _file_type: FileTypeEnum

    def get_info(self) -> GerberFileInfo:
        """Get information about Gerber file."""
        return self._info

    def get_file_type(self) -> FileTypeEnum:
        """Get type of Gerber file."""
        return self._file_type

    def render_svg(
        self,
        destination: BytesIO | Path | str,
        *,
        color_scheme: ColorScheme = ColorScheme.COPPER,
        scale: float = 1.0,
    ) -> None:
        """Render Gerber file to SVG format.

        Parameters
        ----------
        destination : BytesIO | Path | str
            Destination to save file to. When BytesIO is provided, file will be saved
            to buffer. When Path or str is provided, they are treated as file path
            and will be used to open and save file on disk.
        color_scheme : ColorScheme, optional
            Color scheme of image, by default ColorScheme.COPPER
        scale : float, optional
            Scale of image, can be used to scale very large or very small images, by
            default 1.0

        """
        output = SvgRenderer2(
            SvgRenderer2Hooks(color_scheme=color_scheme, scale=Decimal(scale)),
        ).render(self._command_buffer)
        output.save_to(destination)

    def render_raster(
        self,
        destination: BytesIO | Path | str,
        *,
        color_scheme: ColorScheme = ColorScheme.COPPER,
        dpmm: int = 20,
        image_format: ImageFormatEnum = ImageFormatEnum.AUTO,
        pixel_format: PixelFormatEnum = PixelFormatEnum.RGB,
        quality: int = 85,
    ) -> None:
        """Render Gerber file to raster image.

        Parameters
        ----------
        destination : BytesIO | Path | str
            Destination to save file to. When BytesIO is provided, file will be saved
            to buffer. When Path or str is provided, they are treated as file path
            and will be used to open and save file on disk.
        color_scheme : ColorScheme, optional
            Color scheme of image, by default ColorScheme.COPPER
        dpmm : int, optional
            Resolution of image in dots per millimeter, by default 96
        image_format : ImageFormatEnum, optional
            Image format to save, by default ImageFormatEnum.AUTO
        pixel_format : PixelFormatEnum, optional
            Pixel format, by default PixelFormatEnum.RGB
        quality: int, optional
            Image quality for JPEG format, by default 85.

        """
        output = RasterRenderer2(
            RasterRenderer2Hooks(color_scheme=color_scheme, dpmm=dpmm),
        ).render(self._command_buffer)
        output.save_to(
            destination,
            RasterFormatOptions(
                image_format=ImageFormat(image_format.value),
                pixel_format=PixelFormat(pixel_format.value),
                quality=quality,
            ),
        )

get_info

get_info() -> GerberFileInfo

Get information about Gerber file.

Source code in src\pygerber\gerberx3\api\_v2.py
def get_info(self) -> GerberFileInfo:
    """Get information about Gerber file."""
    return self._info

get_file_type

get_file_type() -> FileTypeEnum

Get type of Gerber file.

Source code in src\pygerber\gerberx3\api\_v2.py
def get_file_type(self) -> FileTypeEnum:
    """Get type of Gerber file."""
    return self._file_type

render_svg

render_svg(
    destination: BytesIO | Path | str,
    *,
    color_scheme: ColorScheme = ColorScheme.COPPER,
    scale: float = 1.0
) -> None

Render Gerber file to SVG format.

Parameters:

Name Type Description Default
destination BytesIO | Path | str

Destination to save file to. When BytesIO is provided, file will be saved to buffer. When Path or str is provided, they are treated as file path and will be used to open and save file on disk.

required
color_scheme ColorScheme

Color scheme of image, by default ColorScheme.COPPER

COPPER
scale float

Scale of image, can be used to scale very large or very small images, by default 1.0

1.0
Source code in src\pygerber\gerberx3\api\_v2.py
def render_svg(
    self,
    destination: BytesIO | Path | str,
    *,
    color_scheme: ColorScheme = ColorScheme.COPPER,
    scale: float = 1.0,
) -> None:
    """Render Gerber file to SVG format.

    Parameters
    ----------
    destination : BytesIO | Path | str
        Destination to save file to. When BytesIO is provided, file will be saved
        to buffer. When Path or str is provided, they are treated as file path
        and will be used to open and save file on disk.
    color_scheme : ColorScheme, optional
        Color scheme of image, by default ColorScheme.COPPER
    scale : float, optional
        Scale of image, can be used to scale very large or very small images, by
        default 1.0

    """
    output = SvgRenderer2(
        SvgRenderer2Hooks(color_scheme=color_scheme, scale=Decimal(scale)),
    ).render(self._command_buffer)
    output.save_to(destination)

render_raster

render_raster(
    destination: BytesIO | Path | str,
    *,
    color_scheme: ColorScheme = ColorScheme.COPPER,
    dpmm: int = 20,
    image_format: ImageFormatEnum = ImageFormatEnum.AUTO,
    pixel_format: PixelFormatEnum = PixelFormatEnum.RGB,
    quality: int = 85
) -> None

Render Gerber file to raster image.

Parameters:

Name Type Description Default
destination BytesIO | Path | str

Destination to save file to. When BytesIO is provided, file will be saved to buffer. When Path or str is provided, they are treated as file path and will be used to open and save file on disk.

required
color_scheme ColorScheme

Color scheme of image, by default ColorScheme.COPPER

COPPER
dpmm int

Resolution of image in dots per millimeter, by default 96

20
image_format ImageFormatEnum

Image format to save, by default ImageFormatEnum.AUTO

AUTO
pixel_format PixelFormatEnum

Pixel format, by default PixelFormatEnum.RGB

RGB
quality int

Image quality for JPEG format, by default 85.

85
Source code in src\pygerber\gerberx3\api\_v2.py
def render_raster(
    self,
    destination: BytesIO | Path | str,
    *,
    color_scheme: ColorScheme = ColorScheme.COPPER,
    dpmm: int = 20,
    image_format: ImageFormatEnum = ImageFormatEnum.AUTO,
    pixel_format: PixelFormatEnum = PixelFormatEnum.RGB,
    quality: int = 85,
) -> None:
    """Render Gerber file to raster image.

    Parameters
    ----------
    destination : BytesIO | Path | str
        Destination to save file to. When BytesIO is provided, file will be saved
        to buffer. When Path or str is provided, they are treated as file path
        and will be used to open and save file on disk.
    color_scheme : ColorScheme, optional
        Color scheme of image, by default ColorScheme.COPPER
    dpmm : int, optional
        Resolution of image in dots per millimeter, by default 96
    image_format : ImageFormatEnum, optional
        Image format to save, by default ImageFormatEnum.AUTO
    pixel_format : PixelFormatEnum, optional
        Pixel format, by default PixelFormatEnum.RGB
    quality: int, optional
        Image quality for JPEG format, by default 85.

    """
    output = RasterRenderer2(
        RasterRenderer2Hooks(color_scheme=color_scheme, dpmm=dpmm),
    ).render(self._command_buffer)
    output.save_to(
        destination,
        RasterFormatOptions(
            image_format=ImageFormat(image_format.value),
            pixel_format=PixelFormat(pixel_format.value),
            quality=quality,
        ),
    )

ParsedProject

Multi file project representation.

This object can be used to render multiple Gerber files to single image. It automatically performs alignment and merging of files.

Source code in src\pygerber\gerberx3\api\_v2.py
class ParsedProject:
    """Multi file project representation.

    This object can be used to render multiple Gerber files to single image.
    It automatically performs alignment and merging of files.
    """

    def __init__(self, files: List[ParsedFile]) -> None:
        self.files = files

    def render_raster(
        self,
        destination: BytesIO | Path | str,
        *,
        color_map: COLOR_MAP_T = DEFAULT_COLOR_MAP,
        dpmm: int = 20,
        image_format: ImageFormatEnum = ImageFormatEnum.AUTO,
        pixel_format: PixelFormatEnum = PixelFormatEnum.RGB,
    ) -> None:
        """Render all Gerber file, align them and merge into single file.

        Resulting image will be saved to given `destination`.

        Parameters
        ----------
        destination : BytesIO | Path | str
            Destination to save file to. When BytesIO is provided, file will be saved
            to buffer. When Path or str is provided, they are treated as file path
            and will be used to open and save file on disk.
        color_map : COLOR_MAP_T, optional
            Mapping from image type to color scheme, by default DEFAULT_COLOR_MAP
        dpmm : int, optional
            Resolution of image in dots per millimeter, by default 96
        image_format : ImageFormatEnum, optional
            Image format to save, by default ImageFormatEnum.AUTO
        pixel_format : PixelFormatEnum, optional
            Pixel format, by default PixelFormatEnum.RGB

        """
        if len(self.files) == 0:
            msg = "No files to render"
            raise ValueError(msg)

        min_x_mm = (
            min(
                self.files,
                key=lambda f: f.get_info().min_x_mm,
            )
            .get_info()
            .min_x_mm
        )

        min_y_mm = (
            min(
                self.files,
                key=lambda f: f.get_info().min_y_mm,
            )
            .get_info()
            .min_y_mm
        )

        max_x_mm = (
            max(
                self.files,
                key=lambda f: f.get_info().max_x_mm,
            )
            .get_info()
            .max_x_mm
        )

        max_y_mm = (
            max(
                self.files,
                key=lambda f: f.get_info().max_y_mm,
            )
            .get_info()
            .max_y_mm
        )

        width_mm = max_x_mm - min_x_mm
        height_mm = max_y_mm - min_y_mm

        images = [
            self._render_raster(f, color_map=color_map, dpmm=dpmm) for f in self.files
        ]
        base_image = Image.new(
            "RGBA",
            (
                int(width_mm * dpmm),
                int(height_mm * dpmm),
            ),
            (0, 0, 0, 0),
        )

        for image, file in zip(images, self.files):
            offset_x_mm = abs(min_x_mm - file.get_info().min_x_mm)
            offset_y_mm = abs(max_y_mm - file.get_info().max_y_mm)
            base_image.paste(
                image.image,
                (int(offset_x_mm * dpmm), int(offset_y_mm * dpmm)),
                image.image,
            )

        RasterImageRef(base_image).save_to(
            destination,
            options=RasterFormatOptions(
                image_format=ImageFormat(image_format.value),
                pixel_format=PixelFormat(pixel_format.value),
            ),
        )

    def _render_raster(
        self,
        file: ParsedFile,
        *,
        color_map: COLOR_MAP_T,
        dpmm: int = 20,
    ) -> RasterImageRef:
        output = RasterRenderer2(
            RasterRenderer2Hooks(
                color_scheme=color_map[file.get_file_type()],
                dpmm=dpmm,
            ),
        ).render(
            file._command_buffer,  # noqa: SLF001
        )
        if not isinstance(output, RasterImageRef):
            msg = "Expected RasterImageRef"
            raise TypeError(msg)

        return output

render_raster

render_raster(
    destination: BytesIO | Path | str,
    *,
    color_map: COLOR_MAP_T = DEFAULT_COLOR_MAP,
    dpmm: int = 20,
    image_format: ImageFormatEnum = ImageFormatEnum.AUTO,
    pixel_format: PixelFormatEnum = PixelFormatEnum.RGB
) -> None

Render all Gerber file, align them and merge into single file.

Resulting image will be saved to given destination.

Parameters:

Name Type Description Default
destination BytesIO | Path | str

Destination to save file to. When BytesIO is provided, file will be saved to buffer. When Path or str is provided, they are treated as file path and will be used to open and save file on disk.

required
color_map COLOR_MAP_T

Mapping from image type to color scheme, by default DEFAULT_COLOR_MAP

DEFAULT_COLOR_MAP
dpmm int

Resolution of image in dots per millimeter, by default 96

20
image_format ImageFormatEnum

Image format to save, by default ImageFormatEnum.AUTO

AUTO
pixel_format PixelFormatEnum

Pixel format, by default PixelFormatEnum.RGB

RGB
Source code in src\pygerber\gerberx3\api\_v2.py
def render_raster(
    self,
    destination: BytesIO | Path | str,
    *,
    color_map: COLOR_MAP_T = DEFAULT_COLOR_MAP,
    dpmm: int = 20,
    image_format: ImageFormatEnum = ImageFormatEnum.AUTO,
    pixel_format: PixelFormatEnum = PixelFormatEnum.RGB,
) -> None:
    """Render all Gerber file, align them and merge into single file.

    Resulting image will be saved to given `destination`.

    Parameters
    ----------
    destination : BytesIO | Path | str
        Destination to save file to. When BytesIO is provided, file will be saved
        to buffer. When Path or str is provided, they are treated as file path
        and will be used to open and save file on disk.
    color_map : COLOR_MAP_T, optional
        Mapping from image type to color scheme, by default DEFAULT_COLOR_MAP
    dpmm : int, optional
        Resolution of image in dots per millimeter, by default 96
    image_format : ImageFormatEnum, optional
        Image format to save, by default ImageFormatEnum.AUTO
    pixel_format : PixelFormatEnum, optional
        Pixel format, by default PixelFormatEnum.RGB

    """
    if len(self.files) == 0:
        msg = "No files to render"
        raise ValueError(msg)

    min_x_mm = (
        min(
            self.files,
            key=lambda f: f.get_info().min_x_mm,
        )
        .get_info()
        .min_x_mm
    )

    min_y_mm = (
        min(
            self.files,
            key=lambda f: f.get_info().min_y_mm,
        )
        .get_info()
        .min_y_mm
    )

    max_x_mm = (
        max(
            self.files,
            key=lambda f: f.get_info().max_x_mm,
        )
        .get_info()
        .max_x_mm
    )

    max_y_mm = (
        max(
            self.files,
            key=lambda f: f.get_info().max_y_mm,
        )
        .get_info()
        .max_y_mm
    )

    width_mm = max_x_mm - min_x_mm
    height_mm = max_y_mm - min_y_mm

    images = [
        self._render_raster(f, color_map=color_map, dpmm=dpmm) for f in self.files
    ]
    base_image = Image.new(
        "RGBA",
        (
            int(width_mm * dpmm),
            int(height_mm * dpmm),
        ),
        (0, 0, 0, 0),
    )

    for image, file in zip(images, self.files):
        offset_x_mm = abs(min_x_mm - file.get_info().min_x_mm)
        offset_y_mm = abs(max_y_mm - file.get_info().max_y_mm)
        base_image.paste(
            image.image,
            (int(offset_x_mm * dpmm), int(offset_y_mm * dpmm)),
            image.image,
        )

    RasterImageRef(base_image).save_to(
        destination,
        options=RasterFormatOptions(
            image_format=ImageFormat(image_format.value),
            pixel_format=PixelFormat(pixel_format.value),
        ),
    )

PixelFormatEnum

Bases: Enum

List of officially supported pixel formats.

Source code in src\pygerber\gerberx3\api\_v2.py
class PixelFormatEnum(Enum):
    """List of officially supported pixel formats."""

    RGB = "RGB"
    RGBA = "RGBA"

Project

Multi file project representation.

This object can be used to render multiple Gerber files to single image. It automatically performs alignment and merging of files. Files should be ordered bottom up, topmost layer last, like if adding one layer on top of previous.

Source code in src\pygerber\gerberx3\api\_v2.py
class Project:
    """Multi file project representation.

    This object can be used to render multiple Gerber files to single image.
    It automatically performs alignment and merging of files.
    Files should be ordered bottom up, topmost layer last, like if adding one layer on
    top of previous.
    """

    def __init__(self, files: List[GerberFile]) -> None:
        self.files = files

    def parse(
        self,
        *,
        on_parser_error: OnParserErrorEnum = OnParserErrorEnum.Ignore,
    ) -> ParsedProject:
        """Parse all Gerber files one by one."""
        return ParsedProject(
            [f.parse(on_parser_error=on_parser_error) for f in self.files],
        )

parse

parse(
    *,
    on_parser_error: OnParserErrorEnum = OnParserErrorEnum.Ignore
) -> ParsedProject

Parse all Gerber files one by one.

Source code in src\pygerber\gerberx3\api\_v2.py
def parse(
    self,
    *,
    on_parser_error: OnParserErrorEnum = OnParserErrorEnum.Ignore,
) -> ParsedProject:
    """Parse all Gerber files one by one."""
    return ParsedProject(
        [f.parse(on_parser_error=on_parser_error) for f in self.files],
    )