80 lines
3.0 KiB
Go

package svgtemplate
import (
"io"
"os"
"path/filepath"
"text/template"
"printer.backend/internal/paths"
)
const svgTemplate = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" width="{{.ViewBoxWidth}}mm" height="{{.ViewBoxHeight}}mm" viewBox="{{.ViewBoxMin}} {{.ViewBoxMin}} {{.ViewBoxWidth}} {{.ViewBoxHeight}}">
<defs>
<clipPath id="item-mask">
<rect x="0" y="0" width="{{.MaskWidth}}" height="{{.MaskHeight}}" rx="{{.CornerRadius}}" ry="{{.CornerRadius}}" />
</clipPath>
</defs>
<rect x="{{.ViewBoxMin}}" y="{{.ViewBoxMin}}" width="{{.ViewBoxWidth}}" height="{{.ViewBoxHeight}}" fill="#f9f9f9" />
<g clip-path="url(#item-mask)">
<rect x="{{.OuterOffsetX}}" y="{{.OuterOffsetY}}" width="{{.OuterWidth}}" height="{{.OuterHeight}}" fill="#00FF00" opacity="0.7" />
</g>
<rect x="{{.InnerOffsetX}}" y="{{.InnerOffsetY}}" width="{{.InnerWidth}}" height="{{.InnerHeight}}" rx="{{.InnerRadius}}" ry="{{.InnerRadius}}" fill="none" stroke="#0000FF" stroke-width="0.3" stroke-dasharray="1,1" />
<rect x="0" y="0" width="{{.MaskWidth}}" height="{{.MaskHeight}}" rx="{{.CornerRadius}}" ry="{{.CornerRadius}}" fill="none" stroke="#ccc" stroke-width="0.2" stroke-dasharray="2,2" />
<g stroke="#000000" stroke-width="0.3">
<line x1="0" y1="-{{.Bleed}}" x2="0" y2="-{{appendBleed .Bleed .MarkLength}}" />
<line x1="-{{.Bleed}}" y1="0" x2="-{{appendBleed .Bleed .MarkLength}}" y2="0" />
<line x1="{{.Width}}" y1="-{{.Bleed}}" x2="{{.Width}}" y2="-{{appendBleed .Bleed .MarkLength}}" />
<line x1="{{add .Width .Bleed}}" y1="0" x2="{{addThree .Width .Bleed .MarkLength}}" y2="0" />
<line x1="0" y1="{{add .Height .Bleed}}" x2="0" y2="{{addThree .Height .Bleed .MarkLength}}" />
<line x1="-{{.Bleed}}" y1="{{.Height}}" x2="-{{appendBleed .Bleed .MarkLength}}" y2="{{.Height}}" />
<line x1="{{.Width}}" y1="{{add .Height .Bleed}}" x2="{{.Width}}" y2="{{addThree .Height .Bleed .MarkLength}}" />
<line x1="{{add .Width .Bleed}}" y1="{{.Height}}" x2="{{addThree .Width .Bleed .MarkLength}}" y2="{{.Height}}" />
</g>
</svg>
`
var tmpl = template.Must(
template.New("svg").Funcs(template.FuncMap{
"appendBleed": func(bleed, mark float64) float64 { return bleed + mark },
"add": func(a, b float64) float64 { return a + b },
"addThree": func(a, b, c float64) float64 { return a + b + c },
}).Parse(svgTemplate),
)
// Write renders the SVG template to w.
func Write(w io.Writer, data Data) error {
return tmpl.Execute(w, data)
}
// OutputDir is the directory where generated SVG files are written.
const OutputDir = paths.SVGTemplateDir
// WriteFile renders the SVG template into OutputDir.
func WriteFile(path string, data Data) error {
outPath := filepath.Join(OutputDir, filepath.Base(filepath.Clean(path)))
if err := os.MkdirAll(OutputDir, 0o755); err != nil {
return err
}
file, err := os.Create(outPath)
if err != nil {
return err
}
defer file.Close()
if err := Write(file, data); err != nil {
return err
}
return file.Close()
}