fusenapi/utils/pdf/html_to_pdf.go
2023-10-24 15:22:39 +08:00

44 lines
1.0 KiB
Go

package pdf
import (
"encoding/base64"
"errors"
"strings"
"github.com/SebastiaanKlippert/go-wkhtmltopdf"
)
/*
html转 Pdf
outFile为空则不保存(使用该方法需要安装工具 sudo apt-get install wkhtmltopdf)
*/
func HtmlToPdfBase64(content string, dataType string, pageSize string, outFile ...string) (string, error) {
pdfg, err := wkhtmltopdf.NewPDFGenerator()
if err != nil {
return "", err
}
switch dataType {
case "url": //网页地址
pdfg.AddPage(wkhtmltopdf.NewPage(content))
case "html": //网页内容
pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(content)))
default:
return "", errors.New("invalid type")
}
//模式
pdfg.Orientation.Set(wkhtmltopdf.OrientationPortrait)
//pdf尺寸默认A4纸
pdfg.PageSize.Set(pageSize)
// Create PDF document in memory
if err = pdfg.Create(); err != nil {
return "", err
}
// Write PDF to file
if len(outFile) != 0 {
if err = pdfg.WriteFile(outFile[0]); err != nil {
return "", err
}
}
return base64.StdEncoding.EncodeToString(pdfg.Bytes()), nil
}