Golang 上传Office文档并转化为PDF

之前介绍了利用libreoffice 将office文件转化pdf并处理中文乱码的问题 不清楚的同学点击这里 使用LibreOffice将word转化为pdf -解决中文乱码 现在结合Golang 实现文件上传和并生成PDF链接地址
upload.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处理

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 检查目录是否存在

//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

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
}

上一篇:编辑表格用什么软件比较好?最好用的都在这了!


下一篇:office-excel