mirror of
https://github.com/Dadido3/go-typst.git
synced 2025-04-11 12:13:16 +00:00
Add simple example
This commit is contained in:
parent
9268a6691e
commit
2a1d2990e7
12
examples/simple/README.md
Normal file
12
examples/simple/README.md
Normal file
@ -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.
|
37
examples/simple/main.go
Normal file
37
examples/simple/main.go
Normal file
@ -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)
|
||||
}
|
||||
}
|
16
examples/simple/main_test.go
Normal file
16
examples/simple/main_test.go
Normal file
@ -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()
|
||||
}
|
BIN
examples/simple/output.pdf
Normal file
BIN
examples/simple/output.pdf
Normal file
Binary file not shown.
Loading…
Reference in New Issue
Block a user