2023-06-15 06:34:03 +00:00
|
|
|
package pdf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/SebastiaanKlippert/go-wkhtmltopdf"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// html转 Pdf dataType = 1 为网页url dataType = 2为网页内容 outFile为空则不保存
|
2023-06-15 06:34:40 +00:00
|
|
|
func HtmlToPdf(content string, dataType int, outFile ...string) ([]byte, error) {
|
2023-06-15 06:34:03 +00:00
|
|
|
pdfg, err := wkhtmltopdf.NewPDFGenerator()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
switch dataType {
|
|
|
|
case 1: //网页地址
|
|
|
|
pdfg.AddPage(wkhtmltopdf.NewPage(content))
|
|
|
|
case 2: //网页内容
|
|
|
|
pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(content)))
|
|
|
|
}
|
|
|
|
//模式
|
|
|
|
pdfg.Orientation.Set(wkhtmltopdf.OrientationPortrait)
|
|
|
|
//pdf尺寸默认A4纸
|
|
|
|
pdfg.PageSize.Set(wkhtmltopdf.PageSizeA4)
|
|
|
|
// Create PDF document in memory
|
|
|
|
if err = pdfg.Create(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// 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 06:34:03 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return pdfg.Bytes(), nil
|
|
|
|
}
|