pdf.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package resource
  2. import (
  3. "hongze/fms_api/global"
  4. "os"
  5. "os/exec"
  6. "path"
  7. "strings"
  8. )
  9. //FuncDocs2Pdf
  10. /**
  11. *@tips libreoffice 转换指令:
  12. * libreoffice6.2 invisible --convert-to pdf csDoc.doc --outdir /home/[转出目录]
  13. *
  14. * @function 实现文档类型转换为pdf或html
  15. * @param command:libreofficed的命令(具体以版本为准);win:soffice; linux:libreoffice6.2
  16. * fileSrcPath:转换文件的路径
  17. * fileOutDir:转换后文件存储目录
  18. * converterType:转换的类型pdf/html
  19. * @return fileOutPath 转换成功生成的文件的路径 error 转换错误
  20. */
  21. func FuncDocs2Pdf(command string, fileSrcPath string, fileOutDir string, converterType string) (fileOutPath string, error error) {
  22. //校验fileSrcPath
  23. srcFile, erByOpenSrcFile := os.Open(fileSrcPath)
  24. if erByOpenSrcFile != nil && os.IsNotExist(erByOpenSrcFile) {
  25. return "", erByOpenSrcFile
  26. }
  27. //如文件输出目录fileOutDir不存在则自动创建
  28. outFileDir, erByOpenFileOutDir := os.Open(fileOutDir)
  29. if erByOpenFileOutDir != nil && os.IsNotExist(erByOpenFileOutDir) {
  30. erByCreateFileOutDir := os.MkdirAll(fileOutDir, os.ModePerm)
  31. if erByCreateFileOutDir != nil {
  32. global.LOG.Info("File ouput dir create error.....", erByCreateFileOutDir.Error())
  33. return "", erByCreateFileOutDir
  34. }
  35. }
  36. //关闭流
  37. defer func() {
  38. _ = srcFile.Close()
  39. _ = outFileDir.Close()
  40. }()
  41. //convert
  42. cmd := exec.Command(command, "--invisible", "--convert-to", converterType,
  43. fileSrcPath, "--outdir", fileOutDir)
  44. _, errByCmdStart := cmd.Output()
  45. //命令调用转换失败
  46. if errByCmdStart != nil {
  47. return "", errByCmdStart
  48. }
  49. //success
  50. fileOutPath = fileOutDir + "/" + strings.Split(path.Base(fileSrcPath), ".")[0]
  51. if converterType == "html" {
  52. fileOutPath += ".html"
  53. } else {
  54. fileOutPath += ".pdf"
  55. }
  56. //校验fileSrcPath
  57. outFile, erByOpenOutFile := os.Open(fileOutPath)
  58. if erByOpenOutFile != nil {
  59. return "", erByOpenOutFile
  60. }
  61. defer func() {
  62. _ = outFile.Close()
  63. }()
  64. //fmt.Println("文件转换成功...", string(byteByStat))
  65. return fileOutPath, nil
  66. }