admin管理员组文章数量:1130349
使用 Go 语言实现 Word 模板填充并转换为 PDF
在现代应用程序开发中,自动生成文档是一个常见需求。本文将展示如何使用 Go 语言实现 Word 模板填充,并将填充后的文档转换为 PDF 文件。我们将使用 unioffice 库来处理 Word 文档和 pdfcpu 库来转换 PDF。
1. 准备工作
在开始之前,确保你已经安装了 Go 语言环境,并且你可以使用 go get 命令安装必要的库。
安装必要的库
首先,你需要安装 docx 库:
go get github/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/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),然后下载并安装。
使用 Go 语言实现 Word 模板填充并转换为 PDF
在现代应用程序开发中,自动生成文档是一个常见需求。本文将展示如何使用 Go 语言实现 Word 模板填充,并将填充后的文档转换为 PDF 文件。我们将使用 unioffice 库来处理 Word 文档和 pdfcpu 库来转换 PDF。
1. 准备工作
在开始之前,确保你已经安装了 Go 语言环境,并且你可以使用 go get 命令安装必要的库。
安装必要的库
首先,你需要安装 docx 库:
go get github/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/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),然后下载并安装。
版权声明:本文标题:go语言实现word模版填充,并转换成pdf 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://it.en369.cn/jiaocheng/1763671410a2953160.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论