httpimg.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package httpimg
  2. import (
  3. "io"
  4. "net/http"
  5. "github.com/jung-kurt/gofpdf"
  6. )
  7. // httpimgPdf is a partial interface that only implements the functions we need
  8. // from the PDF generator to put the HTTP images on the PDF.
  9. type httpimgPdf interface {
  10. GetImageInfo(imageStr string) *gofpdf.ImageInfoType
  11. ImageTypeFromMime(mimeStr string) string
  12. RegisterImageReader(imgName, tp string, r io.Reader) *gofpdf.ImageInfoType
  13. SetError(err error)
  14. }
  15. // Register registers a HTTP image. Downloading the image from the provided URL
  16. // and adding it to the PDF but not adding it to the page. Use Image() with the
  17. // same URL to add the image to the page.
  18. func Register(f httpimgPdf, urlStr, tp string) (info *gofpdf.ImageInfoType) {
  19. info = f.GetImageInfo(urlStr)
  20. if info != nil {
  21. return
  22. }
  23. resp, err := http.Get(urlStr)
  24. if err != nil {
  25. f.SetError(err)
  26. return
  27. }
  28. defer resp.Body.Close()
  29. if tp == "" {
  30. tp = f.ImageTypeFromMime(resp.Header["Content-Type"][0])
  31. }
  32. return f.RegisterImageReader(urlStr, tp, resp.Body)
  33. }