go语言实现word模版填充,并转换成pdf

使用 Go 语言实现 Word 模板填充并转换为 PDF

在现代应用程序开发中,自动生成文档是一个常见需求。本文将展示如何使用 Go 语言实现 Word 模板填充,并将填充后的文档转换为 PDF 文件。我们将使用 unioffice 库来处理 Word 文档和 pdfcpu 库来转换 PDF。

1. 准备工作

在开始之前,确保你已经安装了 Go 语言环境,并且你可以使用 go get 命令安装必要的库。

安装必要的库

首先,你需要安装 docx 库:

go get github.com/nguyenthenguyen/docx

2. 创建 Word 模板

为了演示填充 Word 模板的过程,我们首先需要一个 Word 模板文件。假设我们有一个名为 template.docx 的 Word 文件,其内容如下:

Hello {Name},

Your appointment is scheduled for {Date}.

Best regards,
Your Company

在模板中,我们使用 {Name}{Date} 作为占位符,这些占位符将在填充过程中被实际数据替换。

3. 实现 Word 模板填充,并转化pdf

接下来,我们编写 Go 代码来填充 Word 模板。创建一个名为 main.go 的文件,并添加以下代码:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/unidoc/unioffice/document"
)
type Contract struct {
	Name          string `json:"Name" comment:"甲方名称"`
	Date     	  string `json:"Date" comment:"当前日期"`
}
//FillTemplate 填充模版 
func (c *Contract)FillTemplate(templatePath string) error {
    // 打开模板
    r, err := docx.ReadDocxFile(templatePath)
    if err != nil {
        return fmt.Errorf("failed to open template: %v", err)
    }
	defer r.Close()
	doc := r.Editable()
	// 通过反射遍历 Contract 结构体字段
	val := reflect.ValueOf(c).Elem()
	typ := val.Type()
   
   	for i := 0; i < val.NumField(); i++ {
		field := val.Field(i)
		fieldName := typ.Field(i).Tag.Get("json")
		if fieldName == "" {
			continue
		}
		// 将字段值替换到 Word 模板中
		placeholder := "{" + fieldName + "}"
		if err := doc.Replace(placeholder, field.String(), -1); err != nil {
			return  err
		}
	}
    // 生成新的文件路径
	newFileName := id + "合同_签署.docx"
	newFilePath := filepath.Join(newFileName)
	// 保存修改后的文档
	err = doc.WriteToFile(newFilePath)
	if err != nil {
		return err
	}
	outFileName :=  "合同_签署.pdf"
	outFilePath := filepath.Join(outFileName)
	if err := c.ConvertDocxToPDF(newFilePath, outFilePath); err != nil {
		return  err
	}
    return nil
}
//ConvertDocxToPDF 转换成pdf
func (c *Contract) ConvertDocxToPDF(inputFile string, outputFile string) error {
	defer func() {
		os.Remove(inputFile)
	}()
	//判断当前运行环境,
	if runtime.GOOS == "windows" {
		cmd := exec.Command(
			"C:\\Program Files\\LibreOffice\\program\\soffice.exe",
			"--headless",
			"--convert-to", "pdf",
			"--outdir", filepath.Dir(outputFile), // Directory where the output file will be saved
			inputFile,
		)
		return cmd.Run()
	} else {
		cmd := exec.Command("unoconv", "-f", "pdf", "-o", outputFile, inputFile)
		return cmd.Run()
	}
}
func main() {
	templatePath := "template.docx"
    contact := &Contract{
		Name: "user",
		Date: "2024-09-19"
	}
    if err := contract.FillTemplate(templatePath); err != nil {
        log.Fatalf("Error filling template: %v", err)
    }
    fmt.Println("successfully!")
}

linux上需安装

你可以在你的操作系统上安装 unoconv。例如,在 Ubuntu 上,你可以使用以下命令:

sudo apt-get install libreoffice
sudo apt-get install unoconv

windows上需安装

安装 LibreOffice
LibreOffice 是一个强大的办公套件,支持从 Word 转换为 PDF。可以从 LibreOffice 官方网站下载并安装:
访问 LibreOffice 下载页面
选择适合你系统的版本(例如 Windows 64-bit),然后下载并安装。

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yijiacode

互联网+乞讨

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值