go实现word,excel,pptx转pdf

因工作需要实现word转pdf

实现原理:利用go命令行调用libreffice命令实现文件转化

**使用 libreffice 文件转pdf 并发数不能超2,只能一个文件转化成功后,在进行下一个

注意事项使用前本机或者服务器先安装开源软件 libreffice !!!

注意事项使用前本机或者服务器先安装开源软件 libreffice !!!

传送门:libreoffice

代码如下(粘贴后直接运行):

package Test

import (
	"fmt"
	"os"
	"os/exec"
	"path"
	"runtime"
	"strings"
	"testing"
)

//TestToPdf golang+libreffice 实现word,excel,pptx转pdf,html
func TestToPdf(t *testing.T) {

	fileSrcPath := "/Users/xing/Desktop/123/test2.docx" //自己机器上的文件地址
	outPath := "/Users/xing/Desktop/123/pdf"            //转出文件的路径
	fileType := "pdf"

	osName := runtime.GOOS //获取系统类型
	switch osName {
	case "darwin": //mac系统
		command := "/Applications/LibreOffice.app/Contents/MacOS/soffice"
		pdfFile, err := FuncDocs2Pdf(command, fileSrcPath, outPath, fileType)
		if err != nil {
			println("转化异常:", err.Error())
		}
		fmt.Println("转化后的文件:", pdfFile)
	case "linux":
		command := "libreoffice7.3"
		pdfFile, err := FuncDocs2Pdf(command, fileSrcPath, outPath, fileType)
		if err != nil {
			println("转化异常:", err.Error())
		}
		fmt.Println("转化后的文件:", pdfFile)
	case "windows":
		command := "soffice libreoffice" // 因为没有windows机器需要自己测试下这个命令行
		pdfFile, err := FuncDocs2Pdf(command, fileSrcPath, outPath, fileType)
		if err != nil {
			println("转化异常:", err.Error())
		}
		fmt.Println("转化后的文件:", pdfFile)
	default:
		fmt.Println("暂时不支持的系统转化:" + runtime.GOOS)
	}
}

/**
*@tips libreoffice 转换指令:
* libreoffice6.2 invisible --convert-to pdf csDoc.doc --outdir /home/[转出目录]
*
* @function 实现文档类型转换为pdf或html
* @param command:libreofficed的命令(具体以版本为准);win:soffice; linux:libreoffice6.2
*     fileSrcPath:转换文件的路径
*     fileOutDir:转换后文件存储目录
*     converterType:转换的类型pdf/html
* @return fileOutPath 转换成功生成的文件的路径 error 转换错误
 */
func FuncDocs2Pdf(command string, fileSrcPath string, fileOutDir string, converterType string) (fileOutPath string, error error) {
	//校验fileSrcPath
	srcFile, erByOpenSrcFile := os.Open(fileSrcPath)
	if erByOpenSrcFile != nil && os.IsNotExist(erByOpenSrcFile) {
		return "", erByOpenSrcFile
	}
	//如文件输出目录fileOutDir不存在则自动创建
	outFileDir, erByOpenFileOutDir := os.Open(fileOutDir)
	if erByOpenFileOutDir != nil && os.IsNotExist(erByOpenFileOutDir) {
		erByCreateFileOutDir := os.MkdirAll(fileOutDir, os.ModePerm)
		if erByCreateFileOutDir != nil {
			fmt.Println("File ouput dir create error.....", erByCreateFileOutDir.Error())
			return "", erByCreateFileOutDir
		}
	}
	//关闭流
	defer func() {
		_ = srcFile.Close()
		_ = outFileDir.Close()
	}()
	//convert
	cmd := exec.Command(command, "--invisible", "--language=zh-CN", "--convert-to", converterType,
		fileSrcPath, "--outdir", fileOutDir)
	byteByStat, errByCmdStart := cmd.Output()
	//命令调用转换失败
	if errByCmdStart != nil {
		return "", errByCmdStart
	}
	//success
	fileOutPath = fileOutDir + "/" + strings.Split(path.Base(fileSrcPath), ".")[0]
	if converterType == "html" {
		fileOutPath += ".html"
	} else {
		fileOutPath += ".pdf"
	}
	fmt.Println("文件转换成功...", string(byteByStat))
	return fileOutPath, nil
}

参考文章:

golang+libreffice6.2实现word,excel,pptx转pdf,html - 简书

Go语言本身并不直接支持将Word文档换成PDF,因为这涉及到复杂的文件格式处理和换功能,而Go的标准库并没有提供这样的工具。不过,你可以通过引入第三方库来实现这个需求,比如`gopdf`(一个用于生成PDF的库),配合其他专门用于读取Word文档的库,如`github.com/360EntSecGroup-Skylar/excelize/v2` 或 `github.com/OfficeDev/PnP-PowerShell/Commands/Documents`(PowerShell模块)。 以下是一个基本步骤: 1. 安装必要的库: - `gopdf`: 使用`go get github.com/gopdf/gopdf` - Word到XML换(例如excelize): 如果需要,可以安装`github.com/360EntSecGroup-Skylar/excelize/v2` 2. 使用Excelize或其他库读取Word内容并将其存储为中间格式(如XML)。 3. 使用gopdf创建一个新的PDF文件,并将读取的内容添加到PDF中。 4. 导出PDF文件。 示例代码可能会有所不同,具体取决于你选择的具体库,但是大体上会涉及以下部分: ```go package main import ( "github.com/360EntSecGroup-Skylar/excelize/v2" "github.com/gopdf/gopdf" ) func main() { ex := excelize.NewFile() if err := ex.Read("input.docx"); err != nil { // 替换为实际Word文件路径 // 处理错误... } // 获取Word内容并换为适合PDF的形式 content := convertToPDFFormat(ex) // 自定义函数 // 创建PDF pdf := gopdf.New() pdf.AddPage() pdf.SetFont("Arial", "B", 16) pdf.Cell(0, 10, "Content from Word") // 将内容添加到PDF for _, line := range content { pdf.Cell(0, 10, line) } // 输出PDF err = pdf.OutputFileAndClose("output.pdf") // 替换为输出文件路径 // 处理错误... } // convertToPDFFormat 为实际内容换函数 func convertToPDFFormat(ex *excelize.File) []string { // ... 实现Excelize结构化为PDF格式的代码 ... return lines // 返回一个字符串切片,每个元素表示PDF中的行 }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值