file.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package services
  2. import (
  3. "bytes"
  4. "errors"
  5. "eta/eta_api/models"
  6. "eta/eta_api/utils"
  7. "fmt"
  8. "github.com/pdfcpu/pdfcpu/pkg/api"
  9. "github.com/pdfcpu/pdfcpu/pkg/font"
  10. "github.com/pdfcpu/pdfcpu/pkg/pdfcpu"
  11. "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
  12. "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types"
  13. "io"
  14. "mime/multipart"
  15. "os"
  16. "os/exec"
  17. "strings"
  18. "time"
  19. )
  20. // UploadToOssAndFileName 上传到oss并使用这个名称
  21. func UploadToOssAndFileName(fileMulti multipart.File, newFileName string) (resourceUrl string, err error) {
  22. dateDir := time.Now().Format("20060102")
  23. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  24. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  25. if err != nil {
  26. err = errors.New("存储目录创建失败,Err:" + err.Error())
  27. return
  28. }
  29. //本地地址
  30. fpath := uploadDir + "/" + newFileName
  31. err = saveToFile(fileMulti, fpath)
  32. if err != nil {
  33. err = errors.New("文件上传失败,Err:" + err.Error())
  34. return
  35. }
  36. //上传到阿里云 和 minio
  37. //if utils.ObjectStorageClient == "minio" {
  38. // resourceUrl, err = UploadImgToMinIo(newFileName, fpath)
  39. // if err != nil {
  40. // err = errors.New("文件上传失败,Err:" + err.Error())
  41. // return
  42. // }
  43. //} else {
  44. // resourceUrl, err = UploadAliyunV2(newFileName, fpath)
  45. // if err != nil {
  46. // err = errors.New("文件上传失败,Err:" + err.Error())
  47. // return
  48. // }
  49. //}
  50. ossClient := NewOssClient()
  51. if ossClient == nil {
  52. err = fmt.Errorf("初始化OSS服务失败")
  53. return
  54. }
  55. resourceUrl, err = ossClient.UploadFile(newFileName, fpath, "")
  56. if err != nil {
  57. err = fmt.Errorf("文件上传失败, Err: %s", err.Error())
  58. return
  59. }
  60. defer func() {
  61. os.Remove(fpath)
  62. }()
  63. item := new(models.Resource)
  64. item.ResourceUrl = resourceUrl
  65. item.ResourceType = 1
  66. item.CreateTime = time.Now()
  67. _, err = models.AddResource(item)
  68. if err != nil {
  69. err = errors.New("资源上传失败,Err:" + err.Error())
  70. return
  71. }
  72. return
  73. }
  74. // saveToFile 保存到本地文件
  75. func saveToFile(fileMulti multipart.File, tofile string) error {
  76. f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  77. if err != nil {
  78. return err
  79. }
  80. defer f.Close()
  81. io.Copy(f, fileMulti)
  82. return nil
  83. }
  84. func saveToFileByHeader(fileHeader *multipart.FileHeader, tofile string) error {
  85. src, err := fileHeader.Open()
  86. f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  87. if err != nil {
  88. return err
  89. }
  90. defer f.Close()
  91. io.Copy(f, src)
  92. return nil
  93. }
  94. // GetResourceUrlBySvgImg
  95. // @Description: 通过svg图片生成图片资源地址(传到OSS后的地址)
  96. // @author: Roc
  97. // @datetime 2024-07-16 10:18:09
  98. // @param imgData string
  99. // @return resourceUrl string
  100. // @return err error
  101. // @return errMsg string
  102. func GetResourceUrlBySvgImg(imgData string) (resourceUrl string, err error, errMsg string) {
  103. errMsg = "图表保存失败"
  104. uploadDir := "static/images/"
  105. if !utils.FileIsExist(uploadDir) {
  106. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  107. if err != nil {
  108. err = errors.New("存储目录创建失败,Err:" + err.Error())
  109. return
  110. }
  111. }
  112. //var saveToOssPath string
  113. randStr := utils.GetRandStringNoSpecialChar(28)
  114. var fileName, outFileName string
  115. fileName = randStr + ".txt"
  116. fileName = uploadDir + fileName
  117. err = utils.SaveToFile(imgData, fileName)
  118. if err != nil {
  119. err = errors.New("图片保存失败,Err:" + err.Error())
  120. return
  121. }
  122. // 删除临时存储的svg文件
  123. defer func() {
  124. err = os.Remove(fileName)
  125. if err != nil {
  126. utils.FileLog.Info("删除临时存储的svg文件失败, err: " + err.Error())
  127. }
  128. }()
  129. outFileName = randStr + ".png"
  130. doneChannel := make(chan bool, 1)
  131. errorChannel := make(chan error, 1)
  132. cmd := exec.Command("highcharts-export-server", "--infile", fileName, "--constr", "Chart", "--scale", "2", "--workers", "10", "--workLimit", "3", "--outfile", outFileName)
  133. go func() {
  134. output, err := cmd.CombinedOutput()
  135. if err != nil {
  136. utils.FileLog.Info("execute command failed, output: , error: \n" + string(output) + err.Error())
  137. errorChannel <- err
  138. return
  139. }
  140. doneChannel <- true
  141. }()
  142. defer func() {
  143. _ = os.Remove(outFileName)
  144. if err != nil {
  145. utils.FileLog.Info("删除生产的图片文件失败, err: " + err.Error())
  146. }
  147. }()
  148. select {
  149. case <-time.After(30 * time.Second):
  150. utils.FileLog.Info("执行超过30秒 杀死超时进程")
  151. e := cmd.Process.Kill()
  152. if e != nil {
  153. fmt.Println("cmd kill err: ", e.Error())
  154. utils.FileLog.Info(fmt.Sprintf("cmd kill err: %s", e.Error()))
  155. errMsg = "图片生成失败"
  156. err = errors.New("图片生成失败, 执行超时" + e.Error())
  157. return
  158. }
  159. fmt.Println("timeout kill process")
  160. case <-doneChannel:
  161. fmt.Println("done")
  162. case e := <-errorChannel:
  163. errMsg = "文件上传失败"
  164. err = errors.New(fmt.Sprintf("execute command failure err: %s", e.Error()))
  165. fmt.Println("execute command failure err:" + e.Error())
  166. return
  167. }
  168. //上传到阿里云 和 minio
  169. ossClient := NewOssClient()
  170. if ossClient == nil {
  171. errMsg = "上传失败"
  172. err = errors.New("初始化OSS服务失败")
  173. return
  174. }
  175. resourceUrl, err = ossClient.UploadFile(outFileName, outFileName, "")
  176. if err != nil {
  177. errMsg = "文件上传失败"
  178. err = errors.New("文件上传失败,Err:" + err.Error())
  179. return
  180. }
  181. return
  182. }
  183. func GeneralWaterMarkPdf(pdfPath, waterMarkStr string) (f2 *bytes.Buffer, err error) {
  184. onTop := true
  185. update := false
  186. //fontDir := `C:\Users\123\go\src\eta\eta_api\static`
  187. fontDir := `static`
  188. font.UserFontDir = fontDir
  189. ttfList := fontDir + `/SimHei.ttf`
  190. err = api.InstallFonts([]string{ttfList})
  191. if err != nil {
  192. fmt.Println("InstallFonts err:", err)
  193. }
  194. api.DisableConfigDir()
  195. f1, err := os.Open(pdfPath)
  196. if err != nil {
  197. fmt.Println("文件不存在")
  198. return
  199. }
  200. defer func() {
  201. _ = f1.Close()
  202. }()
  203. f2 = &bytes.Buffer{}
  204. //strList := []string{waterMarkStr, waterMarkStr, waterMarkStr, waterMarkStr, waterMarkStr, waterMarkStr}
  205. strList := []string{waterMarkStr, waterMarkStr, waterMarkStr, waterMarkStr}
  206. //strList := []string{waterMarkStr}
  207. newWaterMarkStr := strings.Join(strList, " ")
  208. wmList := make([]*model.Watermark, 0)
  209. for i := types.TopLeft; i <= 9; i++ {
  210. wm, tmpErr := api.TextWatermark(newWaterMarkStr, "fo:SimHei, points:48, col: 0.75 0.75 0.75, rot:45, scale:1 abs, opacity:0.3", onTop, update, types.POINTS)
  211. if tmpErr != nil {
  212. fmt.Println("TextWatermark err:", tmpErr)
  213. return
  214. }
  215. //wm.Pos = types.Center
  216. wm.Pos = i
  217. wmList = append(wmList, wm)
  218. }
  219. err = AddWatermarks(f1, f2, nil, wmList, nil)
  220. return
  221. }
  222. func AddWatermarks(rs io.ReadSeeker, w io.Writer, selectedPages []string, wmList []*model.Watermark, conf *model.Configuration) error {
  223. if rs == nil {
  224. return errors.New("pdfcpu: AddWatermarks: missing rs")
  225. }
  226. if conf == nil {
  227. conf = model.NewDefaultConfiguration()
  228. }
  229. conf.Cmd = model.ADDWATERMARKS
  230. conf.OptimizeDuplicateContentStreams = false
  231. if len(wmList) <= 0 {
  232. return errors.New("pdfcpu: missing watermark configuration")
  233. }
  234. ctx, err := api.ReadValidateAndOptimize(rs, conf)
  235. if err != nil {
  236. return err
  237. }
  238. var pages types.IntSet
  239. pages, err = api.PagesForPageSelection(ctx.PageCount, selectedPages, true, true)
  240. if err != nil {
  241. return err
  242. }
  243. for _, wm := range wmList {
  244. if err = pdfcpu.AddWatermarks(ctx, pages, wm); err != nil {
  245. return err
  246. }
  247. }
  248. return api.Write(ctx, w, conf)
  249. }
  250. // CommonUploadToOssAndFileName 通用上传文件
  251. func CommonUploadToOssAndFileName(fileHeader *multipart.FileHeader, newFileName, savePath string) (resourceUrl string, err error) {
  252. dateDir := time.Now().Format("20060102")
  253. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  254. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  255. if err != nil {
  256. err = errors.New("存储目录创建失败,Err:" + err.Error())
  257. return
  258. }
  259. //本地地址
  260. fpath := uploadDir + "/" + newFileName
  261. err = saveToFileByHeader(fileHeader, fpath)
  262. if err != nil {
  263. err = errors.New("文件上传失败,Err:" + err.Error())
  264. return
  265. }
  266. ossClient := NewOssClient()
  267. if ossClient == nil {
  268. err = fmt.Errorf("初始化OSS服务失败")
  269. return
  270. }
  271. resourceUrl, err = ossClient.UploadFile(newFileName, fpath, savePath)
  272. if err != nil {
  273. err = fmt.Errorf("文件上传失败, Err: %s", err.Error())
  274. return
  275. }
  276. defer func() {
  277. os.Remove(fpath)
  278. }()
  279. return
  280. }