最近收到網友的提問后端怎么把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