SVG graphics

SVG graphics

The svgreader package converts SVG graphics to PDF drawing operators. No external tools (like Inkscape) are needed.

Supported SVG subset

Element Attributes
<path> All path commands: M, L, H, V, C, S, Q, T, A, Z
<rect> x, y, width, height, rx, ry (rounded corners)
<circle> cx, cy, r
<ellipse> cx, cy, rx, ry
<line> x1, y1, x2, y2
<polyline> points
<polygon> points
<g> Groups with transform and style inheritance
<text> Via TextRenderer interface (see below)
<linearGradient> x1, y1, x2, y2, gradientUnits, gradientTransform; as a fill
<radialGradient> cx, cy, r, fx, fy, fr, gradientUnits, gradientTransform; as a fill

Styling, on the <svg> element and below: fill, stroke, stroke-width, stroke-linecap, stroke-linejoin, fill-rule, opacity, fill-opacity, stroke-opacity, stop-opacity, color. Colors as hex (#rgb, #rgba, #rrggbb, #rrggbbaa), named colors, rgb(), hsl(), the colors defined in the document, and currentColor. Inline CSS via the style attribute is supported.

Transforms: translate(), rotate(), scale(), matrix(), skewX(), skewY().

Including an SVG

import (
    "strings"

    "github.com/boxesandglue/boxesandglue/backend/bag"
    "github.com/boxesandglue/boxesandglue/backend/node"
    "github.com/boxesandglue/svgreader"
)

First, parse the SVG document:

svgDoc, err := svgreader.Parse(strings.NewReader(svgString))

or from a file:

file, err := os.Open("diagram.svg")
svgDoc, err := svgreader.Parse(file)

Then create a node with CreateSVGNodeFromDocument:

svgNode := f.Doc.CreateSVGNodeFromDocument(svgDoc, bag.MustSP("80mm"), 0)

The third argument is the height. When set to 0, the height is calculated automatically from the SVG’s aspect ratio (viewBox). Similarly, you can set the width to 0 and specify only the height. If both are 0, the SVG’s natural dimensions are used: its width and height, or its viewBox. As in a browser a user unit is a CSS pixel, 0.75pt, so <svg width="96"> is 72pt wide. Lengths with units, mm or pt for example, take the factors of CSS, on the <svg> element and inside the drawing.

Nothing outside the SVG’s viewport is drawn: the node clips the drawing to its size, as a browser does. Only an SVG without any size, whose node has no area, is drawn unclipped.

To show only a region of the SVG, use CreateSVGNodeFromDocumentCrop. The region, a node.ImageCrop in the units of the SVG’s natural size measured from its top left corner, becomes the viewport: it gives the natural size and the aspect ratio, and the drawing is clipped to it.

func (d *PDFDocument) CreateSVGNodeFromDocumentCrop(svgDoc *svgreader.Document, crop node.ImageCrop, width bag.ScaledPoint, height bag.ScaledPoint, textRenderer ...svgreader.TextRenderer) *node.Rule
crop := node.ImageCrop{X: 50, Y: 20, Width: 100, Height: 80}
svgNode := f.Doc.CreateSVGNodeFromDocumentCrop(svgDoc, crop, bag.MustSP("50mm"), 0)

For more settings at once use CreateSVGNodeWithOptions. Besides the crop and the text renderer, SVGOptions takes the color that currentColor stands for where the drawing sets no color of its own. Without it, currentColor is black. htmlbag passes the CSS color of an inline <svg>, so an icon takes the color of the text around it.

func (d *PDFDocument) CreateSVGNodeWithOptions(svgDoc *svgreader.Document, width bag.ScaledPoint, height bag.ScaledPoint, opts SVGOptions) *node.Rule
type SVGOptions struct {
	// Crop is the region of the SVG to show, in the units of its natural size,
	// measured from its top left corner. A crop without area shows all of it.
	Crop node.ImageCrop
	// TextRenderer draws the <text> elements. Without one they are skipped.
	TextRenderer svgreader.TextRenderer
	// CurrentColor is the color that currentColor stands for where the drawing
	// sets no color of its own: for an inline svg in HTML the CSS color of
	// the element. Nil means black.
	CurrentColor *color.Color
}
red := f.GetColor("#c00")
svgNode := f.Doc.CreateSVGNodeWithOptions(svgDoc, bag.MustSP("5mm"), 0, document.SVGOptions{CurrentColor: red})

Place it on the page like any other node:

vl := node.Vpack(svgNode)
p.OutputAt(bag.MustSP("2cm"), bag.MustSP("26cm"), vl)

Complete example

package main

import (
    "log"
    "strings"

    "github.com/boxesandglue/boxesandglue/backend/bag"
    "github.com/boxesandglue/boxesandglue/backend/node"
    "github.com/boxesandglue/boxesandglue/frontend"
    "github.com/boxesandglue/svgreader"
)

const mySVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 130">
  <rect x="10" y="10" width="180" height="110" rx="8"
        fill="#eef" stroke="#336" stroke-width="2"/>
  <circle cx="100" cy="65" r="40"
          fill="none" stroke="red" stroke-width="1.5"/>
  <path d="M 30 100 C 60 30, 140 30, 170 100"
        fill="none" stroke="blue" stroke-width="2"/>
</svg>`

func main() {
    f, err := frontend.New("svg-example.pdf")
    if err != nil {
        log.Fatal(err)
    }

    svgDoc, err := svgreader.Parse(strings.NewReader(mySVG))
    if err != nil {
        log.Fatal(err)
    }

    p := f.Doc.NewPage()
    svgNode := f.Doc.CreateSVGNodeFromDocument(svgDoc, bag.MustSP("60mm"), 0)
    p.OutputAt(bag.MustSP("2cm"), bag.MustSP("26cm"), node.Vpack(svgNode))
    p.Shipout()
    f.Doc.Finish()
}

Text in SVG

SVG <text> elements require a TextRenderer to convert text into PDF operators with proper font shaping. Without a renderer, text elements are silently skipped.

To enable text rendering, implement the svgreader.TextRenderer interface and pass it in RenderOptions:

type TextRenderer interface {
    RenderText(text string, x, y, fontSize float64,
        fontFamily, fontWeight, fontStyle string,
        fill svgreader.Color) string
}

The RenderText method receives the text content, position, font properties, and fill color. It returns a string of PDF operators (e.g. BT ... ET) that render the text.

Using SVGTextRenderer

The frontend package includes SVGTextRenderer, a ready-made implementation that uses the document’s font system. Font-family names in the SVG are resolved against the document’s registered FontFamilies:

tr := frontend.NewSVGTextRenderer(f)
tr.DefaultFamily = myFontFamily  // fallback for unresolved font-family names

svgNode := f.Doc.CreateSVGNodeFromDocument(svgDoc, bag.MustSP("80mm"), 0, tr)

Low-level approach

You can also use RenderPDF directly for full control. It does not clip: the stream draws everything in the SVG, also what lies outside the viewport.

svgDoc, _ := svgreader.Parse(reader)
stream := svgDoc.RenderPDF(svgreader.RenderOptions{
    Width:        width,
    Height:       height,
    TextRenderer: myTextRenderer,
})

rule := node.NewRule()
rule.Width = bag.ScaledPointFromFloat(width)
rule.Height = bag.ScaledPointFromFloat(height)
rule.Hide = true
rule.Pre = stream