python svg to Gcode
- 安装
pip3 install svgpathtools
- 代码样例
import os
from svgpathtools import Path, Line, QuadraticBezier, CubicBezier, Arc
from svgpathtools import svg2paths, wsvg
import numpy as np
HOME = "G28\n"
UNITS_MILLIMETRES = "G21\n"
def svg_to_gcode(lg, width=10, z_offset=5, n=0, num=0):
# lg,n:组成文件 z_offset 落笔的深度 num:第几次不拼接多个文字的话不需要考虑
FEEDRATE = 1500
Z_OFFSET = 0
START_X = num * width
START_Y = 0
WIDTH = width # mm
paths, attributes = svg2paths("./image/" + lg + ".svg")
gcode = open("./image/" + lg + n + ".gcode", "w")
# Add boilerplate code
if num == 0:
gcode.write(HOME)
gcode.write(UNITS_MILLIMETRES)
gcode.write("G1 F" + str(FEEDRATE) + "\n")
gcode.write("G1 Z" + str(Z_OFFSET) + "\n")
X = np.linspace(0, 1, 100)
X_coords = []
Y_coords = []
for path in paths:
for curve in path:
p = curve.poly()
X_coords.extend(p(X).real)
Y_coords.extend(-p(X).imag)
SCALE = WIDTH / (max(X_coords) - min(X_coords))
Y_OFFSET = START_Y - min(np.array(Y_coords) * SCALE)
X_OFFSET = START_X - min(np.array(X_coords) * SCALE)
for path in paths:
for subpath in path.continuous_subpaths():
X_coords = []
Y_coords = []
if subpath:
for curve in subpath:
p = curve.poly()
if (p.order == 1):
x = [p(0).real, p(1).real]
y = [-p(0).imag, -p(1).imag]
else:
x = p(X).real
y = -p(X).imag
x = np.array(x) * SCALE + X_OFFSET
y = np.array(y) * SCALE + Y_OFFSET
X_coords.extend(x)
Y_coords.extend(y)
gcode.write("G1 X" + str(X_coords[0]) + " Y" + str(Y_coords[0]) + "\n")
gcode.write("G1 Z" + str(Z_OFFSET + z_offset) + "\n")
for x_coord, y_coord in zip(X_coords, Y_coords):
gcode.write("G1 X" + str(x_coord) + " Y" + str(y_coord) + "\n")
gcode.write("G1 Z" + str(Z_OFFSET) + "\n")
gcode.write("G1 X" + str((num + 1) * width) + " Y0" + "\n")
gcode.write("G1 Z" + str(Z_OFFSET) + "\n")