pdf.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package utils
  2. import (
  3. "bytes"
  4. "mtp20_assisted/global"
  5. "os/exec"
  6. "runtime"
  7. "go.uber.org/zap"
  8. )
  9. // 说明:使用本功能需要下载libreoffice SDK
  10. // https://zh-cn.libreoffice.org/download/libreoffice/
  11. //
  12. // ConvertToPDF
  13. // @Description: 转换文件为pdf
  14. // @param filePath 需要转换的文件
  15. // @param outPath 转换后的PDF文件存放目录
  16. // @return string
  17. //
  18. func ConvertToPDF(filePath string, outPath string) bool {
  19. // 1、拼接执行转换的命令
  20. commandName := ""
  21. var params []string
  22. if runtime.GOOS == "windows" {
  23. commandName = "cmd"
  24. params = []string{"/c", "soffice", "--headless", "--invisible", "--convert-to", "pdf", filePath, "--outdir", outPath}
  25. } else if runtime.GOOS == "linux" {
  26. commandName = "libreoffice"
  27. params = []string{"--invisible", "--headless", "--convert-to", "pdf", filePath, "--outdir", outPath}
  28. }
  29. // 开始执行转换
  30. if _, ok := interactiveToexec(commandName, params); ok {
  31. return true
  32. } else {
  33. return false
  34. }
  35. }
  36. //
  37. // interactiveToexec
  38. // @Description: 执行指定命令
  39. // @param commandName 命令名称
  40. // @param params 命令参数
  41. // @return string 执行结果返回信息
  42. // @return bool 是否执行成功
  43. //
  44. func interactiveToexec(commandName string, params []string) (string, bool) {
  45. cmd := exec.Command(commandName, params...)
  46. buf, err := cmd.Output()
  47. w := bytes.NewBuffer(nil)
  48. cmd.Stderr = w
  49. if err != nil {
  50. global.M2A_LOG.Error("执行命令错误", zap.Any("err", err))
  51. return "", false
  52. } else {
  53. return string(buf), true
  54. }
  55. }