nidus-sync/platform/pdf/pdf.go
Eli Ribble 15d8966971
Some checks failed
/ golint (push) Failing after 3m56s
Add context timeouts for third-party requests
Avoid hanging a goroutine for a long time.
2026-05-19 00:24:40 +00:00

46 lines
1.2 KiB
Go

package pdf
import (
"context"
"fmt"
"time"
"github.com/Gleipnir-Technology/nidus-sync/config"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/rs/zerolog/log"
)
func GeneratePDF(ctx context.Context, path string) ([]byte, error) {
// create context
chromedp.Env("CHROME_FLAGS=--no-sandbox --disable-gpu --disable-dev-shm-usage")
chromeCtx, chromeCancel := context.WithTimeout(context.Background(), 60*time.Second)
defer chromeCancel()
chrome_ctx, cancel := chromedp.NewContext(chromeCtx)
defer cancel()
// capture pdf
var buf []byte
url := fmt.Sprintf("https://%s%s", config.DomainNidus, path)
log.Info().Str("url", url).Msg("Getting with headless chrome")
if err := chromedp.Run(chrome_ctx, printToPDF(url, &buf)); err != nil {
return nil, fmt.Errorf("print to pdf: %w", err)
}
return buf, nil
}
// print a specific pdf page.
func printToPDF(urlstr string, res *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(urlstr),
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().WithPrintBackground(false).Do(ctx)
if err != nil {
return err
}
*res = buf
return nil
}),
}
}