fusenapi/utils/pdf/html_to_pdf.go

44 lines
1.0 KiB
Go
Raw Normal View History

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