export.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package lorca
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. )
  7. const (
  8. // PageA4Width is a width of an A4 page in pixels at 96dpi
  9. PageA4Width = 816
  10. // PageA4Height is a height of an A4 page in pixels at 96dpi
  11. PageA4Height = 1056
  12. )
  13. // PDF converts a given URL (may be a local file) to a PDF file. Script is
  14. // evaluated before the page is printed to PDF, you may modify the contents of
  15. // the page there of wait until the page is fully rendered. Width and height
  16. // are page bounds in pixels. PDF by default uses 96dpi density. For A4 page
  17. // you may use PageA4Width and PageA4Height constants.
  18. func PDF(url, script string, width, height int) ([]byte, error) {
  19. return doHeadless(url, func(c *chrome) ([]byte, error) {
  20. if _, err := c.eval(script); err != nil {
  21. return nil, err
  22. }
  23. return c.pdf(width, height)
  24. })
  25. }
  26. // PNG converts a given URL (may be a local file) to a PNG image. Script is
  27. // evaluated before the "screenshot" is taken, so you can modify the contents
  28. // of a URL there. Image bounds are provides in pixels. Background is in ARGB
  29. // format, the default value of zero keeps the background transparent. Scale
  30. // allows zooming the page in and out.
  31. //
  32. // This function is most convenient to convert SVG to PNG of different sizes,
  33. // for example when preparing Lorca app icons.
  34. func PNG(url, script string, x, y, width, height int, bg uint32, scale float32) ([]byte, error) {
  35. return doHeadless(url, func(c *chrome) ([]byte, error) {
  36. if _, err := c.eval(script); err != nil {
  37. return nil, err
  38. }
  39. return c.png(x, y, width, height, bg, scale)
  40. })
  41. }
  42. func doHeadless(url string, f func(c *chrome) ([]byte, error)) ([]byte, error) {
  43. dir, err := ioutil.TempDir("", "lorca")
  44. if err != nil {
  45. return nil, err
  46. }
  47. defer os.RemoveAll(dir)
  48. args := append(defaultChromeArgs, fmt.Sprintf("--user-data-dir=%s", dir), "--remote-debugging-port=0", "--headless", url)
  49. chrome, err := newChromeWithArgs(ChromeExecutable(), args...)
  50. if err != nil {
  51. return nil, err
  52. }
  53. defer chrome.kill()
  54. return f(chrome)
  55. }