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 id="Hello-World"> 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中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

WebStorm Mac版
好用的JavaScript开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能