最近收到网友的提问后端怎么把html转成pdf文件,于是我就把我以前做的例子发出来给大家参考一下,如果对你有帮助的话请点个赞
1.首先选择适合自己的系统下载wkhtmltopdf工具
mac下载后安装成功会自动添加到环境变量 直接执行 wkhtmltopdf -V 测试是否安装成功
hfy@566-Mac-mini ~ % wkhtmltopdf -V
wkhtmltopdf 0.12.5 (with patched qt)
linux环境安装需要下载好,添加执行权限并手动加到环境变量下面,如果不想加入到环境变量在代码里写死路径也行
2.直接使用下面demo修改下就可以使用了
package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os/exec"
"path/filepath"
)
var (
argsError = errors.New("no input file or out path")
fileTypeError = errors.New("the file must be in pdf format")
)
type HtmlToPdf struct {
Commond string
in string
out string
argsMap map[string]string
prams []string
}
func NewPdf() *HtmlToPdf {
args := map[string]string{
"--load-error-handling": "ignore",
"--footer-center": "第[page]页/共[topage]页",
"--footer-font-size": "8",
"-B": "31",
"-T": "32",
}
return &HtmlToPdf{
Commond: "wkhtmltopdf",
argsMap: args,
}
}
func (this *HtmlToPdf) OutFile(input string, outPath string) (string, error) {
var pdfPath string
// 输入 输出 参数不能为空
if input == "" || outPath == "" {
return pdfPath, argsError
}
//判断是否是生成pdf 文件
ext := filepath.Ext(outPath)
if ext != ".pdf" {
return pdfPath, fileTypeError
}
this.in = input
this.out = outPath
//构建参数
this.buildPrams()
//执行命令
if _, err := this.doExce();err != nil {
return pdfPath, err
}
return pdfPath, nil
}
func (this *HtmlToPdf) doExce() ([]byte, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cmd := exec.CommandContext(ctx, this.Commond, this.prams...)
stdout, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
defer stdout.Close()
//运行命令
err = cmd.Start()
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(stdout)
if err != nil {
return nil, err
}
cmd.Wait()
return bytes, err
}
func (this *HtmlToPdf) buildPrams() {
for key, val := range this.argsMap {
this.prams = append(this.prams, key, val)
}
//添加 输入 输出 参数
this.prams = append(this.prams, this.in, this.out)
}
func main() {
pdfOpt:= NewPdf()
htmlDemoPath := "xxxxx/src/demo/test.html"
PdfDemoPath := "xxxxx/src/demo/test.pdf"
str,err := pdfOpt.OutFile(htmlDemoPath,PdfDemoPath)
if err != nil {
fmt.Println("Error ",err)
return
}
fmt.Println(str)
}
效果:
image.png