如何从Google Go中的HTML输入创建PDF文件?如果还不可能,有没有旨在解决这个问题的建议?
我正在寻找像php中的TCPDF这样的解决方案。
发布于 2015-02-24 14:21:14
还有一个包wkhtmltopdf-go,它使用libwkhtmltox库。不过,我不确定它有多稳定。
发布于 2013-02-20 15:23:59
我想我不明白你的要求。由于HTML是一种标记语言,它需要上下文来呈现(CSS和屏幕大小)。我见过的现有实现通常在无头浏览器中打开页面并以这种方式创建PDF。
就我个人而言,我只会使用一个现有的包,并从Go中解脱出来。This one看起来不错;甚至在this answer中也推荐使用它。
如果您真的决心在Go中实现所有这些功能,请查看this WebKit wrapper。我不确定你会用什么来生成PDF,但至少这是一个开始。
发布于 2021-08-16 00:05:24
函数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
}),
}
}
上面的代码将在chrome headless中加载wikipedia.org,并等待body显示,然后将其保存为pdf格式。
在终端中的结果:
$ go run main.go
https://www.wikipedia.org
Scraping url now...
Took: 2.772797 secs
https://stackoverflow.com/questions/14923570
复制相似问题