pythonlayoutdxfezdxf

change page setup with ezdxf


i would like to change the properties of layouts with ezdxf. There is a function called page_setup, but it is not working in my case. This is a minimal example created from the API. What is wrong with my approach?

import ezdxf

# Create a new DXF document.
doc = ezdxf.new(dxfversion="R2010", setup=True)
doc.units = ezdxf.units.M

# Create new table entries (layers, linetypes, text styles, ...).
doc.layers.add("TEXTLAYER", color=0)

# DXF entities (LINE, TEXT, ...) reside in a layout (modelspace,
# paperspace layout or block definition).
msp = doc.modelspace()

# Add entities to a layout by factory methods: layout.add_...()
msp.add_line((0, 0), (20, 0), dxfattribs={"color": 0})
msp.add_text(
    "Test",
    dxfattribs={
        "layer": "TEXTLAYER"
    }).set_pos((0, 0.2), align="CENTER") #halign, valign

# Create Layout
psp = doc.layout("Layout1")
psp.page_setup(size=(297, 210),
            margins=(0, 0, 0, 0),
            units="mm", offset=(0, 0),
            rotation=0, scale=16,
            name="ezdxf ",
            device="DWG to PDF.pc3")

a4_x = 21
a4_y = 29.7

a4_x = a4_x * 0.01
a4_y = a4_y * 0.01

# Add viewport
psp.add_viewport(
    center=(a4_x*(0.5),a4_y*(0.5)),
    size=(a4_x,a4_y),
    view_center_point=(0,0),
    view_height=100)

# Needs to be done twice for some reason
psp.add_viewport(
    center=(a4_x*(0.5),a4_y*(0.5)),
    size=(a4_x,a4_y),
    view_center_point=(0,0),
    view_height=100)

# Save as File
doc.saveas("test.dxf")

Solution

  • I assume you got your example from an outdated documentation. I refactored your example so it works with the latest version of ezdxf.

    from typing import cast
    import ezdxf
    from ezdxf.layouts import Paperspace
    from ezdxf.enums import TextEntityAlignment
    
    doc = ezdxf.new(dxfversion="R2010", setup=True)
    doc.units = ezdxf.units.M
    doc.layers.add("TEXTLAYER", color=0)
    msp = doc.modelspace()
    
    msp.add_line((0, 0), (20, 0), dxfattribs={"color": 0})
    msp.add_text("Test", dxfattribs={"layer": "TEXTLAYER"}).set_placement(
        (0, 0.2), align=TextEntityAlignment.CENTER
    )
    
    # get the existing (default) "Layout1":
    psp = cast(Paperspace, doc.layout("Layout1"))
    a4_width = 210
    a4_height = 297
    
    # reset page properties:
    psp.page_setup(size=(a4_width, a4_height), margins=(0, 0, 0, 0))
    
    # add a new viewport to the paperspace:
    psp.add_viewport(
        # center of viewport in paperspace:
        center=(a4_width * 0.5, a4_height * 0.5),
        # size of the viewport in paperspace:
        size=(a4_width, a4_height),
        # Define the portion of the modelspace to show.
        # center in modelspace:
        view_center_point=(0, 0),
        # the view height to show in modelspace units:
        view_height=100,
        # The view width is proportional to the viewport size!
    )
    doc.saveas("test.dxf")
    

    enter image description here