golang 对 word docx 文档中的占位符进行替换

更新日期: 2024-09-28 阅读次数: 130 字数: 378 分类: golang

选型问题

go 似乎还是少,python 的比较多。那我不如去看看 c# 和 python 的实现。我看最完善的是 java 的, 连模板编辑都有

golang docx 选型

https://github.com/nguyenthenguyen/docx

这个库只能对 docx 进行占位符替换。但是足够了。

来自这个项目的总结:https://github.com/fumiama/go-docx

golang pdf 选型

https://github.com/signintech/pdft

但是这个库,是在指定坐标插入文本,并不能替换。

//insert text to pdf
err = pt.Insert("Hi", 1, 10, 10, 100, 100, gopdf.Center|gopdf.Bottom, nil)

其他选型

  • c# pdf https://github.com/itext/itext-dotnet
  • python pdf https://github.com/hoehermann/pypdf_strreplace 这里面也说明了 pdf 做文本替换相对复杂。从其他示例看,替换的文本长度跟原文本长度不一致,会出现覆盖后续文本的情况。

go 的收费版本

https://github.com/unidoc/unioffice

  • Filling out Form Fields Opening a document with embedded form fields, filling out the fields and saving the result as a new filled form.
  • Editing an existing document Open an existing document and replace/remove text without modifying formatting.

看起来这两个功能比较符合需求,但是可惜是收费的。

模板存储在服务器本地

不需要感觉,还是存到七牛吧。

安裝依賴

> go get github.com/nguyenthenguyen/docx
go: downloading github.com/nguyenthenguyen/docx v0.0.0-20230621112118-9c8e795a11db
go: added github.com/nguyenthenguyen/docx v0.0.0-20230621112118-9c8e795a11db

zip: not a valid zip file

报错:

doc 格式的有这个问题,docx 的正常。 所以,我干脆把 doc 都换成了 docx 的格式。

文件异常,直接退出问题

error 需要处理一下。

微信关注我哦 👍

大象工具微信公众号

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式