浏览代码

Merge branch 'ETA_1.8.1' into debug

zwxi 11 月之前
父节点
当前提交
cf16dd3457

+ 105 - 0
controllers/smart_report/smart_report.go

@@ -1506,3 +1506,108 @@ func (this *SmartReportController) CancelApprove() {
 	br.Success = true
 	br.Msg = "操作成功"
 }
+
+// GetReportPdfUrl
+// @Title 研报生成pdf和图片
+// @Description 研报生成pdf和图片接口
+// @Success 200 {object} smart_report.SmartReportListResp
+// @router /get_pdf_url [post]
+func (this *SmartReportController) GetReportPdfUrl() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		return
+	}
+
+	var req models.GetReportPdfUrlReq
+	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
+		br.Msg = "参数有误"
+		br.ErrMsg = "参数解析失败, Err: " + e.Error()
+		return
+	}
+	if req.ReportUrl == "" {
+		br.Msg = "参数有误"
+		br.ErrMsg = "报告链接有误"
+		return
+	}
+
+	if req.Type != 1 && req.Type != 2 {
+		br.Msg = "参数有误"
+		br.ErrMsg = "获取资源类型有误"
+		return
+	}
+
+	filePath := `./static/` + req.ReportCode
+	var err error
+	if req.Type == 1 {
+		filePath += ".pdf"
+		err = services.ReportToPdf(req.ReportUrl, filePath)
+		if err != nil {
+			br.Msg = "转换失败"
+			br.ErrMsg = "报告转PDF失败,Err:" + err.Error()
+			return
+		}
+	} else {
+		filePath += ".jpeg"
+		err = services.ReportToJpeg(req.ReportUrl, filePath+".jpeg")
+		if err != nil {
+			br.Msg = "转换失败"
+			br.ErrMsg = "报告转图片失败,Err:" + err.Error()
+			return
+		}
+	}
+
+	file, err := os.Open(filePath)
+	if err != nil {
+		fmt.Println("Error:", err)
+		return
+	}
+
+
+	ext := path.Ext(file.Name())
+	//dateDir := time.Now().Format("20060102")
+	//uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
+	//err = os.MkdirAll(uploadDir, utils.DIR_MOD)
+	//if err != nil {
+	//	br.Msg = "存储目录创建失败"
+	//	br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
+	//	return
+	//}
+	randStr := utils.GetRandStringNoSpecialChar(28)
+	fileName := randStr + ext
+	//fpath := utils.STATIC_DIR + "/" + fileName
+	defer file.Close() //关闭上传文件
+
+	resourceUrl := ``
+	ossClient := services.NewOssClient()
+	if ossClient == nil {
+		br.Msg = "上传失败"
+		br.ErrMsg = "初始化OSS服务失败"
+		return
+	}
+	resourceUrl, err = ossClient.UploadFile(fileName, filePath, "")
+	if err != nil {
+		br.Msg = "文件上传失败"
+		br.ErrMsg = "文件上传失败,Err:" + err.Error()
+		return
+	}
+	defer func() {
+		_ = os.Remove(filePath)
+	}()
+
+
+	br.Ret = 200
+	br.Success = true
+	br.Data = resourceUrl
+	br.Msg = "操作成功"
+}

+ 1 - 0
controllers/smart_report/smart_resource.go

@@ -294,6 +294,7 @@ func (this *SmartReportResourceController) Add() {
 	item.ImgName = req.ImgName
 	item.ImgUrl = req.ImgUrl
 	item.CreateTime = time.Now().Local()
+	item.Style = req.Style
 
 	if e := item.Create(); e != nil {
 		br.Msg = "操作失败"

+ 7 - 0
models/report.go

@@ -1142,3 +1142,10 @@ func UpdateReportsStateBySecondIds(oldState, newState int, secondIds []int) (err
 	_, err = o.Raw(sql, oldState, newState, secondIds).Exec()
 	return
 }
+
+// GetReportPdfUrlReq 获取报告pdf地址请求体
+type GetReportPdfUrlReq struct {
+	ReportUrl  string `description:"报告Url"`
+	ReportCode string `description:"报告Code"`
+	Type       int    `description:"类型 1-pdf 2-图片"`
+}

+ 2 - 0
models/smart_report/smart_resource.go

@@ -11,6 +11,7 @@ import (
 type SmartReportResource struct {
 	ResourceId int       `orm:"column(resource_id);pk" description:"智能研报资源ID"`
 	ImgUrl     string    // 图片链接
+	Style      string    // 版图样式
 	ImgName    string    // 图片名称
 	Type       int       // 类型 1-版头 2-版尾
 	CreateTime time.Time // 创建时间
@@ -104,4 +105,5 @@ type SmartReportResourceAddReq struct {
 	Type    int    `description:"类型 1-版头 2-版尾"`
 	ImgUrl  string `description:"图片链接"`
 	ImgName string `description:"图片名称"`
+	Style   string `description:"版图样式"`
 }

+ 9 - 0
routers/commentsRouter.go

@@ -6163,6 +6163,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "GetReportPdfUrl",
+            Router: `/get_pdf_url`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
         beego.ControllerComments{
             Method: "LastPublishedReport",

+ 100 - 0
services/smart_report.go

@@ -8,6 +8,7 @@ import (
 	"eta/eta_api/utils"
 	"fmt"
 	"html"
+	"os/exec"
 	"strconv"
 	"time"
 )
@@ -128,3 +129,102 @@ func SmartReportElasticUpsert(smartReportId int, state int) (err error) {
 	}
 	return
 }
+
+func ReportToPdf(reportUrl, filePath string) (err error) {
+	pyCode := `
+import asyncio
+from pyppeteer import launch
+
+async def main():
+    
+    browser = await launch({
+        'executablePath': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+        'headless': True
+    })
+    page = await browser.newPage()
+    await page.setViewport({
+        'width': 1920,
+        'height': 1080,
+    })
+	# 对于大的PDF生成,可能会时间很久,这里规定不会进行超时处理
+    # await page.setDefaultNavigationTimeout(0)
+	# 不再有网络连接时触发
+    await page.goto('%s',{
+        'waitUntil':'networkidle0'
+    })
+    
+
+    await page.pdf({
+        'path': "%s",
+        'printBackground': True,
+        'format': "A2",
+        'displayHeaderFooter':True,
+        # 'headerTemplate':'<div></div>',
+        # 'footerTemplate':"<div style='width:100%;text-align:center;font-size:16px'><span class='pageNumber''></span></div>",
+        'margin': {
+            'top': 100,
+            'bottom': 100,
+            'left':0,
+            'right':0
+        }
+    })
+    await browser.close()
+
+asyncio.run(main())
+`
+
+	pyCode = fmt.Sprintf(pyCode, reportUrl, filePath)
+
+	cmd := exec.Command("python3", "-c", pyCode)
+	_, err = cmd.CombinedOutput()
+	defer func() {
+		cmd.Process.Kill()
+	}()
+	return
+}
+
+func ReportToJpeg(reportUrl, filePath string) (err error) {
+	pyCode := `
+import asyncio
+from pyppeteer import launch
+
+async def main():
+    
+    browser = await launch({
+        'executablePath': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+        'headless': True
+    })
+    page = await browser.newPage()
+    await page.setViewport({
+        'width': 1920,
+        'height': 1080,
+    })
+	# 对于大的PDF生成,可能会时间很久,这里规定不会进行超时处理
+    # await page.setDefaultNavigationTimeout(0)
+	# 不再有网络连接时触发    
+	await page.goto('%s',{
+        'waitUntil':'networkidle0'
+    })
+    # Customizing footer for page numbers starting from page 2
+
+    await page.screenshot({
+        'path': "%s",
+        'type': "jpeg",
+        'fullPage': True,
+    })
+    await browser.close()
+
+asyncio.run(main())
+`
+
+	pyCode = fmt.Sprintf(pyCode, reportUrl, filePath)
+
+	cmd := exec.Command("python3", "-c", pyCode)
+
+	_, err = cmd.CombinedOutput()
+	defer func() {
+		cmd.Process.Kill()
+	}()
+	return
+}
+