Best Rod code snippet using rod.PDF
examples_test.go
Source:examples_test.go
...184}185func Example_page_pdf() {186 page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()187 // simple version188 page.MustPDF("my.pdf")189 // customized version190 pdf, _ := page.PDF(&proto.PagePrintToPDF{191 PaperWidth: gson.Num(8.5),192 PaperHeight: gson.Num(11),193 PageRanges: "1-3",194 })195 _ = utils.OutputFile("my.pdf", pdf)196}197// Show how to handle multiple results of an action.198// Such as when you login a page, the result can be success or wrong password.199func Example_race_selectors() {200 const username = ""201 const password = ""202 browser := rod.New().MustConnect()203 page := browser.MustPage("https://leetcode.com/accounts/login/")204 page.MustElement("#id_login").MustInput(username)205 page.MustElement("#id_password").MustInput(password).MustType(input.Enter)206 // It will keep retrying until one selector has found a match207 elm := page.Race().Element(".nav-user-icon-base").MustHandle(func(e *rod.Element) {208 // print the username after successful login209 fmt.Println(*e.MustAttribute("title"))210 }).Element("[data-cy=sign-in-error]").MustDo()211 if elm.MustMatches("[data-cy=sign-in-error]") {212 // when wrong username or password213 panic(elm.MustText())214 }215}216// Rod uses mouse cursor to simulate clicks, so if a button is moving because of animation, the click may not work as expected.217// We usually use WaitStable to make sure the target isn't changing anymore.218func Example_wait_for_animation() {219 browser := rod.New().MustConnect()220 defer browser.MustClose()221 page := browser.MustPage("https://getbootstrap.com/docs/4.0/components/modal/")222 page.MustWaitLoad().MustElement("[data-target='#exampleModalLive']").MustClick()223 saveBtn := page.MustElementR("#exampleModalLive button", "Close")224 // Here, WaitStable will wait until the button's position and size become stable.225 saveBtn.MustWaitStable().MustClick().MustWaitInvisible()226 fmt.Println("done")227 // Output: done228}229// When you want to wait for an ajax request to complete, this example will be useful.230func Example_wait_for_request() {231 browser := rod.New().MustConnect()232 defer browser.MustClose()233 page := browser.MustPage("https://www.wikipedia.org/").MustWaitLoad()234 // Start to analyze request events235 wait := page.MustWaitRequestIdle()236 // This will trigger the search ajax request237 page.MustElement("#searchInput").MustClick().MustInput("lisp")238 // Wait until there's no active requests239 wait()240 // We want to make sure that after waiting, there are some autocomplete241 // suggestions available.242 fmt.Println(len(page.MustElements(".suggestion-link")) > 0)243 // Output: true244}245// Shows how to change the retry/polling options that is used to query elements.246// This is useful when you want to customize the element query retry logic.247func Example_customize_retry_strategy() {248 browser := rod.New().MustConnect()249 defer browser.MustClose()250 page := browser.MustPage("https://github.com")251 // sleep for 0.5 seconds before every retry252 sleeper := func() utils.Sleeper {253 return func(context.Context) error {254 time.Sleep(time.Second / 2)255 return nil256 }257 }258 el, _ := page.Sleeper(sleeper).Element("input")259 fmt.Println(el.MustProperty("name"))260 // If sleeper is nil page.ElementE will query without retrying.261 // If nothing found it will return an error.262 el, err := page.Sleeper(rod.NotFoundSleeper).Element("input")263 if errors.Is(err, &rod.ErrElementNotFound{}) {264 fmt.Println("element not found")265 } else if err != nil {266 panic(err)267 }268 fmt.Println(el.MustProperty("name"))269 // Output:270 // q271 // q272}273// Shows how we can further customize the browser with the launcher library.274// Usually you use launcher lib to set the browser's command line flags (switches).275// Doc for flags: https://peter.sh/experiments/chromium-command-line-switches276func Example_customize_browser_launch() {277 url := launcher.New().278 Proxy("127.0.0.1:8080"). // set flag "--proxy-server=127.0.0.1:8080"279 Delete("use-mock-keychain"). // delete flag "--use-mock-keychain"280 MustLaunch()281 browser := rod.New().ControlURL(url).MustConnect()282 defer browser.MustClose()283 // So that we don't have to self issue certs for MITM284 browser.MustIgnoreCertErrors(true)285 // Adding authentication to the proxy, for the next auth request.286 // We use CLI tool "mitmproxy --proxyauth user:pass" as an example.287 go browser.MustHandleAuth("user", "pass")()288 // mitmproxy needs a cert config to support https. We use http here instead,289 // for example290 fmt.Println(browser.MustPage("https://mdn.dev/").MustElement("title").MustText())291}292// When rod doesn't have a feature that you need. You can easily call the cdp to achieve it.293// List of cdp API: https://github.com/moredure/xrod/tree/master/lib/proto294func Example_direct_cdp() {295 page := rod.New().MustConnect().MustPage()296 // Rod doesn't have a method to enable AD blocking,297 // but you can call cdp interface directly to achieve it.298 // The two code blocks below are equal to enable AD blocking299 {300 _ = proto.PageSetAdBlockingEnabled{301 Enabled: true,302 }.Call(page)303 }304 {305 // Interact with the cdp JSON API directly306 _, _ = page.Call(context.TODO(), "", "Page.setAdBlockingEnabled", map[string]bool{307 "enabled": true,308 })309 }310}311// Shows how to listen for events.312func Example_handle_events() {313 browser := rod.New().MustConnect()314 defer browser.MustClose()315 page := browser.MustPage()316 done := make(chan struct{})317 // Listen for all events of console output.318 go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {319 fmt.Println(page.MustObjectsToJSON(e.Args))320 close(done)321 })()322 wait := page.WaitEvent(&proto.PageLoadEventFired{})323 page.MustNavigate("https://mdn.dev")324 wait()325 // EachEvent allows us to achieve the same functionality as above.326 if false {327 // Subscribe events before they happen, run the "wait()" to start consuming328 // the events. We can return an optional stop signal to unsubscribe events.329 wait := page.EachEvent(func(e *proto.PageLoadEventFired) (stop bool) {330 return true331 })332 page.MustNavigate("https://mdn.dev")333 wait()334 }335 // Or the for-loop style to handle events to do the same thing above.336 if false {337 page.MustNavigate("https://mdn.dev")338 for msg := range page.Event() {339 e := proto.PageLoadEventFired{}340 if msg.Load(&e) {341 break342 }343 }344 }345 page.MustEval(`() => console.log("hello", "world")`)346 <-done347 // Output:348 // [hello world]349}350func Example_download_file() {351 browser := rod.New().MustConnect()352 page := browser.MustPage("https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/")353 wait := browser.MustWaitDownload()354 page.MustElementR("a", "DOWNLOAD SAMPLE PDF FILE").MustClick()355 _ = utils.OutputFile("t.pdf", wait())356}357// Shows how to intercept requests and modify358// both the request and the response.359// The entire process of hijacking one request:360//361// browser --req-> rod ---> server ---> rod --res-> browser362//363// The --req-> and --res-> are the parts that can be modified.364func Example_hijack_requests() {365 browser := rod.New().MustConnect()366 defer browser.MustClose()367 router := browser.HijackRequests()368 defer router.MustStop()...
main.go
Source:main.go
...24 // You may want to start a server to watch the screenshots of the remote browser.25 // launcher.Open(browser.ServeMonitor(""))26 page := browser.MustPage("https://github.com").MustWaitLoad()27 // simple version28 page.MustPDF("my.pdf")29 // customized version30 pdf, _ := page.PDF(&proto.PagePrintToPDF{31 PaperWidth: gson.Num(8.5),32 PaperHeight: gson.Num(11),33 PageRanges: "1-3",34 })35 _ = utils.OutputFile("my.pdf", pdf)36}...
browserAutomationController.go
Source:browserAutomationController.go
...4 "github.com/senthilsweb/notifier/pkg/utils"5 "github.com/tidwall/gjson"6 "github.com/go-rod/rod"7)8func Export2PDF(c *gin.Context) {9 request_body := utils.GetStringFromGinRequestBody(c)10 webpage := gjson.Get(request_body, "message.webpage")11 filename := gjson.Get(request_body, "message.filename")12 page := rod.New().MustConnect().MustPage(webpage.String())13 response := page.MustWaitLoad().MustPDF()14 c.Writer.Header().Add("Content-type", "application/octet-stream")15 c.Header("Content-Disposition", "attachment; filename="+filename.String()+".pdf")16 c.Writer.Write(response)17 return18}19func Export2PNG(c *gin.Context) {20 request_body := utils.GetStringFromGinRequestBody(c)21 webpage := gjson.Get(request_body, "message.webpage")22 filename := gjson.Get(request_body, "message.filename")23 fullpage := gjson.Get(request_body, "message.fullpage")24 page := rod.New().MustConnect().MustPage(webpage.String())25 var response []byte26 if fullpage.Bool() {27 response = page.MustWaitLoad().MustScreenshotFullPage()...
Using AI Code Generation
1import (2func main() {3 l := launcher.New().Headless(false).MustLaunch()4 defer l.Close()5 b := rod.New().ControlURL(l).MustConnect()6 defer b.Close()7 defer page.Close()8 page.MustWaitLoad()9 page.MustScreenshot("screenshot.png")10 page.MustWaitLoad()11 page.MustScreenshot("screenshot1.png")12 fmt.Println("Hello World")13}14import (15func main() {16 l := launcher.New().Headless(false).MustLaunch()17 defer l.Close()18 b := rod.New().ControlURL(l).MustConnect()19 defer b.Close()20 defer page.Close()21 page.MustWaitLoad()22 page.MustScreenshot("screenshot.png")23 page.MustWaitLoad()24 page.MustScreenshot("screenshot1.png")25 page.MustWaitLoad()26 page.MustScreenshot("screenshot2.png")27 fmt.Println("Hello World")28}29import (
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 title := page.MustTitle()5 fmt.Println("Page title:", title)6 browser.MustClose()7}8import (9func main() {10 browser := rod.New().MustConnect()11 title := page.MustTitle()12 fmt.Println("Page title:", title)13 browser.MustClose()14}15import (16func main() {17 browser := rod.New().MustConnect()18 title := page.MustTitle()19 fmt.Println("Page title:", title)20 browser.MustClose()21}22import (23func main() {24 browser := rod.New().MustConnect()25 title := page.MustTitle()26 fmt.Println("Page title:", title)27 browser.MustClose()28}29import (
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 pdf := page.MustPDF(&rod.PagePDF{5 })6 fmt.Println(pdf)7}
Using AI Code Generation
1import "fmt"2type rod struct {3}4func (r *rod) PDF() {5 fmt.Printf("PDF is %d6}7func main() {8 r.PDF()9}10import "fmt"11type rod struct {12}13func (r *rod) PDF() {14 fmt.Printf("PDF is %d15}16func main() {17 r.PDF()18 p.PDF()19}20import "fmt"21type rod struct {22}23func (r *rod) PDF() {24 fmt.Printf("PDF is %d25}26func main() {27 r.PDF()28 p.PDF()29 r1 := rod{length: 10, weight: 10}30 r1.PDF()31}32import "fmt"33type rod struct {34}35func (r *rod) PDF() {36 fmt.Printf("PDF is %d37}38func main() {
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 title := page.MustTitle()5 fmt.Println(title)6 browser.MustClose()7}8import (9func main() {10 browser := rod.New().MustConnect()11 page.MustPDF("page.pdf")12 browser.MustClose()13}14import (15func main() {16 browser := rod.New().MustConnect()17 page.MustScreenshot("page.png")18 browser.MustClose()19}
Using AI Code Generation
1import "fmt"2import "github.com/rod/rod"3func main() {4 browser := rod.New().MustConnect()5 page.MustWaitLoad()6 page.MustScreenshot("1.png")7 browser.MustClose()8}9import "fmt"10import "github.com/rod/rod"11func main() {12 browser := rod.New().MustConnect()13 page.MustWaitLoad()14 page.MustPDF("1.pdf")15 browser.MustClose()16}17import "fmt"18import "github.com/rod/rod"19func main() {20 browser := rod.New().MustConnect()21 page.MustWaitLoad()22 page.MustPDF("1.pdf")23 browser.MustClose()24}25import "fmt"26import "github.com/rod/rod"27func main() {28 browser := rod.New().MustConnect()29 page.MustWaitLoad()30 page.MustPDF("1.pdf")31 browser.MustClose()32}33import "fmt"34import "github.com/rod/rod"35func main() {36 browser := rod.New().MustConnect()37 page.MustWaitLoad()38 page.MustPDF("1.pdf")39 browser.MustClose()40}41import "fmt"42import "github.com/rod/rod"43func main() {44 browser := rod.New().MustConnect()45 page.MustWaitLoad()46 page.MustPDF("1.pdf")47 browser.MustClose()48}
Using AI Code Generation
1import "fmt"2import "github.com/rod"3type PDF struct {4}5func (p *PDF) PDF() {6 fmt.Println("I am a PDF")7}8func main() {9 p := &PDF{}10 p.Rod.Rod()11 p.PDF()12}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!