Skip to content

api

The api module provides simple, high-level API for rendering Gerber X3/X2 files.

CompositeImage

Image composed of multiple sub-images.

CompositePillowImage

Bases: CompositeImage

Image composed of multiple sub-images.

get_sub_images

get_sub_images() -> Sequence[PillowImage]

Get sequence containing sub-images.

get_image

get_image() -> Image

Get image composed out of sub-images.

CompositeView

View composed of multiple Gerber files.

Composite view is a generalized concept of a top / bottom / inner layer view extracted from a Gerber project. Usually it does not make sense to render all layers at once, as bottom layers will be simply covered by top layers.

This object can be used to render selected 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.

files property

files: tuple[GerberFile, ...]

Get sequence of Gerber files.

render_with_pillow

render_with_pillow(dpmm: int = 20) -> CompositePillowImage

Render project to raster image using Pillow.

FileTypeEnum

Bases: Enum

Enumeration of possible Gerber file types.

COPPER class-attribute instance-attribute

COPPER = 'COPPER'

Copper layer.

MASK class-attribute instance-attribute

MASK = 'MASK'

Mask layer.

PASTE class-attribute instance-attribute

PASTE = 'PASTE'

Paste layer.

SILK class-attribute instance-attribute

SILK = 'SILK'

Silk layer.

EDGE class-attribute instance-attribute

EDGE = 'EDGE'

Edge layer.

PLATED class-attribute instance-attribute

PLATED = 'PLATED'

Plated layer.

NON_PLATED class-attribute instance-attribute

NON_PLATED = 'NON_PLATED'

Non-plated layer.

PROFILE class-attribute instance-attribute

PROFILE = 'PROFILE'

Profile layer.

SOLDERMASK class-attribute instance-attribute

SOLDERMASK = 'SOLDERMASK'

Solder mask layer.

LEGEND class-attribute instance-attribute

LEGEND = 'LEGEND'

Legend layer.

COMPONENT class-attribute instance-attribute

COMPONENT = 'COMPONENT'

Component layer.

GLUE class-attribute instance-attribute

GLUE = 'GLUE'

Glue layer.

CARBONMASK class-attribute instance-attribute

CARBONMASK = 'CARBONMASK'

Carbon mask layer.

GOLDMASK class-attribute instance-attribute

GOLDMASK = 'GOLDMASK'

Gold mask layer.

HEATSINKMASK class-attribute instance-attribute

HEATSINKMASK = 'HEATSINKMASK'

Heat sink mask layer.

PEELABLEMASK class-attribute instance-attribute

PEELABLEMASK = 'PEELABLEMASK'

Peelable mask layer.

SILVERMASK class-attribute instance-attribute

SILVERMASK = 'SILVERMASK'

Silver mask layer.

TINMASK class-attribute instance-attribute

TINMASK = 'TINMASK'

Tin mask layer.

DEPTHROUT class-attribute instance-attribute

DEPTHROUT = 'DEPTHROUT'

Depth out layer.

VCUT class-attribute instance-attribute

VCUT = 'VCUT'

V cut layer.

VIAFILL class-attribute instance-attribute

VIAFILL = 'VIAFILL'

Via fill layer.

PADS class-attribute instance-attribute

PADS = 'PADS'

Pads layer.

OTHER class-attribute instance-attribute

OTHER = 'OTHER'

Other layer.

UNDEFINED class-attribute instance-attribute

UNDEFINED = 'UNDEFINED'

Unrecognized layer sentinel.

INFER_FROM_EXTENSION class-attribute instance-attribute

INFER_FROM_EXTENSION = 'INFER_FROM_EXTENSION'

Represents request to identify layer type from file extension.

INFER_FROM_ATTRIBUTES class-attribute instance-attribute

INFER_FROM_ATTRIBUTES = 'INFER_FROM_ATTRIBUTES'

Represents request to identify layer type from file attributes.

INFER class-attribute instance-attribute

INFER = 'INFER'

Represents request to identify layer type from file extension or attributes.

infer_from_attributes classmethod

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

Infer file type from file extension.

PathToGerberJobProjectNotDefinedError

Bases: GerberX3APIError

Raised when path to Gerber Job project is not defined.

GerberFile

Generic representation of Gerber file.

This objects provides interface for loading and parsing Gerber files.

source_code property

source_code: str

Gerber source code.

file_type property

file_type: FileTypeEnum

File type classification.

from_file classmethod

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

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

Parameters:

  • file_path (str | Path) –

    Path to Gerber file on disk.

  • file_type (FileTypeEnum, default: INFER ) –

    File type classification, by default FileTypeEnum.INFER

from_str classmethod

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

Initialize GerberFile object with Gerber source code from string.

Parameters:

  • source_code (str) –

    Gerber source code as strobject.

  • file_type (FileTypeEnum, default: INFER ) –

    File type classification, by default FileTypeEnum.INFER

Returns:

  • Self

    New instance of GerberFile object.

from_buffer classmethod

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

Initialize object with Gerber source code from readable buffer.

Parameters:

  • buffer (TextIO) –

    Readable buffer with Gerber source code.

  • file_type (FileTypeEnum, default: INFER ) –

    File type classification, by default FileTypeEnum.INFER

set_parser_options

set_parser_options(**options: Any) -> Self

Set parser options for this Gerber file.

This is a window into advanced parser settings, only reason to use this method should be for advanced user to tweak parser behavior without binging more advanced PyGerber APIs into consideration.

Parameters:

  • **options (Any, default: {} ) –

    Parser options.

Returns:

  • Self

    Returns self for method chaining.

set_compiler_options

set_compiler_options(**options: Any) -> Self

Set compiler options for this Gerber file.

This is a window into advanced compiler settings, only reason to use this method should be for advanced user to tweak compiler behavior without binging more advanced PyGerber APIs into consideration.

Parameters:

  • **options (Any, default: {} ) –

    Compiler options.

Returns:

  • Self

    Returns self for method chaining

set_color_map

set_color_map(color_map: COLOR_MAP_T) -> Self

Set color map for rendering of this Gerber file.

Gerber files themselves do not contain color data. Therefore only way to get colorful image is to explicitly ask rendering backend to apply particular color to image.

Parameters:

  • color_map (COLOR_MAP_T) –

    Color map to be used for rendering Gerber file. You can use one of two predefined color maps: DEFAULT_COLOR_MAP or DEFAULT_ALPHA_COLOR_MAP or your own. They are both available in pygerber.gerber.api module. In most basic cases there is no need to alter default color map, as it already includes alpha channel thus allows for image stacking.

Returns:

  • Self

    Returns self for method chaining.

render_with_pillow

render_with_pillow(
    style: Optional[Style] = None, dpmm: int = 20
) -> PillowImage

Render Gerber file to raster image using rendering backend based on Pillow library.

Parameters:

  • style (Style, default: None ) –

    Style (color scheme) of rendered image, if value is None, file_type will be used. file_type was one of FileTypeEnum.INFER* attempt will be done to guess file_type based on extension and/or attributes, by default None

  • dpmm (int, default: 20 ) –

    Resolution of image in dots per millimeter, by default 20

render_with_shapely

render_with_shapely(
    style: Optional[Style] = None,
) -> ShapelyImage

Render Gerber file to vector image using rendering backend based on Shapely library.

Parameters:

  • style (Style, default: None ) –

    Style (color scheme) of rendered image, if value is None, file_type will be used. file_type was one of FileTypeEnum.INFER* attempt will be done to guess file_type based on extension and/or attributes, by default None Only foreground color is used, as all operations with clear polarity are performing actual boolean difference operations on geometry.

format

format(output: TextIO, options: Optional[Options]) -> None

Format Gerber code and write it to output stream.

formats

formats(options: Optional[Options]) -> str

Format Gerber code and return it as str object.

sha256

sha256() -> str

SHA256 hash of Gerber source code.

Image

The Image class is a base class for all rendered images returned by GerberFile.render_with_* methods.

get_image_space

get_image_space() -> ImageSpace

Get information about image space.

ImageSpace

Container for information about Gerber image space.

units property

units: Units

Units of image space.

min_x property

min_x: float

Minimum X coordinate in image in file defined unit.

min_y property

min_y: float

Minimum Y coordinate in image in file defined unit.

max_x property

max_x: float

Maximum X coordinate in image in file defined unit.

max_y property

max_y: float

Maximum T coordinate in image in file defined unit.

dpmm property

dpmm: int

Resolution of image in dots per millimeter.

min_x_mm

min_x_mm() -> float

Minimum X coordinate of image in millimeters.

min_y_mm

min_y_mm() -> float

Minimum Y coordinate of image in millimeters.

max_x_mm

max_x_mm() -> float

Maximum X coordinate of image in millimeters.

max_y_mm

max_y_mm() -> float

Maximum Y coordinate of image in millimeters.

width_mm

width_mm() -> float

Width of image in millimeters.

height_mm

height_mm() -> float

Height of image in millimeters.

center_x_mm

center_x_mm() -> float

Center X coordinate of image in millimeters.

This value can be negative.

center_y_mm

center_y_mm() -> float

Center Y coordinate of image in millimeters.

This value can be negative.

min_x_pixels

min_x_pixels() -> int

Minimum X coordinate of image in pixels.

This value can be negative.

min_y_pixels

min_y_pixels() -> int

Minimum Y coordinate of image in pixels.

This value can be negative.

max_x_pixels

max_x_pixels() -> int

Maximum X coordinate of image in pixels.

max_y_pixels

max_y_pixels() -> int

Maximum Y coordinate of image in pixels.

PillowImage

Bases: Image

The PillowImage class is a rendered image returned by GerberFile.render_with_pillow method.

get_image

get_image() -> Image

Get image object.

ShapelyImage

Bases: Image

The ShapelyImage class is a rendered image returned by GerberFile.render_with_shapely method.

save

save(destination: str | Path | TextIO) -> None

Write rendered image as SVG to location or buffer.

Parameters:

  • destination (str | Path) –

    str and Path objects are interpreted as file paths and opened with truncation. TextIO-like (files, StringIO) objects are written to directly.

Units

Bases: Enum

The Units enum contains possible Gerber file units.

DesignRules

Bases: _ModelType

Design Rules.

FilesAttributes

Bases: _ModelType

Files Attributes.

GeneralSpecs

Bases: _ModelType

General Specs.

GenerationSoftware

Bases: _ModelType

Generation Software.

GerberJobFile

Bases: _ModelType

Gerber Job File.

from_file classmethod

from_file(path: str | Path) -> GerberJobFile

Load Gerber Job File.

Parameters:

  • path (str | Path) –

    Path to a .gbrjob file.

Returns:

to_project

to_project(*, path: Optional[Path] = None) -> Project

Convert Gerber Job File to PyGerber Project object.

Parameters:

  • path (Optional[Path], default: None ) –

    If GerberJobFile was not loaded from file on disk, you must provide a path to where that file should be, including file name, by default None

Returns:

  • Project

    New project object containing Gerber files from Gerber Job File.

Header

Bases: _ModelType

Header.

MaterialStackup

Bases: _ModelType

Material Stackup.

ProjectId

Bases: _ModelType

Project ID.

Size

Bases: _ModelType

Size.

Options

Bases: BaseModel

The Options class aggregates configuration options for the Gerber formatter.

For detailed description of individual options, please visit (TODO: Add doc link).

indent_character class-attribute instance-attribute

indent_character: Literal[' ', '\t'] = Field(default=' ')

Character used for indentation, by default " " (space).

macro_body_indent class-attribute instance-attribute

macro_body_indent: Union[str, int] = Field(default=0)

Indentation of macro body, could be either a string containing desired whitespaces or integer which will be used to create indent string based on indent_character, by default 0 which results in no indentation.

macro_param_indent class-attribute instance-attribute

macro_param_indent: Union[str, int] = Field(default=0)

Indentation of macro parameters, could be either a string containing desired whitespaces or integer which will be used to create indent string based on indent_character, by default 0 which results in no indentation.

macro_param_indent indentation is added on top of macro body indentation.

macro_param_indent has effect only when macro_split_mode is PARAMETERS.

macro_split_mode class-attribute instance-attribute

macro_split_mode: MacroSplitMode = Field(
    default=SplitOnPrimitives
)

Changes how macro definitions are formatted, by default MacroSplitMode.SplitOnPrimitives.


When NoSplit is selected, macro definition will be formatted as a single line.

%AMDonut*1,1,$1,$2,$3*$4=$1x0.75*1,0,$4,$2,$3*%

When SplitOnPrimitives is selected, macro definition will be formatted with each primitive in a new line.

%AMDonut*
1,1,$1,$2,$3*
$4=$1x0.75*
1,0,$4,$2,$3*%

When SplitOnParameters is selected, macro definition will be formatted with each primitive on a new line and each parameter of a primitive on a new line.

%AMDonut*
1,
1,
$1,
$2,
$3*
$4=$1x0.75*
1,
0,
$4,
$2,
$3*%

Use macro_body_indent and macro_param_indent to control indentation.

macro_end_in_new_line class-attribute instance-attribute

macro_end_in_new_line: MacroEndInNewLine = Field(default=No)

Toggles placing % sign which marks the end of macro in new line, by default MacroEndInNewLine.No

block_aperture_body_indent class-attribute instance-attribute

block_aperture_body_indent: Union[str, int] = Field(
    default=0
)

Indentation of block aperture definition body, could be either a string containing desired whitespaces or integer which will be used to create indent string based indent_character, by default 0 which results in no indentation.

This indentations stacks for nested block apertures.

step_and_repeat_body_indent class-attribute instance-attribute

step_and_repeat_body_indent: Union[str, int] = Field(
    default=0
)

Indentation of step and repeat definition body, could be either a string containing desired whitespaces or integer which will be used to create indent string based indent_character, by default 0 which results in no indentation.

This indentations stacks for nested step and repeat blocks.

float_decimal_places class-attribute instance-attribute

float_decimal_places: int = Field(default=-1)

Limit number of decimal places shown for float values, by default -1 which means as many decimal places as needed.

float_trim_trailing_zeros class-attribute instance-attribute

float_trim_trailing_zeros: FloatTrimTrailingZeros = Field(
    default=Yes
)

Remove trailing zeros from floats, by default FloatTrimTrailingZeros.Yes.

When this is set to FloatTrimTrailingZeros.Yes, after floating point number is formatted with respect to float_decimal_places, trailing zeros are removed. If all zeros after decimal point are removed, decimal point is also removed.

d01_indent class-attribute instance-attribute

d01_indent: Union[str, int] = Field(default=0)

Custom indentation of D01 command, could be either a string containing desired whitespaces or integer which will be used to create indent string based indent_character, by default 0

d02_indent class-attribute instance-attribute

d02_indent: Union[str, int] = Field(default=0)

Custom indentation of D02 command, could be either a string containing desired whitespaces or integer which will be used to create indent string based indent_character, by default 0

d03_indent class-attribute instance-attribute

d03_indent: Union[str, int] = Field(default=0)

Custom indentation of D03 command, could be either a string containing desired whitespaces or integer which will be used to create indent string based indent_character, by default 0

line_end class-attribute instance-attribute

line_end: Literal['\n', '\r\n'] = Field(default='\n')

Line ending character, Unix or Windows style, by default " " (Unix style) If strip_whitespace is enabled, this setting is ignored and no line endings are added.

empty_line_before_polarity_switch class-attribute instance-attribute

empty_line_before_polarity_switch: (
    EmptyLineBeforePolaritySwitch
) = Field(default=No)

Add empty line before polarity switch, by default EmptyLineBeforePolaritySwitch.Yes

Inserting empty lines before polarity switches enhances visual separation of sequences of commands with different polarities.

keep_non_standalone_codes class-attribute instance-attribute

keep_non_standalone_codes: KeepNonStandaloneCodes = Field(
    default=Keep
)

Keep non-standalone codes in the output, by default KeepNonStandaloneCodes.Keep

If this option is disabled, legacy merged code forms like G70D02* will be divided into two separate commands, G70* and D02*, otherwise they will be kept as is.

remove_g54 class-attribute instance-attribute

remove_g54: RemoveG54 = Field(default=Keep)

Remove G54 code from output, by default RemoveG54.Keep

G54 code has no effect on the output, it was used in legacy files to prefix select aperture command.

remove_g55 class-attribute instance-attribute

remove_g55: RemoveG55 = Field(default=Keep)

Remove G55 code from output, by default RemoveG55.Keep

G55 code has no effect on the output, it was used in legacy files to prefix flash command.

explicit_parenthesis class-attribute instance-attribute

explicit_parenthesis: ExplicitParenthesis = Field(
    default=KeepOriginal
)

Toggle explicit parenthesis around all mathematical expressions within macro, by default ExplicitParenthesis.KeepOriginal

strip_whitespace class-attribute instance-attribute

strip_whitespace: StripWhitespace = Field(default=Default)

Toggle stripping of whitespace from the output, by default StripWhitespace.Default which results in normal whitespace handling.

Style

Bases: ModelType

Style class represents colors which should be used for coloring rendered image layer.

presets

Bases: Namespace

Style.presets contains predefined styles for convenience.

SILK class-attribute

SILK: Style

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: Style

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: Style

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: Style

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: Style

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: Style

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: Style

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: Style

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: Style

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

DEBUG_1 class-attribute

DEBUG_1: Style

Debug color scheme.

DEBUG_1_ALPHA class-attribute

DEBUG_1_ALPHA: Style

Debug color scheme with alpha channel.

BLACK_WHITE class-attribute

BLACK_WHITE: Style

Black and white color scheme.

BLACK_WHITE_ALPHA class-attribute

BLACK_WHITE_ALPHA: Style

Black and white color scheme with alpha channel.