Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6e833533e | ||
|
|
1822fc3628 | ||
|
|
d80764b943 | ||
|
|
bd07add64e | ||
|
|
7fec8e1101 | ||
|
|
5b20d4406c | ||
|
|
40f683a917 | ||
|
|
ff460fffa1 |
@@ -17,20 +17,18 @@ import (
|
||||
|
||||
// html to pdf converter structure for
|
||||
type Converter struct {
|
||||
chromePath string
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
progress func(progress int)
|
||||
chromePath string
|
||||
allocCtx context.Context
|
||||
allocCancel context.CancelFunc // Cancels the whole Chrome process manager
|
||||
browserCtx context.Context // The specific browser instance
|
||||
browserCancel context.CancelFunc // Closes the browser
|
||||
progress func(progress int)
|
||||
}
|
||||
|
||||
// NewConverter starts a new converter instance with a chrome headless shell executable
|
||||
func NewConverter(chromePath string) (*Converter, error) {
|
||||
var err error
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
hideConsole()
|
||||
}
|
||||
|
||||
c := &Converter{chromePath: chromePath}
|
||||
chromePath, err = c.getChromePath()
|
||||
if err != nil {
|
||||
@@ -42,14 +40,21 @@ func NewConverter(chromePath string) (*Converter, error) {
|
||||
chromedp.NoSandbox,
|
||||
chromedp.Headless,
|
||||
chromedp.DisableGPU,
|
||||
chromedp.Flag("disable-software-rasterizer", true),
|
||||
chromedp.Flag("disable-dev-shm-usage", true),
|
||||
chromedp.Flag("no-first-run", true),
|
||||
)
|
||||
|
||||
var allocCtx context.Context
|
||||
allocCtx, c.cancel = chromedp.NewExecAllocator(context.Background(), opts...)
|
||||
c.ctx, c.cancel = chromedp.NewContext(allocCtx)
|
||||
opts = append(opts, platformOptions())
|
||||
|
||||
c.allocCtx, c.allocCancel = chromedp.NewExecAllocator(context.Background(), opts...)
|
||||
c.browserCtx, c.browserCancel = chromedp.NewContext(c.allocCtx)
|
||||
|
||||
// 5. "Warm up" the browser to ensure the executable actually runs
|
||||
// This catches "file not found" or permission errors immediately
|
||||
err = chromedp.Run(c.browserCtx)
|
||||
if err != nil {
|
||||
c.Close() // Cleanup if start fails
|
||||
return nil, fmt.Errorf("failed to start chrome: %w", err)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
@@ -86,10 +91,11 @@ func (c *Converter) Convert(files ...models.File) error {
|
||||
|
||||
htmlURL.WriteString(filepath.ToSlash(absPath))
|
||||
|
||||
c.ctx, c.cancel = context.WithTimeout(c.ctx, 60*time.Second)
|
||||
taskCtx, taskCancel := chromedp.NewContext(c.browserCtx)
|
||||
timeoutCtx, timeoutCancel := context.WithTimeout(taskCtx, 60*time.Second)
|
||||
|
||||
var pdfData []byte
|
||||
err = chromedp.Run(c.ctx,
|
||||
err = chromedp.Run(timeoutCtx,
|
||||
chromedp.Navigate(htmlURL.String()),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
@@ -106,21 +112,87 @@ func (c *Converter) Convert(files ...models.File) error {
|
||||
}),
|
||||
)
|
||||
|
||||
timeoutCancel()
|
||||
taskCancel()
|
||||
if err != nil {
|
||||
c.cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
// Save PDF to file
|
||||
if err := os.WriteFile(f.Output, pdfData, 0644); err != nil {
|
||||
c.cancel()
|
||||
return err
|
||||
}
|
||||
}
|
||||
c.cancel()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert converts all given input files
|
||||
func (c *Converter) ConvertHtmls(htmls ...models.Html) error {
|
||||
for i, h := range htmls {
|
||||
if c.progress != nil {
|
||||
c.progress(i + 1)
|
||||
}
|
||||
if len(h.Html) == 0 {
|
||||
return fmt.Errorf("no .html input provided")
|
||||
} else if h.Output == "" || filepath.Ext(h.Output) != ".pdf" {
|
||||
return fmt.Errorf("no .pdf output file path provided: %s", h.Output)
|
||||
}
|
||||
|
||||
taskCtx, taskCancel := chromedp.NewContext(c.browserCtx)
|
||||
timeoutCtx, timeoutCancel := context.WithTimeout(taskCtx, 60*time.Second)
|
||||
|
||||
var pdfData []byte
|
||||
err := chromedp.Run(timeoutCtx,
|
||||
// Start with a blank page
|
||||
chromedp.Navigate("about:blank"),
|
||||
// Inject HTML directly
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
frameTree, err := page.GetFrameTree().Do(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return page.SetDocumentContent(frameTree.Frame.ID, string(h.Html)).Do(ctx)
|
||||
}),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
buf, _, err := page.PrintToPDF().
|
||||
WithPrintBackground(true).
|
||||
WithPaperWidth(8.27).
|
||||
WithPaperHeight(11.69).
|
||||
Do(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pdfData = buf
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
|
||||
timeoutCancel()
|
||||
taskCancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Save PDF to file
|
||||
if err := os.WriteFile(h.Output, pdfData, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Converter) Close() {
|
||||
// Close browser first, then allocator
|
||||
if c.browserCancel != nil {
|
||||
c.browserCancel()
|
||||
}
|
||||
if c.allocCancel != nil {
|
||||
c.allocCancel()
|
||||
}
|
||||
}
|
||||
|
||||
// getChromePath checks for system Chrome, else falls back to bundled headless shell
|
||||
func (c *Converter) getChromePath() (string, error) {
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
package converter
|
||||
|
||||
// hideConsole does nothing on non-Windows systems
|
||||
func hideConsole() {
|
||||
// macOS and Linux don't have the same "console window" concept
|
||||
// that needs manual hiding at runtime like Windows.
|
||||
import "github.com/chromedp/chromedp"
|
||||
|
||||
func platformOptions() chromedp.ExecAllocatorOption {
|
||||
// Returns a no-op option for Mac/Linux
|
||||
return chromedp.NoSandbox
|
||||
}
|
||||
|
||||
@@ -3,21 +3,18 @@
|
||||
package converter
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"github.com/chromedp/chromedp"
|
||||
)
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
getConsoleWindow = kernel32.NewProc("GetConsoleWindow")
|
||||
showWindow = user32.NewProc("ShowWindow")
|
||||
)
|
||||
|
||||
const SW_HIDE = 0
|
||||
|
||||
func hideConsole() {
|
||||
hwnd, _, _ := getConsoleWindow.Call()
|
||||
if hwnd != 0 {
|
||||
showWindow.Call(hwnd, SW_HIDE)
|
||||
}
|
||||
func platformOptions() chromedp.ExecAllocatorOption {
|
||||
return chromedp.ModifyCmdFunc(func(cmd *exec.Cmd) {
|
||||
if cmd.SysProcAttr == nil {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{}
|
||||
}
|
||||
cmd.SysProcAttr.HideWindow = true
|
||||
cmd.SysProcAttr.CreationFlags = 0x08000000 // CREATE_NO_WINDOW
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ func Convert(chromePath, inputFile, outputFile string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
return c.Convert(input)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package html2pdf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -42,10 +43,11 @@ func TestConvertFiles(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
c, err := converter.NewConverter("./assets")
|
||||
c, err := converter.NewConverter("assets/chrome-headless-shell/win64")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
c.SetProgressCallback(func(progress int) {
|
||||
fmt.Println(progress)
|
||||
@@ -56,3 +58,62 @@ func TestConvertFiles(t *testing.T) {
|
||||
}
|
||||
t.Log("test successfull")
|
||||
}
|
||||
|
||||
func TestConvertHtml(t *testing.T) {
|
||||
t.Log("start test ConvertHtml")
|
||||
|
||||
// Skip in short mode (useful for CI)
|
||||
if testing.Short() {
|
||||
t.Skip("skipping ConvertHtml integration test in short mode")
|
||||
}
|
||||
|
||||
html := []byte(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Test PDF</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; }
|
||||
h1 { color: #333; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello PDF</h1>
|
||||
<p>This is a test.</p>
|
||||
</body>
|
||||
</html>
|
||||
`)
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
outputPath := filepath.Join(tmpDir, "test.pdf")
|
||||
|
||||
c, err := converter.NewConverter("assets/chrome-headless-shell/win64")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
err = c.ConvertHtmls(models.Html{Html: html, Output: outputPath})
|
||||
if err != nil {
|
||||
t.Fatalf("ConvertHtml failed: %v", err)
|
||||
}
|
||||
|
||||
// Assert PDF exists
|
||||
data, err := os.ReadFile(outputPath)
|
||||
if err != nil {
|
||||
t.Fatalf("PDF not created: %v", err)
|
||||
}
|
||||
|
||||
// Assert non-empty
|
||||
if len(data) == 0 {
|
||||
t.Fatal("PDF file is empty")
|
||||
}
|
||||
|
||||
// Assert valid PDF header
|
||||
if !bytes.HasPrefix(data, []byte("%PDF-")) {
|
||||
t.Fatalf("output is not a valid PDF (missing %%PDF- header)")
|
||||
}
|
||||
|
||||
t.Log("ConvertHtml test successful")
|
||||
}
|
||||
|
||||
9
models/html.go
Normal file
9
models/html.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package models
|
||||
|
||||
type Htmls []Html
|
||||
|
||||
// input model for converter
|
||||
type Html struct {
|
||||
Html []byte
|
||||
Output string
|
||||
}
|
||||
Reference in New Issue
Block a user