html2image.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "git.aionnect.com/aionnect/go-common/utils"
  6. "github.com/cbroglie/mustache"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "strconv"
  11. )
  12. const tplStr = `<html>
  13. <body style="border: 0; padding: 0; margin: 0">
  14. <div style="width: 768px; height: 1024px; text-align: center; background-color: bisque">
  15. <h3 style="padding-top:20px">{{title}}</h3>
  16. <p>{{description}}</p>
  17. <img src="{{url}}" width="430" height="430" />
  18. </div>
  19. </body>
  20. </html>`
  21. const (
  22. W = 768
  23. H = 1024
  24. )
  25. func main() {
  26. var buf bytes.Buffer
  27. tpl, _ := mustache.ParseString(tplStr)
  28. _ = tpl.FRender(&buf, map[string]string{
  29. "title": "Hello world",
  30. "description": "A test for convert html to jpg",
  31. "url": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFe8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyUFlBM1FKcDlldWgxMDAwMDAwNzAAAgTryl1eAwQAAAAA",
  32. })
  33. tempId := utils.NextId()
  34. htmlFileName := fmt.Sprintf("temp_%d.html", tempId)
  35. imgFileName := fmt.Sprintf("temp_%d.jpg", tempId)
  36. _ = ioutil.WriteFile(htmlFileName, buf.Bytes(), os.ModeAppend)
  37. cmd := exec.Command(`wkhtmltoimage`, `--height`, strconv.Itoa(H), `--width`, strconv.Itoa(W), htmlFileName, imgFileName)
  38. _ = cmd.Run()
  39. // output, err := cmd.CombinedOutput()
  40. }