78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
|
|
package qyglreport
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"encoding/base64"
|
|||
|
|
"html/template"
|
|||
|
|
"mime"
|
|||
|
|
"os"
|
|||
|
|
"path/filepath"
|
|||
|
|
"sync"
|
|||
|
|
|
|||
|
|
"github.com/gin-gonic/gin"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
const (
|
|||
|
|
defaultBannerRel = "resources/qygl-media/banner.jpg"
|
|||
|
|
defaultFooterRel = "resources/qygl-media/footer.png"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
var (
|
|||
|
|
loadOnce sync.Once
|
|||
|
|
bannerURL template.URL
|
|||
|
|
footerURL template.URL
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
func loadPosterAssets() {
|
|||
|
|
bannerURL = dataURLFromFile(resolveMediaFile([]string{
|
|||
|
|
defaultBannerRel,
|
|||
|
|
"resources/qygl-media/banner.png",
|
|||
|
|
}), "/reports/qygl/media/banner.jpg")
|
|||
|
|
footerURL = dataURLFromFile(defaultFooterRel, "/reports/qygl/media/footer.png")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func resolveMediaFile(candidates []string) string {
|
|||
|
|
for _, p := range candidates {
|
|||
|
|
if _, err := os.Stat(p); err == nil {
|
|||
|
|
return p
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
if len(candidates) > 0 {
|
|||
|
|
return candidates[0]
|
|||
|
|
}
|
|||
|
|
return ""
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func dataURLFromFile(path string, httpFallback string) template.URL {
|
|||
|
|
if path == "" {
|
|||
|
|
return template.URL(httpFallback)
|
|||
|
|
}
|
|||
|
|
data, err := os.ReadFile(path)
|
|||
|
|
if err != nil {
|
|||
|
|
return template.URL(httpFallback)
|
|||
|
|
}
|
|||
|
|
ext := filepath.Ext(path)
|
|||
|
|
mimeType := mime.TypeByExtension(ext)
|
|||
|
|
if mimeType == "" {
|
|||
|
|
switch ext {
|
|||
|
|
case ".jpg", ".jpeg":
|
|||
|
|
mimeType = "image/jpeg"
|
|||
|
|
case ".png":
|
|||
|
|
mimeType = "image/png"
|
|||
|
|
default:
|
|||
|
|
mimeType = "application/octet-stream"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
encoded := base64.StdEncoding.EncodeToString(data)
|
|||
|
|
return template.URL("data:" + mimeType + ";base64," + encoded)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// PageTemplateData 企业报告 HTML 模板数据(海报内嵌 data URL,PDF 生成不依赖外链)
|
|||
|
|
func PageTemplateData(reportJSON template.JS) gin.H {
|
|||
|
|
loadOnce.Do(loadPosterAssets)
|
|||
|
|
return gin.H{
|
|||
|
|
"ReportJSON": reportJSON,
|
|||
|
|
"BannerPosterURL": bannerURL,
|
|||
|
|
"FooterPosterURL": footerURL,
|
|||
|
|
}
|
|||
|
|
}
|