2026-05-26 17:11:09 +02:00

55 lines
1.2 KiB
Go

package platepdf
import (
"fmt"
"regexp"
"strconv"
"strings"
)
var svgAttrRE = regexp.MustCompile(`(?i)(\w+)\s*=\s*"([^"]*)"`)
func svgAttrValue(openTag, name string) string {
for _, m := range svgAttrRE.FindAllStringSubmatch(openTag, -1) {
if strings.EqualFold(m[1], name) {
return m[2]
}
}
return ""
}
// svgViewportMM reads width/height from the root <svg> element (supports mm suffix).
func svgViewportMM(data []byte) (widthMM, heightMM float64, err error) {
s := string(data)
open := strings.Index(s, "<svg")
if open < 0 {
return 0, 0, fmt.Errorf("invalid svg: missing root element")
}
tagEnd := strings.Index(s[open:], ">")
if tagEnd < 0 {
return 0, 0, fmt.Errorf("invalid svg: malformed root element")
}
tagEnd += open
w, err := parseLengthMM(svgAttrValue(s[open:tagEnd], "width"))
if err != nil {
return 0, 0, err
}
h, err := parseLengthMM(svgAttrValue(s[open:tagEnd], "height"))
if err != nil {
return 0, 0, err
}
return w, h, nil
}
func parseLengthMM(s string) (float64, error) {
s = strings.TrimSpace(s)
if s == "" {
return 0, fmt.Errorf("empty length")
}
if strings.HasSuffix(s, "mm") {
return strconv.ParseFloat(strings.TrimSuffix(s, "mm"), 64)
}
return strconv.ParseFloat(s, 64)
}