mim*_*ock 23 pdf pdf-generation go
如何从Google Go中的HTML输入创建PDF文件?如果还不可能,是否有任何旨在解决此问题的启动?
我正在寻找像PHP中的TCPDF这样的解决方案.
Jua*_*ras 18
怎么样gopdf(https://github.com/signintech/gopdf)或gofpdf(http://godoc.org/code.google.com/p/gofpdf).
好像你在寻找.
mut*_*ius 13
安装
go get -u github.com/SebastiaanKlippert/go-wkhtmltopdf
go version go1.9.2 linux/amd64
代码
import (
"fmt"
"strings"
wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
)
func main(){
pdfg, err := wkhtml.NewPDFGenerator()
if err != nil{
return
}
htmlStr := `<html><body><h1 style="color:red;">This is an html
from pdf to test color<h1><img src="http://api.qrserver.com/v1/create-qr-
code/?data=HelloWorld" alt="img" height="42" width="42"></img></body></html>`
pdfg.AddPage(wkhtml.NewPageReader(strings.NewReader(htmlStr)))
// Create PDF document in internal buffer
err = pdfg.Create()
if err != nil {
log.Fatal(err)
}
//Your Pdf Name
err = pdfg.WriteFile("./Your_pdfname.pdf")
if err != nil {
log.Fatal(err)
}
fmt.Println("Done")
}
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于在 golang 中使用适当的背景图像和嵌入式 CSS 样式标签将 html 转换为 pdf
该功能page.PrintToPDF()效果很好。
下面是一个将其与 chromedp ( ) 一起使用的示例go get -u github.com/chromedp/chromedp:
import (
"context"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
func main() {
taskCtx, cancel := chromedp.NewContext(
context.Background(),
chromedp.WithLogf(log.Printf),
)
defer cancel()
var pdfBuffer []byte
if err := chromedp.Run(taskCtx, pdfGrabber("https://www.wikipedia.org", "body", &pdfBuffer)); err != nil {
log.Fatal(err)
}
if err := ioutil.WriteFile("coolsite.pdf", pdfBuffer, 0644); err != nil {
log.Fatal(err)
}
}
func pdfGrabber(url string, sel string, res *[]byte) chromedp.Tasks {
start := time.Now()
return chromedp.Tasks{
emulation.SetUserAgentOverride("WebScraper 1.0"),
chromedp.Navigate(url),
// wait for footer element is visible (ie, page is loaded)
// chromedp.ScrollIntoView(`footer`),
chromedp.WaitVisible(`body`, chromedp.ByQuery),
// chromedp.Text(`h1`, &res, chromedp.NodeVisible, chromedp.ByQuery),
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().WithPrintBackground(true).Do(ctx)
if err != nil {
return err
}
*res = buf
//fmt.Printf("h1 contains: '%s'\n", res)
fmt.Printf("\nTook: %f secs\n", time.Since(start).Seconds())
return nil
}),
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将在 chrome headless 中加载 wikipedia.org 并等待正文显示,然后将其另存为 pdf。
终端结果:
$ go run main.go
https://www.wikipedia.org
Scraping url now...
Took: 2.772797 secs
Run Code Online (Sandbox Code Playgroud)