Golang 上传Office文档并转化为PDF

hulu · · 2564 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

之前介绍了利用libreoffice 将office文件转化pdf并处理中文乱码的问题 不清楚的同学点击这里 [使用LibreOffice将word转化为pdf -解决中文乱码](https://studygolang.com/articles/35059#reply0) 现在结合Golang 实现文件上传和并生成PDF链接地址 upload.html 上传页面 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Upload</title> </head> <body> <h1>Office Transport to pdf</h1> <form action="/upload" method="post" enctype="multipart/form-data"> <p><input type="file" name="file"></p> <p><input type="submit" value="submit"></p> </form> </body> </html> ``` upload处理 ```golang func Upload(w http.ResponseWriter, req *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE") w.Header().Add("Access-Control-Allow-Headers", "Content-Type;x-requested-with") // header的类型 w.Header().Set("Content-Type", "application/json") file, header, err := req.FormFile("file") if err != nil { data := map[string]interface{}{ "code": -1, "message": "upload file error", } response(w, data) return } year := time.Now().Year() month := int(time.Now().Month()) day := time.Now().Day() tempPath := fmt.Sprintf("./static/tmp/") outPutPath := fmt.Sprintf("./static/pdf/%d/%d/%d", year, month, day) checkPath(tempPath) rand.Seed(time.Now().UnixNano()) randNum := rand.Intn(100) fileName := fmt.Sprintf("%s-%d", time.Now().Format("20060102-15_04_05"), randNum) suffix := []string{".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".pdf"} fileType := "" for _, v := range suffix { if strings.HasSuffix(header.Filename, v) { fileType = v break } } needExport := true exportName := fileName if fileType == "" { data := map[string]interface{}{ "code": -1, "message": "upload file type error", } response(w, data) return } else if fileType == ".pdf" { fileName = outPutPath + "/" + fileName + fileType needExport = false } else { fileName = tempPath + fileName + fileType } dst, err := os.Create(fileName) defer dst.Close() if err != nil { log.Errorf("upload file error") data := map[string]interface{}{ "code": -1, "message": "upload file error", } response(w, data) return } _, err = io.Copy(dst, file) if err != nil { log.Errorf("copy file error") data := map[string]interface{}{ "code": -1, "message": "copy file error", } response(w, data) return } if needExport { err := exportToPdf(fileName, outPutPath) if err != nil { log.Errorf("output file error") data := map[string]interface{}{ "code": -1, "message": "output file error", } response(w, data) return } os.Remove(fileName) //删除上传文件 } exportName = strings.TrimPrefix(outPutPath+"/"+exportName+".pdf", "./") data := map[string]interface{}{ "code": 0, "url": WebAgent.Host + "/" + exportName, } response(w, data) return } ``` checkPath 检查目录是否存在 ```golang //checkPath 检查目录是否存在并创建 func checkPath(path string) error { _, err := os.Stat(path) if err != nil && os.IsNotExist(err) { err := os.MkdirAll(path, os.ModePerm) if err != nil { return err } } return nil } ``` golang 调用系统命令导出为pdf ```golang func exportToPdf(filename string, outPath string) error { checkPath(outPath) lock.Lock() defer lock.Unlock() cmd := exec.Command("libreoffice7.0", "--invisible", "--language=zh-CN", "--convert-to", "pdf", filename, "--outdir", outPath) cmd.Stdout = os.Stdout err := cmd.Run() if err != nil { log.Errorf("transport pdf err:%v", err) return err } return nil } ```

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2564 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传