smart_report.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package services
  2. import (
  3. "eta_gn/eta_api/models"
  4. "eta_gn/eta_api/services/alarm_msg"
  5. "eta_gn/eta_api/utils"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "strconv"
  11. "time"
  12. )
  13. func ReportToPdf(width int, reportUrl, filePath string) (err error) {
  14. pyCode := `
  15. import asyncio
  16. from pyppeteer import launch
  17. @asyncio.coroutine
  18. async def main():
  19. # 异步代码
  20. browser = await launch({
  21. 'executablePath': '%s',
  22. 'headless': True,
  23. 'args': ['--disable-infobars', '--no-sandbox']
  24. })
  25. page = await browser.newPage()
  26. await page.setViewport({
  27. 'width': %d,
  28. 'height': 1080,
  29. })
  30. await page.goto('%s', {
  31. 'waitUntil': 'networkidle0',
  32. 'timeout': 3000000 # 设置超时时间为 100 秒
  33. })
  34. # 在生成PDF之前等待2秒
  35. await asyncio.sleep(10)
  36. await page.pdf({
  37. 'path': "%s",
  38. 'printBackground': True,
  39. 'format': "A2",
  40. 'margin': {
  41. 'top': '10mm',
  42. 'bottom': '10mm',
  43. 'left': '10mm',
  44. 'right': '10mm'
  45. }
  46. })
  47. await browser.close()
  48. # 创建事件循环
  49. loop = asyncio.get_event_loop()
  50. # 使用事件循环运行main函数
  51. try:
  52. loop.run_until_complete(main())
  53. finally:
  54. # 关闭事件循环
  55. loop.close()
  56. `
  57. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
  58. utils.FileLog.Info("pdf pyCode: \n" + pyCode)
  59. cmd := exec.Command("python3", "-c", pyCode)
  60. output, e := cmd.CombinedOutput()
  61. if e != nil {
  62. err = e
  63. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  64. utils.FileLog.Info("Output: %s\n", string(output))
  65. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  66. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  67. }
  68. defer func() {
  69. cmd.Process.Kill()
  70. }()
  71. return
  72. }
  73. func ReportToJpeg(width int, reportUrl, filePath string) (err error) {
  74. pyCode := `
  75. import asyncio
  76. from pyppeteer import launch, errors
  77. async def main():
  78. try:
  79. # 启动浏览器
  80. browser = await launch({
  81. 'executablePath': '%s',
  82. 'headless': True,
  83. 'args': ['--disable-infobars', '--no-sandbox']
  84. })
  85. # 新建页面
  86. page = await browser.newPage()
  87. # 设置视口大小
  88. await page.setViewport({
  89. 'width': %d,
  90. 'height': 1080
  91. })
  92. # 导航到页面
  93. await page.goto('%s', {
  94. 'waitUntil': 'networkidle0',
  95. 'timeout': 3000000 # 设置超时时间为 100 秒
  96. })
  97. # Customizing footer for page numbers starting from page 2
  98. # 在这里添加两秒的等待
  99. await asyncio.sleep(5)
  100. await page.screenshot({
  101. 'path': "%s",
  102. 'fullPage': True,
  103. 'quality':80
  104. })
  105. except errors.BrowserError as e:
  106. print('Browser closed unexpectedly:', e)
  107. except Exception as e:
  108. print('An error occurred:', e)
  109. finally:
  110. # 确保浏览器关闭
  111. if browser is not None:
  112. await browser.close()
  113. # 获取当前事件循环
  114. loop = asyncio.get_event_loop()
  115. # 运行事件循环直到main协程完成
  116. try:
  117. loop.run_until_complete(main())
  118. except Exception as e:
  119. print('Error during event loop execution:', e)
  120. finally:
  121. # 关闭事件循环
  122. loop.close()
  123. `
  124. pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
  125. utils.FileLog.Info("jpeg pyCode: \n" + pyCode)
  126. cmd := exec.Command("python3", "-c", pyCode)
  127. output, e := cmd.CombinedOutput()
  128. if e != nil {
  129. err = e
  130. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  131. utils.FileLog.Info("Output: %s\n", string(output))
  132. go alarm_msg.SendAlarmMsg("ReportToJpeg failed:"+err.Error(), 3)
  133. go alarm_msg.SendAlarmMsg("Output :"+string(output), 3)
  134. }
  135. defer func() {
  136. cmd.Process.Kill()
  137. }()
  138. return
  139. }
  140. // Report2pdfAndJpeg
  141. // @Description: 报告转pdf和图片
  142. // @author: Roc
  143. // @datetime 2024-07-19 14:11:38
  144. // @param reportUrl string
  145. // @param reportId int
  146. // @param reportType int
  147. func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
  148. var err error
  149. defer func() {
  150. if err != nil {
  151. go alarm_msg.SendAlarmMsg("Report2pdfAndJpeg failed:"+err.Error(), 3)
  152. utils.FileLog.Info("Report2pdfAndJpeg failed: , error: \n" + err.Error())
  153. }
  154. }()
  155. if reportUrl == `` {
  156. return
  157. }
  158. // 先清空报告字段
  159. err = models.UpdatePdfUrlReportById(reportId)
  160. if err != nil {
  161. utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
  162. return
  163. }
  164. reportCode := utils.MD5(strconv.Itoa(reportId))
  165. pdfPath := `./static/` + reportCode + ".pdf"
  166. jpegPath := `./static/` + reportCode + ".jpg"
  167. // 生成pdf
  168. width := 1560
  169. if reportType == 3 {
  170. width = 800
  171. }
  172. err = ReportToPdf(width, reportUrl, pdfPath)
  173. if err != nil {
  174. utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
  175. go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
  176. }
  177. file, err := os.Open(pdfPath)
  178. if err != nil {
  179. utils.FileLog.Info("Open failed: , error: \n" + err.Error())
  180. go alarm_msg.SendAlarmMsg("Open failed:"+err.Error(), 3)
  181. return
  182. }
  183. ext := path.Ext(file.Name())
  184. randStr := utils.GetRandStringNoSpecialChar(28)
  185. fileName := randStr + ext
  186. defer file.Close() //关闭上传文件
  187. resourceUrl := ``
  188. ossClient := NewOssClient()
  189. if ossClient == nil {
  190. utils.FileLog.Info("初始化OSS服务失败")
  191. return
  192. }
  193. resourceUrl, err = ossClient.UploadFile(fileName, pdfPath, "")
  194. if err != nil {
  195. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  196. go alarm_msg.SendAlarmMsg("文件上传失败:"+err.Error(), 3)
  197. return
  198. }
  199. defer func() {
  200. _ = os.Remove(pdfPath)
  201. }()
  202. // 更新pdf url
  203. err = models.ModifyReportPdfUrl(reportId, resourceUrl)
  204. if err != nil {
  205. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  206. return
  207. }
  208. time.Sleep(1 * time.Minute)
  209. // 生成图片
  210. err = ReportToJpeg(width, reportUrl, jpegPath)
  211. if err != nil {
  212. utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
  213. }
  214. file, err = os.Open(jpegPath)
  215. if err != nil {
  216. utils.FileLog.Info("open file failed: , error: \n" + err.Error())
  217. return
  218. }
  219. ext = path.Ext(file.Name())
  220. randStr = utils.GetRandStringNoSpecialChar(28)
  221. fileName = randStr + ext
  222. defer file.Close() //关闭上传文件
  223. resourceUrl = ``
  224. ossClient = NewOssClient()
  225. if ossClient == nil {
  226. utils.FileLog.Info("初始化OSS服务失败")
  227. return
  228. }
  229. resourceUrl, err = ossClient.UploadFile(fileName, jpegPath, "")
  230. if err != nil {
  231. utils.FileLog.Info("文件上传失败, Err: \n" + err.Error())
  232. return
  233. }
  234. defer func() {
  235. _ = os.Remove(jpegPath)
  236. }()
  237. err = models.ModifyReportImgUrl(reportId, resourceUrl)
  238. if err != nil {
  239. utils.FileLog.Info("更新研报失败, Err: \n" + err.Error())
  240. return
  241. }
  242. return
  243. }