首頁  >  文章  >  後端開發  >  Go ChromeDP 在列印到 pdf 期間忽略任何外部或內部 CSS,僅使用 html 檔案中的 CSS

Go ChromeDP 在列印到 pdf 期間忽略任何外部或內部 CSS,僅使用 html 檔案中的 CSS

PHPz
PHPz轉載
2024-02-10 14:42:09623瀏覽

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一个>.

以上是Go ChromeDP 在列印到 pdf 期間忽略任何外部或內部 CSS,僅使用 html 檔案中的 CSS的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除