github.com/phpdave11/gofpdf@v1.4.2/contrib/httpimg/httpimg.go (about)

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