Last active
July 27, 2023 14:32
-
-
Save pasdam/e4d1eb72ff2ed482cdc8cce43b83fd47 to your computer and use it in GitHub Desktop.
Go - Print html to pdf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"log" | |
"os" | |
"github.com/playwright-community/playwright-go" | |
) | |
func main() { | |
pw, err := playwright.Run() | |
if err != nil { | |
log.Fatalf("could not start playwright: %v", err) | |
} | |
browser, err := pw.Chromium.Launch() | |
if err != nil { | |
log.Fatalf("could not launch browser: %v", err) | |
} | |
page, err := browser.NewPage() | |
if err != nil { | |
log.Fatalf("could not create page: %v", err) | |
} | |
// if err = page.SetContent("<html><body><h1>Test</h1></body></html>"); err != nil { | |
if _, err = page.Goto("file://index.html"); err != nil { | |
log.Fatalf("could not goto: %v", err) | |
} | |
page.WaitForLoadState("networkidle") | |
printBackground := true | |
scale := 0.83 | |
content, err := page.PDF(playwright.PagePdfOptions{ | |
PrintBackground: &printBackground, | |
Scale: &scale, | |
}) | |
if err != nil { | |
log.Fatalf("could not get entries: %v", err) | |
} | |
filePath := "temp.pdf" | |
var f *os.File | |
if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) { | |
f, err = os.Create(filePath) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} else { | |
f, err = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, os.ModeAppend) | |
if err != nil { | |
log.Fatalf("could not generate pdf: %v", err) | |
} | |
} | |
defer f.Close() | |
_, err = f.Write(content) | |
if err != nil { | |
log.Fatalf("could not save pdf: %v", err) | |
} | |
if err = browser.Close(); err != nil { | |
log.Fatalf("could not close browser: %v", err) | |
} | |
if err = pw.Stop(); err != nil { | |
log.Fatalf("could not stop Playwright: %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment