Explorar o código

Merge branch 'feature/eta_2.6.9' into debug

hsun hai 5 días
pai
achega
fe38930c6f
Modificáronse 1 ficheiros con 94 adicións e 47 borrados
  1. 94 47
      services/smart_report.go

+ 94 - 47
services/smart_report.go

@@ -8,10 +8,12 @@ import (
 	"eta/eta_mobile/utils"
 	"fmt"
 	"html"
+	"math"
 	"os"
 	"os/exec"
 	"path"
 	"strconv"
+	"strings"
 	"time"
 )
 
@@ -136,11 +138,12 @@ func SmartReportElasticUpsert(smartReportId int, state int) (err error) {
 	return
 }
 
-func ReportToPdf(width int, reportUrl, filePath string, top, bottom, left, right int) (err error) {
+func ReportToPdf(width, height int, reportUrl, filePath string, top, bottom, left, right int) (err error) {
 	pyCode := `
 import asyncio
 from pyppeteer import launch
 
+@asyncio.coroutine
 async def main():
     # 异步代码
     browser = await launch({
@@ -151,7 +154,7 @@ async def main():
     page = await browser.newPage()
     await page.setViewport({
         'width': %d,
-        'height': 1697
+        'height': %d
     })
     await page.goto('%s', {
         'waitUntil': 'networkidle0',
@@ -163,7 +166,7 @@ async def main():
 
     await page.pdf({
 		'width': %d,
-        'height': 1697,
+        'height': %d,
         'path': "%s",
         'printBackground': True,
         'margin': {
@@ -186,7 +189,7 @@ finally:
     loop.close()
 `
 
-	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width+left+right, reportUrl, width, filePath, top, bottom, left, right)
+	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, height, reportUrl, width+left+right, height+top+bottom, filePath, top, bottom, left, right)
 	utils.FileLog.Info("pdf pyCode: \n" + pyCode)
 	cmd := exec.Command("python3", "-c", pyCode)
 	output, e := cmd.CombinedOutput()
@@ -203,7 +206,7 @@ finally:
 	return
 }
 
-func ReportToJpeg(width int, reportUrl, filePath string) (err error) {
+func ReportToJpeg(width, height int, reportUrl, filePath string) (err error) {
 	pyCode := `
 import asyncio
 from pyppeteer import launch, errors
@@ -223,23 +226,23 @@ async def main():
         # 设置视口大小
         await page.setViewport({
             'width': %d,
-            'height': 1080
+            'height': %d
         })
         
         # 导航到页面
         await page.goto('%s', {
             'waitUntil': 'networkidle0',
-            'timeout': 1000000  # 设置超时时间为 100 秒
+            'timeout': 3000000  # 设置超时时间为 100 秒
         })
         # Customizing footer for page numbers starting from page 2
 
         # 在这里添加两秒的等待
-        await asyncio.sleep(2)
+        await asyncio.sleep(5)
 
         await page.screenshot({
             'path': "%s",
             'fullPage': True,
-			'quality':100
+			'quality':80
         })
         
     except errors.BrowserError as e:
@@ -264,10 +267,9 @@ finally:
     loop.close()
 `
 
-	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
+	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, height, reportUrl, filePath)
 	utils.FileLog.Info("jpeg pyCode: \n" + pyCode)
 	cmd := exec.Command("python3", "-c", pyCode)
-
 	output, e := cmd.CombinedOutput()
 	if e != nil {
 		err = e
@@ -304,6 +306,13 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 	}
 	var report *models.ReportDetail
 
+	// 默认宽高,自由布局需要根据比例重新计算
+	var freeRatio string
+	pcWidth := 1200
+	pcHeight := 1697
+	mobileWidth := 600
+	mobileHeight := 1697
+
 	// 先清空字段
 	if reportType == 1 {
 		report, err = models.GetReportById(reportId)
@@ -315,6 +324,9 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 			utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
 			return
 		}
+		if report.ReportLayout == 3 {
+			freeRatio = report.FreeReportRatio
+		}
 	} else if reportType == 2 {
 		err = models.UpdatePdfUrlEnglishReportById(reportId)
 		if err != nil {
@@ -329,21 +341,41 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 		}
 	}
 
+	// 7/10为A4的比例,不需要重新算
+	if freeRatio != "" && freeRatio != "7/10" {
+		h, e := calculateReportPdfHeight(pcWidth, freeRatio)
+		if e != nil {
+			err = fmt.Errorf("重新计算PDF生成高度失败, %v", e)
+			return
+		}
+		pcHeight = h
+
+		hm, e := calculateReportPdfHeight(mobileWidth, freeRatio)
+		if e != nil {
+			err = fmt.Errorf("重新计算移动端PDF生成高度失败, %v", e)
+			return
+		}
+		mobileHeight = hm
+	}
+
 	reportCode := utils.MD5(strconv.Itoa(reportId))
 
 	// pc端
-	pdfPath := `./static/` + reportCode + "_1200.pdf"
-	jpegPath := `./static/` + reportCode + "_1200.jpeg"
-
 	go func() {
-		width := 1200
+		pdfPath := `./static/` + reportCode + "_1200.pdf"
+		jpegPath := `./static/` + reportCode + "_1200.jpg"
+
+		//width := 1200
 		top, bottom, left, right := 20, 20, 20, 20
 		if reportType == 1 {
 			if report != nil && report.ReportLayout == 3 {
 				top, bottom, left, right = 0, 0, 0, 0
 			}
 		}
-		err := ReportToPdf(width, reportUrl, pdfPath, top, bottom, left, right)
+		//if reportType == 3 {
+		//	width = 800
+		//}
+		err = ReportToPdf(pcWidth, pcHeight, reportUrl, pdfPath, top, bottom, left, right)
 		if err != nil {
 			utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
 			go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
@@ -401,31 +433,26 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 			}
 		}
 
-	}()
+		time.Sleep(1 * time.Minute)
 
-	go func() {
-		width := 1200
-		/*if reportType == 3 {
-			width = 800
-		}*/
-		err := ReportToJpeg(width, reportUrl, jpegPath)
+		err = ReportToJpeg(pcWidth, pcHeight, reportUrl, jpegPath)
 		if err != nil {
 			utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
 		}
-		file, err := os.Open(jpegPath)
+		file, err = os.Open(jpegPath)
 		if err != nil {
 			utils.FileLog.Info("open file failed: , error: \n" + err.Error())
 			return
 		}
 
-		ext := path.Ext(file.Name())
+		ext = path.Ext(file.Name())
 
-		randStr := utils.GetRandStringNoSpecialChar(28)
-		fileName := randStr + ext
+		randStr = utils.GetRandStringNoSpecialChar(28)
+		fileName = randStr + ext
 		defer file.Close() //关闭上传文件
 
-		resourceUrl := ``
-		ossClient := NewOssClient()
+		resourceUrl = ``
+		ossClient = NewOssClient()
 		if ossClient == nil {
 			utils.FileLog.Info("初始化OSS服务失败")
 			return
@@ -461,12 +488,7 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 				return
 			}
 		}
-
 	}()
-
-	// 移动端
-	pdfPathMobile := `./static/` + reportCode + "_600.pdf"
-	jpegPathMobile := `./static/` + reportCode + "_600.jpeg"
 	var mobilePdf = true
 	if reportType == 1 && report != nil {
 		if report.ReportLayout == 3 {
@@ -474,10 +496,13 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 		}
 	}
 	if mobilePdf {
+		// 移动端
 		go func() {
-			width := 600
+			pdfPathMobile := `./static/` + reportCode + "_600.pdf"
+			jpegPathMobile := `./static/` + reportCode + "_600.jpg"
 			top, bottom, left, right := 20, 20, 20, 20
-			err := ReportToPdf(width, reportUrl, pdfPathMobile, top, bottom, left, right)
+			//width := 600
+			err = ReportToPdf(mobileWidth, mobileHeight, reportUrl, pdfPathMobile, top, bottom, left, right)
 			if err != nil {
 				utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
 				go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
@@ -535,28 +560,26 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 				}
 			}
 
-		}()
+			time.Sleep(1 * time.Minute)
 
-		go func() {
-			width := 600
-			err := ReportToJpeg(width, reportUrl, jpegPathMobile)
+			err = ReportToJpeg(mobileWidth, mobileHeight, reportUrl, jpegPathMobile)
 			if err != nil {
 				utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
 			}
-			file, err := os.Open(jpegPathMobile)
+			file, err = os.Open(jpegPathMobile)
 			if err != nil {
 				utils.FileLog.Info("open file failed: , error: \n" + err.Error())
 				return
 			}
 
-			ext := path.Ext(file.Name())
+			ext = path.Ext(file.Name())
 
-			randStr := utils.GetRandStringNoSpecialChar(28)
-			fileName := randStr + ext
+			randStr = utils.GetRandStringNoSpecialChar(28)
+			fileName = randStr + ext
 			defer file.Close() //关闭上传文件
 
-			resourceUrl := ``
-			ossClient := NewOssClient()
+			resourceUrl = ``
+			ossClient = NewOssClient()
 			if ossClient == nil {
 				utils.FileLog.Info("初始化OSS服务失败")
 				return
@@ -592,7 +615,31 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 					return
 				}
 			}
-
 		}()
 	}
 }
+
+// calculateReportPdfHeight 自由布局-根据宽度和布局比例计算高度
+func calculateReportPdfHeight(width int, freeRatio string) (height int, err error) {
+	ratioArr := strings.Split(freeRatio, "/")
+	if len(ratioArr) != 2 {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	m, e := strconv.ParseFloat(ratioArr[0], 64)
+	if e != nil {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	n, e := strconv.ParseFloat(ratioArr[1], 64)
+	if e != nil {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	if m <= 0 {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	height = int(math.Round(float64(width) * n / m))
+	return
+}