| 1 |
package tinysvg |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"os" |
| 6 |
) |
| 7 |
|
| 8 |
// Document is an XML document, with a title and a root tag |
| 9 |
type Document struct { |
| 10 |
title []byte |
| 11 |
root *Tag |
| 12 |
} |
| 13 |
|
| 14 |
// NewDocument creates a new XML/HTML/SVG image, with a root tag. |
| 15 |
// If rootTagName contains "<" or ">", it can be used for preceding declarations, |
| 16 |
// like <!DOCTYPE html> or <?xml version=\"1.0\"?>. |
| 17 |
// Returns a pointer to a Document. |
| 18 |
func NewDocument(title, rootTagName []byte) *Document { |
| 19 |
var image Document |
| 20 |
image.title = title |
| 21 |
rootTag := NewTag(rootTagName) |
| 22 |
image.root = rootTag |
| 23 |
return &image |
| 24 |
} |
| 25 |
|
| 26 |
// GetTag searches all tags for the given name |
| 27 |
func (image *Document) GetTag(name []byte) (*Tag, error) { |
| 28 |
return image.root.GetTag(name) |
| 29 |
} |
| 30 |
|
| 31 |
// GetRoot returns the root tag of the image |
| 32 |
func (image *Document) GetRoot() *Tag { |
| 33 |
return image.root |
| 34 |
} |
| 35 |
|
| 36 |
// AddContent adds content to the body tag. |
| 37 |
// Returns the body tag and nil if successful. |
| 38 |
// Returns and an error if no body tag is found, else nil. |
| 39 |
func (image *Document) AddContent(content []byte) (*Tag, error) { |
| 40 |
body, err := image.root.GetTag([]byte("body")) |
| 41 |
if err == nil { |
| 42 |
body.AddContent(content) |
| 43 |
} |
| 44 |
return body, err |
| 45 |
} |
| 46 |
|
| 47 |
// Bytes renders the image as an XML document |
| 48 |
func (image *Document) Bytes() []byte { |
| 49 |
return image.root.Bytes() |
| 50 |
} |
| 51 |
|
| 52 |
// String renders the image as an XML document |
| 53 |
func (image *Document) String() string { |
| 54 |
return image.root.String() |
| 55 |
} |
| 56 |
|
| 57 |
// SaveSVG will save the current image as an SVG file |
| 58 |
func (image *Document) SaveSVG(filename string) error { |
| 59 |
return os.WriteFile(filename, image.Bytes(), 0644) |
| 60 |
} |
| 61 |
|
| 62 |
// WriteTo will write the current image to the given io.Writer. |
| 63 |
// Returns bytes written and possibly an error. |
| 64 |
// This also fullfills the io.WriterTo interface. |
| 65 |
func (image *Document) WriteTo(w io.Writer) (int64, error) { |
| 66 |
return image.root.WriteTo(w) |
| 67 |
} |