f
This commit is contained in:
@@ -2,8 +2,10 @@ package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
@@ -14,6 +16,7 @@ import (
|
||||
api_services "tyapi-server/internal/domains/api/services"
|
||||
"tyapi-server/internal/domains/api/services/processors"
|
||||
"tyapi-server/internal/domains/api/services/processors/qygl"
|
||||
"tyapi-server/internal/shared/pdf"
|
||||
)
|
||||
|
||||
// QYGLReportHandler 企业全景报告页面渲染处理器
|
||||
@@ -135,3 +138,59 @@ func (h *QYGLReportHandler) GetQYGLReportPageByID(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// GetQYGLReportPDFByID 通过编号导出企业全景报告 PDF(基于 headless Chrome 渲染 HTML)
|
||||
// GET /reports/qygl/:id/pdf
|
||||
func (h *QYGLReportHandler) GetQYGLReportPDFByID(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.String(http.StatusBadRequest, "报告编号不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
// 可选:从数据库查一次,用于生成更友好的文件名
|
||||
var fileName = "企业全景报告.pdf"
|
||||
if h.reportRepo != nil {
|
||||
if entity, err := h.reportRepo.FindByReportID(c.Request.Context(), id); err == nil && entity != nil {
|
||||
if entity.EntName != "" {
|
||||
fileName = fmt.Sprintf("%s_企业全景报告.pdf", entity.EntName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 根据当前请求推断访问协议(支持通过反向代理的 X-Forwarded-Proto)
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
} else if forwardedProto := c.Request.Header.Get("X-Forwarded-Proto"); forwardedProto != "" {
|
||||
scheme = forwardedProto
|
||||
}
|
||||
|
||||
// 构建用于 headless 浏览器访问的完整报告页面 URL
|
||||
reportURL := fmt.Sprintf("%s://%s/reports/qygl/%s", scheme, c.Request.Host, id)
|
||||
|
||||
h.logger.Info("开始生成企业全景报告 PDF(headless Chrome)",
|
||||
zap.String("report_id", id),
|
||||
zap.String("url", reportURL),
|
||||
)
|
||||
|
||||
pdfGen := pdf.NewHTMLPDFGenerator(h.logger)
|
||||
pdfBytes, err := pdfGen.GenerateFromURL(c.Request.Context(), reportURL)
|
||||
if err != nil {
|
||||
h.logger.Error("生成企业全景报告 PDF 失败", zap.String("report_id", id), zap.Error(err))
|
||||
c.String(http.StatusInternalServerError, "生成企业报告 PDF 失败,请稍后重试")
|
||||
return
|
||||
}
|
||||
|
||||
if len(pdfBytes) == 0 {
|
||||
h.logger.Error("生成的企业全景报告 PDF 为空", zap.String("report_id", id))
|
||||
c.String(http.StatusInternalServerError, "生成的企业报告 PDF 为空,请稍后重试")
|
||||
return
|
||||
}
|
||||
|
||||
encodedFileName := url.QueryEscape(fileName)
|
||||
c.Header("Content-Type", "application/pdf")
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", encodedFileName))
|
||||
c.Data(http.StatusOK, "application/pdf", pdfBytes)
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user