Last active
March 31, 2022 08:04
-
-
Save dvas0004/41c33a4213c821b97f964099065cbc6b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"log" | |
"math/rand" | |
"os" | |
"strings" | |
"time" | |
"github.com/SebastiaanKlippert/go-wkhtmltopdf" | |
"github.com/go-echarts/go-echarts/v2/charts" | |
"github.com/go-echarts/go-echarts/v2/opts" | |
) | |
// generate random data for bar chart | |
func generateBarItems() []opts.BarData { | |
items := make([]opts.BarData, 0) | |
for i := 0; i < 7; i++ { | |
items = append(items, opts.BarData{Value: rand.Intn(300)}) | |
} | |
return items | |
} | |
func exampleBarChart() bytes.Buffer { | |
// create a new bar instance | |
bar := charts.NewBar() | |
// set some global options like Title/Legend/ToolTip or anything else | |
bar.SetGlobalOptions(charts.WithTitleOpts(opts.Title{ | |
Title: "My first bar chart generated by go-echarts", | |
Subtitle: "It's extremely easy to use, right?", | |
})) | |
// Put data into instance | |
bar.SetXAxis([]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}). | |
AddSeries("Category A", generateBarItems()). | |
AddSeries("Category B", generateBarItems()) | |
// Where the magic happens | |
var result bytes.Buffer | |
bar.Render(&result) | |
return result | |
} | |
func ExampleNewPDFGenerator() { | |
// Create new PDF generator | |
pdfg, err := wkhtmltopdf.NewPDFGenerator() | |
if err != nil { | |
log.Fatal(err) | |
} | |
html := "<html>Hi</html>" | |
pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(html))) | |
chart := exampleBarChart() | |
chartString := strings.ReplaceAll(chart.String(), "let ", "var ") | |
f, _ := os.Create(fmt.Sprintf("bar-%d.html", time.Now().UnixMicro())) | |
f.WriteString(chartString) | |
f.Close() | |
defer os.Remove(f.Name()) | |
pdfg.AddPage(wkhtmltopdf.NewPage(f.Name())) | |
// Create PDF document in internal buffer | |
err = pdfg.Create() | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Write buffer contents to file on disk | |
err = pdfg.WriteFile("./simplesample.pdf") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("Done") | |
// Output: Done | |
} | |
func main() { | |
ExampleNewPDFGenerator() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment