卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35223本站已运行394

Go ChromeDP 在打印到 pdf 期间忽略任何外部或内部 CSS,仅使用 html 文件中的 CSS

go chromedp 在打印到 pdf 期间忽略任何外部或内部 css,仅使用 html 文件中的 css

php小编柚子将为大家介绍一种名为Go ChromeDP的工具,它在将网页打印为PDF的过程中,可以忽略所有外部和内部CSS样式,只使用HTML文件中的CSS样式。这个工具可以帮助开发人员更好地控制PDF输出的样式,并且提供了更灵活的定制选项。通过Go ChromeDP,我们可以轻松地生成符合我们需求的高质量PDF文档,为我们的项目提供更好的用户体验和功能。接下来,让我们一起来了解一下Go ChromeDP的使用方法和特点吧!

问题内容

go chromedp 不使用任何 css,无论是内部样式还是外部样式(仅使用 html 编写的样式,而不是其他文件)。我使用的方法

page.setdocumentcontent(frametree.frame.id, string(buf.bytes())).do(ctx)

将 html 文件添加到 chromedp,并且

buf, _, err: = page.printtopdf().do(ctx)
if err != nil {
    return err
}
_, err = outputbuf.write(buf)
if err != nil {
    return err
}

打印到pdf,但结果中的pdf没有样式(即使使用外部css文件服务器)。我尝试使用 page.getresourcetree().do(ctx) + css.createstylesheet(resourcetree.frame.id).do(ctx) + 添加它

css.SetStyleSheetText(stylesheet, `.c {
     color: red;
     font-size: 30px;
     background-color: aqua;
}
`).Do(ctx)

它确实有效,但每次我想生成pdf时都使用它,特别是在我的情况下,因为我使用的是html/template中的html,所以很难过。也许有简单的方法将外部 css 添加到单个 html 文件中?你觉得怎么样?

感谢您的回答

博赫丹

我想使用 chromedp 将带有外部 css、图像和字体的 go 模板转换为 pdf,但它忽略了主 html 文件之外的任何内容。

解决方法

请注意,加载外部资源需要一些时间。您应该等待它们加载。当页面准备好时,将引发 page.loadeventfired 事件。所以我们可以等待这个事件并随后打印页面。请参阅下面的演示:

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "net/http/httptest"
    "os"
    "sync"
    "time"

    "github.com/chromedp/cdproto/page"
    "github.com/chromedp/chromedp"
)

func main() {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Simulate a network latency.
        time.Sleep(2 * time.Second)
        w.Header().Set("Content-Type", "text/css")
        fmt.Fprint(w, `h1 {font-size: 100pt; color: red;}`)
    }))
    defer ts.Close()

    ctx, cancel := chromedp.NewContext(context.Background())
    defer cancel()

    // construct your html
    html := `<html>
    <head>
        <link rel="stylesheet" href="%s/style.css">
    </head>
    <body>
        <h1> Hello World! </h1>
    </body>
</html>
`

    var wg sync.WaitGroup
    wg.Add(1)
    if err := chromedp.Run(ctx,
        chromedp.Navigate("about:blank"),
        // setup the listener to listen for the page.EventLoadEventFired
        chromedp.ActionFunc(func(ctx context.Context) error {
            lctx, cancel := context.WithCancel(ctx)
            chromedp.ListenTarget(lctx, func(ev interface{}) {
                if _, ok := ev.(*page.EventLoadEventFired); ok {
                    wg.Done()
                    // remove the event listener
                    cancel()
                }
            })
            return nil
        }),
        chromedp.ActionFunc(func(ctx context.Context) error {
            frameTree, err := page.GetFrameTree().Do(ctx)
            if err != nil {
                return err
            }
            return page.SetDocumentContent(frameTree.Frame.ID, fmt.Sprintf(html, ts.URL)).Do(ctx)
        }),
        // wait for page.EventLoadEventFired
        chromedp.ActionFunc(func(ctx context.Context) error {
            wg.Wait()
            return nil
        }),
        chromedp.ActionFunc(func(ctx context.Context) error {
            buf, _, err := page.PrintToPDF().Do(ctx)
            if err != nil {
                return err
            }
            return os.WriteFile("sample.pdf", buf, 0644)
        }),
    ); err != nil {
        log.Fatal(err)
    }

    log.Println("done!")
}

参考:https://www.php.cn/link/13c86fac19a52dbc843105b709dc71fc一个>.

卓越飞翔博客
上一篇: 有没有办法在Golang中处理nil指针而不使用if/else?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏