diff --git a/examples/simple/README.md b/examples/simple/README.md new file mode 100644 index 0000000..27f4e83 --- /dev/null +++ b/examples/simple/README.md @@ -0,0 +1,12 @@ +# Simple example + +This example shows how to render Typst documents directly from strings in Go. + +## The pros and cons + +The main advantage of this method is that it's really easy to set up. +In the most simple case you build your Typst markup by concatenating strings, or by using `fmt.Sprintf`. + +The downside is that the final Typst markup is only generated on demand. +This means that you can't easily use the existing Typst tooling to write, update or debug your Typst markup. +Especially as your your documents get more complex, you should switch to other methods. diff --git a/examples/simple/main.go b/examples/simple/main.go new file mode 100644 index 0000000..ae8920b --- /dev/null +++ b/examples/simple/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "bytes" + "fmt" + "log" + "os" + "time" + + "github.com/Dadido3/go-typst" +) + +func main() { + // Convert a time.Time value into Typst markup. + date, err := typst.MarshalVariable(time.Now()) + if err != nil { + log.Panicf("Failed to marshal date into Typst markup: %v", err) + } + + // Write Typst markup into buffer. + var markup bytes.Buffer + fmt.Fprintf(&markup, `= Hello world + +This document was created at #%s.display() using typst-go.`, date) + + // Compile the prepared markup with Typst and write the result it into `output.pdf`. + f, err := os.Create("output.pdf") + if err != nil { + log.Panicf("Failed to create output file: %v.", err) + } + defer f.Close() + + typstCLI := typst.CLI{} + if err := typstCLI.Compile(&markup, f, nil); err != nil { + log.Panic("failed to compile document: %w", err) + } +} diff --git a/examples/simple/main_test.go b/examples/simple/main_test.go new file mode 100644 index 0000000..96ccbb0 --- /dev/null +++ b/examples/simple/main_test.go @@ -0,0 +1,16 @@ +package main + +import ( + "testing" +) + +// Run the example as a test. +func TestMain(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Error(r) + } + }() + + main() +} diff --git a/examples/simple/output.pdf b/examples/simple/output.pdf new file mode 100644 index 0000000..24f0857 Binary files /dev/null and b/examples/simple/output.pdf differ