diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index cf1fce5..be3f9ef 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -17,7 +17,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version-file: go.mod - name: Install wkhtmltopdf run: | diff --git a/.gitignore b/.gitignore index 6f72f89..1d3b607 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ go.work.sum # env file .env + +# Build output +/bin/ diff --git a/.goreleaser.yml b/.goreleaser.yml index 5a03daf..aec8224 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -14,7 +14,7 @@ builds: ignore: - goos: windows goarch: arm64 - main: . + main: ./cmd/go-mdtopdf-helper binary: go-mdtopdf-helper ldflags: - -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}} diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b3744e2 --- /dev/null +++ b/Makefile @@ -0,0 +1,25 @@ +BINARY := go-mdtopdf-helper +BIN_DIR := bin +CMD := ./cmd/go-mdtopdf-helper + +.PHONY: all build run test lint format clean + +all: format lint test build + +build: + go build -o $(BIN_DIR)/$(BINARY) $(CMD) + +run: + go run $(CMD) $(ARGS) + +test: + go test ./... + +lint: + golangci-lint run ./... + +format: + gofmt -s -w . + +clean: + rm -rf $(BIN_DIR) diff --git a/README.md b/README.md index 4c9ecc7..e6053f6 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,38 @@ # go-mdtopdf-helper -A command-line tool that automatically converts Markdown files to PDF using wkhtmltopdf. Perfect for maintaining PDF documentation alongside your Markdown files in Git repositories. +A command-line tool that automatically converts Markdown files to PDF. Perfect for maintaining PDF documentation alongside your Markdown files in Git repositories. ## Features -- Converts Markdown files to high-quality PDFs +- Converts Markdown files to PDF, HTML or DOCX (one or several at once) +- Choice of PDF rendering engines +- Works out of the box: the default engine is pure Go with no external dependencies - Can run as a Git pre-commit hook - Recursive directory scanning - Parallel file processing - Cross-platform support (Windows, Linux, macOS) -- Automatic detection of wkhtmltopdf installation -## Prerequisites +## Output Formats -This tool requires [wkhtmltopdf](https://wkhtmltopdf.org/) to be installed on your system. The application will check for its presence in standard installation locations: +Select formats with `-format`, for example `-format pdf,html,docx`. Each file is written next to its Markdown source with the matching extension (`README.md` → `README.pdf`, `README.html`, `README.docx`). -- Windows: `C:\Program Files\wkhtmltopdf\bin` -- Linux: `/usr/local/bin/wkhtmltopdf` or `/usr/bin/wkhtmltopdf` -- macOS: `/usr/local/bin/wkhtmltopdf` or via Homebrew +- **pdf**: rendered by the selected engine (see below). +- **html**: a standalone page with embedded CSS. +- **docx**: a Word document generated in pure Go (no Word or other tools needed). Supports headings, paragraphs, bold/italic/code, links, bulleted and numbered lists, code blocks, quotes, rules and tables. Images are written as `[image: alt]` text. -If wkhtmltopdf is not found, you will be prompted to install it. +In pre-commit hook mode every generated file is staged. + +## Engines + +The engine only applies to PDF output. + +Select an engine with `-engine`: + +| Engine | Needs | Notes | +|--------|-------|-------| +| `gopdf` (default) | nothing | Pure Go. Supports headings, paragraphs, bold/italic/code, links, lists, code blocks, quotes, rules and tables. Images are shown as `[image: alt]`. | +| `chromedp` | Chrome or Chromium | Best rendering (full HTML/CSS). Runs headless Chrome; the sandbox is disabled automatically when running as root, as in most CI containers. | +| `wkhtmltopdf` | [wkhtmltopdf](https://wkhtmltopdf.org/) | Legacy engine. Looked up in the standard install locations (Windows: `C:\Program Files\wkhtmltopdf\bin`, Linux/macOS: `/usr/local/bin`, `/usr/bin`, Homebrew). | ## Installation @@ -51,6 +64,10 @@ Options: Convert files in parallel (default true) -hook Run as git pre-commit hook + -engine string + PDF engine: gopdf, wkhtmltopdf, chromedp (default "gopdf") + -format string + Output formats, comma separated: pdf, html, docx (default "pdf") ``` ### Git Pre-commit Hook @@ -79,11 +96,16 @@ When enabled as a pre-commit hook, the tool will: ## PDF Output Configuration -The generated PDFs are configured with: -- 300 DPI resolution -- 15mm margins on all sides -- Local file access enabled for images -- Support for common Markdown extensions +Generated PDFs are A4 with 15mm margins on all sides. The `chromedp` and `wkhtmltopdf` engines render the full Markdown-to-HTML output, so they support everything the Markdown parser's common extensions produce. + +## Project Layout + +``` +cmd/go-mdtopdf-helper/ CLI entry point (flags, hook mode) +internal/converter/ File discovery, parallel conversion, git hook +internal/document/ HTML and DOCX writers +internal/engine/ Engine interface and the gopdf, wkhtmltopdf and chromedp backends +``` ## Contributing @@ -105,11 +127,15 @@ Contributions are welcome! Please feel free to submit a Pull Request. Here's how 3. Make your changes 4. Run tests: ```bash - go test ./... + make test ``` +`make` also provides `build`, `lint` (golangci-lint), `format` (gofmt) and `all`. Tests for the `chromedp` and `wkhtmltopdf` engines are skipped when the tool is not installed. + ## Dependencies +- [gopdf](https://github.com/signintech/gopdf) - Pure Go PDF generation +- [chromedp](https://github.com/chromedp/chromedp) - Headless Chrome driver - [go-wkhtmltopdf](https://github.com/SebastiaanKlippert/go-wkhtmltopdf) - Go wrapper for wkhtmltopdf - [gomarkdown](https://github.com/gomarkdown/markdown) - Markdown parser and HTML renderer diff --git a/README.pdf b/README.pdf index 87043da..d0b99aa 100644 Binary files a/README.pdf and b/README.pdf differ diff --git a/cmd/go-mdtopdf-helper/main.go b/cmd/go-mdtopdf-helper/main.go new file mode 100644 index 0000000..3a62181 --- /dev/null +++ b/cmd/go-mdtopdf-helper/main.go @@ -0,0 +1,64 @@ +package main + +import ( + "flag" + "fmt" + "os" + "slices" + "strings" + + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/converter" + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine" +) + +func main() { + os.Exit(run()) +} + +func run() int { + conv := &converter.Converter{} + var hookMode bool + var engineName, formatList string + + flag.StringVar(&conv.InputDir, "dir", ".", "Directory to scan for markdown files") + flag.BoolVar(&conv.Recursive, "recursive", true, "Scan directories recursively") + flag.BoolVar(&conv.Parallel, "parallel", true, "Convert files in parallel") + flag.BoolVar(&hookMode, "hook", false, "Run as git pre-commit hook") + flag.StringVar(&engineName, "engine", engine.Default, + "PDF engine: "+strings.Join(engine.Names, ", ")) + flag.StringVar(&formatList, "format", converter.FormatPDF, + "Output formats, comma separated: "+strings.Join(converter.FormatNames, ", ")) + flag.Parse() + + formats, err := converter.ParseFormats(formatList) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 2 + } + conv.Formats = formats + + // The engine only matters for PDF output. + if slices.Contains(formats, converter.FormatPDF) { + eng, err := engine.New(engineName) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 2 + } + defer func() { _ = eng.Close() }() + conv.Engine = eng + } + + if hookMode { + if err := conv.RunAsHook(); err != nil { + fmt.Fprintf(os.Stderr, "Hook error: %v\n", err) + return 1 + } + return 0 + } + + if err := conv.Run(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 1 + } + return 0 +} diff --git a/converter_test.go b/converter_test.go deleted file mode 100644 index d73c8a7..0000000 --- a/converter_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package main - -import ( - "os" - "path/filepath" - "testing" -) - -func TestBasicCompilation(t *testing.T) { - // Create a temporary directory for test - tmpDir, err := os.MkdirTemp("", "mdtopdf-test") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tmpDir) - - // Create a simple test markdown file - testContent := `# Test Document -This is a basic test.` - - testFile := filepath.Join(tmpDir, "test.md") - if err := os.WriteFile(testFile, []byte(testContent), 0644); err != nil { - t.Fatalf("Failed to create test file: %v", err) - } - - // Create and test converter - conv := &Converter{ - inputDir: tmpDir, - recursive: false, - parallel: false, - } - - // Run conversion - err = conv.Run() - if err != nil { - t.Fatalf("Basic conversion failed: %v", err) - } - - // Check if PDF was created - pdfPath := filepath.Join(tmpDir, "test.pdf") - if _, err := os.Stat(pdfPath); os.IsNotExist(err) { - t.Error("PDF file was not created") - } -} diff --git a/go.mod b/go.mod index 9183618..f25b5ba 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,18 @@ module github.com/Warky-Devs/go-mdtopdf-helper.git -go 1.22.5 +go 1.26.0 require ( github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.3 + github.com/chromedp/cdproto v0.157.8 + github.com/chromedp/chromedp v0.20.1 github.com/gomarkdown/markdown v0.0.0-20241205020045-f7e15b2f3e62 + github.com/signintech/gopdf v0.38.1 + golang.org/x/image v0.46.0 +) + +require ( + github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875 // indirect + github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311 // indirect + github.com/pkg/errors v0.8.1 // indirect ) diff --git a/go.sum b/go.sum index 005e4d9..3ab5952 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,26 @@ github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.3 h1:vrA6+R1BMLKMTbos8jAeuBrImHPGtY4gTlcue3OIej8= github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.3/go.mod h1:SQq4xfIdvf6WYKSDxAJc+xOJdolt+/bc1jnQKMtPMvQ= +github.com/chromedp/cdproto v0.157.8 h1:Tkq0AjsUlC3Z4sJfHBzV/uAAxnTF/AZyuSTjfV/1gvk= +github.com/chromedp/cdproto v0.157.8/go.mod h1:h68JaIuFr9o3yiayxEYhBdvaxgYO3shDrPSYhNlyfu0= +github.com/chromedp/chromedp v0.20.1 h1:983T9wmyM09JtROWlxhLQwljKOQovqt8CVE89W3U0NA= +github.com/chromedp/chromedp v0.20.1/go.mod h1:6z1Y5FdKUxRzxx2qcC5h1xjaBJrSWrZp1mjgITfNZig= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875 h1:XGPtjxqp0FS8jj1Z7QGcSOSgyq1fUPjNyJXvi3KfI4A= +github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875/go.mod h1:uNVvRXArCGbZ508SxYYTC5v1JWoz2voff5pm25jU1Ok= github.com/gomarkdown/markdown v0.0.0-20241205020045-f7e15b2f3e62 h1:pbAFUZisjG4s6sxvRJvf2N7vhpCvx2Oxb3PmS6pDO1g= github.com/gomarkdown/markdown v0.0.0-20241205020045-f7e15b2f3e62/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA= +github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311 h1:zyWXQ6vu27ETMpYsEMAsisQ+GqJ4e1TPvSNfdOPF0no= +github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/signintech/gopdf v0.38.1 h1:mMdVMPKrvHCskYmjet/uTuXRAEV742oTM7GdFcuhuwM= +github.com/signintech/gopdf v0.38.1/go.mod h1:d23eO35GpEliSrF22eJ4bsM3wVeQJTjXTHq5x5qGKjA= github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= +golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/converter/converter.go b/internal/converter/converter.go new file mode 100644 index 0000000..2861cc1 --- /dev/null +++ b/internal/converter/converter.go @@ -0,0 +1,186 @@ +// Package converter finds Markdown files and converts them to PDF, HTML or DOCX. +package converter + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document" + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine" +) + +// Output formats accepted by ParseFormats. +const ( + FormatPDF = "pdf" + FormatHTML = "html" + FormatDOCX = "docx" +) + +// FormatNames lists every supported output format. +var FormatNames = []string{FormatPDF, FormatHTML, FormatDOCX} + +// ParseFormats turns a comma separated list such as "pdf,html" into validated, de-duplicated formats. +func ParseFormats(list string) ([]string, error) { + var formats []string + seen := map[string]bool{} + for _, f := range strings.Split(list, ",") { + f = strings.ToLower(strings.TrimSpace(f)) + if f == "" || seen[f] { + continue + } + if !slices.Contains(FormatNames, f) { + return nil, fmt.Errorf("unknown format %q (available: %s)", f, strings.Join(FormatNames, ", ")) + } + seen[f] = true + formats = append(formats, f) + } + if len(formats) == 0 { + return nil, fmt.Errorf("no output format given (available: %s)", strings.Join(FormatNames, ", ")) + } + return formats, nil +} + +// Converter converts Markdown files found under InputDir into each of Formats. +// Engine renders the PDF format and may be nil when PDF is not requested. +type Converter struct { + InputDir string + Recursive bool + Parallel bool + Formats []string + Engine engine.Engine +} + +// outputPath returns the file written for inputFile in the given format. +func outputPath(inputFile, format string) string { + return strings.TrimSuffix(inputFile, filepath.Ext(inputFile)) + "." + format +} + +// Run converts every Markdown file under InputDir. +func (c *Converter) Run() error { + files, err := c.findMarkdownFiles() + if err != nil { + return fmt.Errorf("failed to find markdown files: %w", err) + } + + if len(files) == 0 { + fmt.Println("No markdown files found") + return nil + } + + return c.ConvertFiles(files) +} + +// ConvertFiles converts the given Markdown files, in parallel when enabled. +func (c *Converter) ConvertFiles(files []string) error { + if c.Parallel { + return c.convertFilesParallel(files) + } + return c.convertFilesSerial(files) +} + +func isMarkdown(path string) bool { + return strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".markdown") +} + +func (c *Converter) findMarkdownFiles() ([]string, error) { + var files []string + + walkFn := func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if info.IsDir() && !c.Recursive && path != c.InputDir { + return filepath.SkipDir + } + + if !info.IsDir() && isMarkdown(path) { + files = append(files, path) + } + + return nil + } + + if err := filepath.Walk(c.InputDir, walkFn); err != nil { + return nil, err + } + + return files, nil +} + +func (c *Converter) convertFilesParallel(files []string) error { + var wg sync.WaitGroup + errs := make(chan error, len(files)) + + for _, file := range files { + wg.Add(1) + go func(f string) { + defer wg.Done() + if err := c.convertFile(f); err != nil { + errs <- fmt.Errorf("failed to convert %s: %w", f, err) + } + }(file) + } + + wg.Wait() + close(errs) + + for err := range errs { + return err + } + return nil +} + +func (c *Converter) convertFilesSerial(files []string) error { + for _, file := range files { + if err := c.convertFile(file); err != nil { + return fmt.Errorf("failed to convert %s: %w", file, err) + } + } + return nil +} + +func (c *Converter) convertFile(inputFile string) error { + mdContent, err := os.ReadFile(inputFile) + if err != nil { + return fmt.Errorf("failed to read file: %w", err) + } + + formats := c.Formats + if len(formats) == 0 { + formats = []string{FormatPDF} + } + + for _, format := range formats { + outputFile := outputPath(inputFile, format) + if err := c.write(mdContent, format, outputFile); err != nil { + return fmt.Errorf("%s: %w", format, err) + } + fmt.Printf("Successfully converted %s to %s\n", inputFile, outputFile) + } + return nil +} + +func (c *Converter) write(md []byte, format, outputFile string) error { + switch format { + case FormatPDF: + if c.Engine == nil { + return fmt.Errorf("no PDF engine configured") + } + return c.Engine.Render(md, outputFile) + case FormatHTML: + return os.WriteFile(outputFile, document.HTML(md), 0o644) + case FormatDOCX: + data, err := document.DOCX(md) + if err != nil { + return err + } + return os.WriteFile(outputFile, data, 0o644) + default: + return fmt.Errorf("unknown format %q", format) + } +} diff --git a/internal/converter/converter_test.go b/internal/converter/converter_test.go new file mode 100644 index 0000000..de95452 --- /dev/null +++ b/internal/converter/converter_test.go @@ -0,0 +1,103 @@ +package converter + +import ( + "bytes" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine" +) + +func TestRunConvertsMarkdownFiles(t *testing.T) { + tmpDir := t.TempDir() + + content := "# Test Document\nThis is a basic test." + if err := os.WriteFile(filepath.Join(tmpDir, "test.md"), []byte(content), 0o644); err != nil { + t.Fatalf("Failed to create test file: %v", err) + } + + eng, err := engine.New(engine.Default) + if err != nil { + t.Fatal(err) + } + defer func() { _ = eng.Close() }() + + conv := &Converter{InputDir: tmpDir, Engine: eng} + if err := conv.Run(); err != nil { + t.Fatalf("Conversion failed: %v", err) + } + + pdf, err := os.ReadFile(filepath.Join(tmpDir, "test.pdf")) + if err != nil { + t.Fatalf("PDF file was not created: %v", err) + } + if !bytes.HasPrefix(pdf, []byte("%PDF")) { + t.Error("output is not a PDF") + } +} + +func TestRunNonRecursiveSkipsSubdirs(t *testing.T) { + tmpDir := t.TempDir() + sub := filepath.Join(tmpDir, "sub") + if err := os.Mkdir(sub, 0o755); err != nil { + t.Fatal(err) + } + for _, p := range []string{filepath.Join(tmpDir, "a.md"), filepath.Join(sub, "b.md")} { + if err := os.WriteFile(p, []byte("# hi"), 0o644); err != nil { + t.Fatal(err) + } + } + + eng, _ := engine.New(engine.Default) + conv := &Converter{InputDir: tmpDir, Engine: eng} + if err := conv.Run(); err != nil { + t.Fatal(err) + } + + if _, err := os.Stat(filepath.Join(tmpDir, "a.pdf")); err != nil { + t.Errorf("expected a.pdf: %v", err) + } + if _, err := os.Stat(filepath.Join(sub, "b.pdf")); err == nil { + t.Error("b.pdf should not exist when not recursive") + } +} + +func TestParseFormats(t *testing.T) { + got, err := ParseFormats("PDF, html,pdf,docx") + if err != nil { + t.Fatal(err) + } + if want := []string{FormatPDF, FormatHTML, FormatDOCX}; !slices.Equal(got, want) { + t.Errorf("got %v, want %v", got, want) + } + + for _, bad := range []string{"", ",", "odt", "pdf,rtf"} { + if _, err := ParseFormats(bad); err == nil { + t.Errorf("ParseFormats(%q) should fail", bad) + } + } +} + +func TestRunWritesAllFormats(t *testing.T) { + tmpDir := t.TempDir() + if err := os.WriteFile(filepath.Join(tmpDir, "doc.md"), []byte("# Hi\n\ntext"), 0o644); err != nil { + t.Fatal(err) + } + + // No engine needed when PDF is not requested. + conv := &Converter{InputDir: tmpDir, Formats: []string{FormatHTML, FormatDOCX}} + if err := conv.Run(); err != nil { + t.Fatal(err) + } + + for _, ext := range []string{"html", "docx"} { + if _, err := os.Stat(filepath.Join(tmpDir, "doc."+ext)); err != nil { + t.Errorf("expected doc.%s: %v", ext, err) + } + } + if _, err := os.Stat(filepath.Join(tmpDir, "doc.pdf")); err == nil { + t.Error("doc.pdf should not be written") + } +} diff --git a/internal/converter/hook.go b/internal/converter/hook.go new file mode 100644 index 0000000..af3f529 --- /dev/null +++ b/internal/converter/hook.go @@ -0,0 +1,81 @@ +package converter + +import ( + "bufio" + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// RunAsHook converts the staged Markdown files and stages the generated output. +func (c *Converter) RunAsHook() error { + if !confirmConversion() { + fmt.Println("Skipping conversion") + return nil + } + + files, err := stagedMarkdownFiles() + if err != nil { + return fmt.Errorf("failed to get staged files: %w", err) + } + + if len(files) == 0 { + return nil + } + + if err := c.ConvertFiles(files); err != nil { + return err + } + + return c.stageGeneratedFiles(files) +} + +func confirmConversion() bool { + fmt.Print("Convert Markdown files? [Y/n] ") + reader := bufio.NewReader(os.Stdin) + response, err := reader.ReadString('\n') + if err != nil { + return false + } + + response = strings.ToLower(strings.TrimSpace(response)) + return response == "" || response == "y" || response == "yes" +} + +func stagedMarkdownFiles() ([]string, error) { + cmd := exec.Command("git", "diff", "--cached", "--name-only", "--diff-filter=d") + output, err := cmd.Output() + if err != nil { + return nil, err + } + + var files []string + scanner := bufio.NewScanner(bytes.NewReader(output)) + for scanner.Scan() { + if file := scanner.Text(); isMarkdown(file) { + files = append(files, file) + } + } + + return files, scanner.Err() +} + +func (c *Converter) stageGeneratedFiles(files []string) error { + formats := c.Formats + if len(formats) == 0 { + formats = []string{FormatPDF} + } + + for _, file := range files { + for _, format := range formats { + out := filepath.FromSlash(outputPath(file, format)) + if err := exec.Command("git", "add", out).Run(); err != nil { + fmt.Printf("Warning: Could not stage %s\n", out) + } + } + } + return nil +} diff --git a/internal/document/document_test.go b/internal/document/document_test.go new file mode 100644 index 0000000..1c0fb7b --- /dev/null +++ b/internal/document/document_test.go @@ -0,0 +1,73 @@ +package document + +import ( + "archive/zip" + "bytes" + "encoding/xml" + "io" + "strings" + "testing" +) + +const sample = "# Title\n\nSome **bold**, *italic*, `code` & a [link](http://example.com/?a=1&b=2).\n\n" + + "- one\n- two\n - nested\n\n1. first\n2. second\n ```\n code in item\n ```\n\n" + + "> quote\n\n---\n\n```\nfunc main() {}\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n" + +func TestHTML(t *testing.T) { + out := string(HTML([]byte(sample))) + for _, want := range []string{"", " + + +` + +const htmlFoot = "\n\n\n" + +// NewParser returns the Markdown parser used by every output format. +func NewParser() *parser.Parser { + return parser.NewWithExtensions(parser.CommonExtensions | parser.AutoHeadingIDs) +} + +// HTML renders a standalone HTML document with embedded styling. +func HTML(md []byte) []byte { + body := markdown.ToHTML(md, NewParser(), nil) + out := make([]byte, 0, len(htmlHead)+len(body)+len(htmlFoot)) + out = append(out, htmlHead...) + out = append(out, body...) + return append(out, htmlFoot...) +} diff --git a/internal/engine/chromedp.go b/internal/engine/chromedp.go new file mode 100644 index 0000000..706de44 --- /dev/null +++ b/internal/engine/chromedp.go @@ -0,0 +1,100 @@ +package engine + +import ( + "context" + "fmt" + "os" + "sync" + "time" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/page" + "github.com/chromedp/chromedp" +) + +const ( + renderTimeout = 60 * time.Second + marginInches = 15 / 25.4 // 15mm +) + +// chromedpEngine drives a single headless Chrome shared by all renders; each render gets its own tab. +type chromedpEngine struct { + once sync.Once + browserCtx context.Context + cancelBrowser context.CancelFunc + cancelAlloc context.CancelFunc + startErr error +} + +func (e *chromedpEngine) Name() string { return Chromedp } + +func (e *chromedpEngine) start() { + opts := append([]chromedp.ExecAllocatorOption{}, chromedp.DefaultExecAllocatorOptions[:]...) + opts = append(opts, chromedp.Flag("disable-dev-shm-usage", true)) + // Containers and CI commonly run as root, where Chrome refuses to start with its sandbox. + if os.Geteuid() == 0 { + opts = append(opts, chromedp.NoSandbox) + } + + allocCtx, cancelAlloc := chromedp.NewExecAllocator(context.Background(), opts...) + browserCtx, cancelBrowser := chromedp.NewContext(allocCtx) + e.browserCtx, e.cancelBrowser, e.cancelAlloc = browserCtx, cancelBrowser, cancelAlloc + + // The browser lives as long as the context that first runs it, so start it here + // instead of from a per-render context that is cancelled after each file. + e.startErr = chromedp.Do(browserCtx) +} + +func (e *chromedpEngine) Render(md []byte, outputFile string) error { + e.once.Do(e.start) + if e.startErr != nil { + return fmt.Errorf("failed to start Chrome (is Chrome/Chromium installed?): %w", e.startErr) + } + + tabCtx, cancelTab := chromedp.NewContext(e.browserCtx) + defer cancelTab() + // Run once so the tab owns no timeout, then bound the actual work. + if err := chromedp.Do(tabCtx); err != nil { + return fmt.Errorf("failed to open Chrome tab: %w", err) + } + ctx, cancel := context.WithTimeout(tabCtx, renderTimeout) + defer cancel() + + html := string(markdownToHTML(md)) + setContent := chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { + tree, err := cdp.Call(ctx, t, page.GetFrameTree, cdp.Empty{}) + if err != nil { + return err + } + _, err = cdp.Call(ctx, t, page.SetDocumentContent, page.SetDocumentContentParams{ + FrameID: tree.FrameTree.Frame.ID, + HTML: html, + }) + return err + }) + if err := chromedp.Do(ctx, chromedp.Navigate("about:blank"), setContent); err != nil { + return fmt.Errorf("failed to load document in Chrome: %w", err) + } + + pdf, err := chromedp.Run(ctx, chromedp.PrintToPDF( + chromedp.PDFPaper(chromedp.PaperA4), + chromedp.PDFMargin(marginInches), + chromedp.PDFPrintBackground(), + )) + if err != nil { + return fmt.Errorf("chrome failed to render PDF: %w", err) + } + + if err := os.WriteFile(outputFile, pdf, 0o644); err != nil { + return fmt.Errorf("failed to write PDF file: %w", err) + } + return nil +} + +func (e *chromedpEngine) Close() error { + if e.cancelBrowser != nil { + e.cancelBrowser() + e.cancelAlloc() + } + return nil +} diff --git a/internal/engine/engine.go b/internal/engine/engine.go new file mode 100644 index 0000000..1fb78c5 --- /dev/null +++ b/internal/engine/engine.go @@ -0,0 +1,43 @@ +// Package engine converts Markdown documents to PDF using interchangeable backends. +package engine + +import ( + "fmt" + "strings" +) + +// Engine names accepted by New. +const ( + GoPDF = "gopdf" + Wkhtmltopdf = "wkhtmltopdf" + Chromedp = "chromedp" +) + +// Default is the engine used when none is requested. It needs no external binaries. +const Default = GoPDF + +// Names lists every supported engine. +var Names = []string{GoPDF, Wkhtmltopdf, Chromedp} + +// Engine renders Markdown into a PDF file. +type Engine interface { + Name() string + // Render converts the Markdown source and writes the PDF to outputFile. + Render(markdown []byte, outputFile string) error + // Close releases resources held by the engine. It is safe to call more than once. + Close() error +} + +// New returns the engine registered under name. +func New(name string) (Engine, error) { + switch strings.ToLower(name) { + case GoPDF: + return &gopdfEngine{}, nil + case Wkhtmltopdf: + return &wkhtmltopdfEngine{}, nil + case Chromedp: + return &chromedpEngine{}, nil + default: + return nil, fmt.Errorf("unknown engine %q (available: %s)", name, strings.Join(Names, ", ")) + } +} diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go new file mode 100644 index 0000000..bd6cd46 --- /dev/null +++ b/internal/engine/engine_test.go @@ -0,0 +1,79 @@ +package engine + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +var sample = "# Title\n\n" + + "Some *italic*, **bold**, `code` and a [link](http://example.com) in a paragraph that is long enough to wrap " + + "across several lines so that the line layout code gets exercised properly. " + strings.Repeat("word ", 80) + "\n\n" + + "## List\n\n- one\n- two\n - nested\n\n1. first\n2. second\n\n" + + "> quoted text\n\n---\n\n" + + "```go\nfunc main() {\n\tfmt.Println(\"hi\")\n}\n```\n\n" + + "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n\n" + + "averyveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongunbreakableword\n" + +func TestNewUnknownEngine(t *testing.T) { + if _, err := New("nope"); err == nil { + t.Error("expected error for unknown engine") + } +} + +func TestNewKnownEngines(t *testing.T) { + for _, name := range Names { + e, err := New(name) + if err != nil { + t.Fatalf("New(%q): %v", name, err) + } + if e.Name() != name { + t.Errorf("Name() = %q, want %q", e.Name(), name) + } + } +} + +func renderSample(t *testing.T, name string) { + t.Helper() + e, err := New(name) + if err != nil { + t.Fatal(err) + } + defer func() { _ = e.Close() }() + + out := filepath.Join(t.TempDir(), "out.pdf") + if err := e.Render([]byte(sample), out); err != nil { + t.Fatalf("render with %s: %v", name, err) + } + pdf, err := os.ReadFile(out) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(pdf, []byte("%PDF")) { + t.Errorf("%s output is not a PDF", name) + } +} + +func TestGoPDFRender(t *testing.T) { + renderSample(t, GoPDF) +} + +func TestWkhtmltopdfRender(t *testing.T) { + if _, err := exec.LookPath("wkhtmltopdf"); err != nil { + t.Skip("wkhtmltopdf not installed") + } + renderSample(t, Wkhtmltopdf) +} + +func TestChromedpRender(t *testing.T) { + for _, bin := range []string{"google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome"} { + if _, err := exec.LookPath(bin); err == nil { + renderSample(t, Chromedp) + return + } + } + t.Skip("Chrome/Chromium not installed") +} diff --git a/internal/engine/gopdf.go b/internal/engine/gopdf.go new file mode 100644 index 0000000..f4a20d0 --- /dev/null +++ b/internal/engine/gopdf.go @@ -0,0 +1,599 @@ +package engine + +import ( + "fmt" + "strconv" + "strings" + "unicode" + + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document" + "github.com/gomarkdown/markdown/ast" + "github.com/signintech/gopdf" + "golang.org/x/image/font/gofont/gobold" + "golang.org/x/image/font/gofont/gobolditalic" + "golang.org/x/image/font/gofont/goitalic" + "golang.org/x/image/font/gofont/gomono" + "golang.org/x/image/font/gofont/goregular" +) + +// gopdfEngine renders Markdown directly into PDF drawing commands. It has no external dependencies. +type gopdfEngine struct{} + +func (e *gopdfEngine) Name() string { return GoPDF } + +func (e *gopdfEngine) Close() error { return nil } + +func (e *gopdfEngine) Render(md []byte, outputFile string) error { + r, err := newPDFRenderer() + if err != nil { + return err + } + + doc := document.NewParser().Parse(md) + r.blocks(doc.GetChildren(), r.left, r.right-r.left) + if r.err != nil { + return r.err + } + return r.pdf.WritePdf(outputFile) +} + +const ( + pageWidth = 595.28 // A4 in points + pageHeight = 841.89 + pageMargin = 42.5 // 15mm + bodySize = 11.0 + codeSize = 9.0 + lineSpacing = 1.4 + blockGap = 6.0 + listIndent = 18.0 + quoteIndent = 14.0 + cellPadding = 4.0 + tabWidth = " " + baselineShift = 0.8 + fontRegular = "go" + fontBold = "go-bold" + fontItalic = "go-italic" + fontBoldItal = "go-bold-italic" + fontMono = "go-mono" +) + +type rgb struct{ r, g, b uint8 } + +var ( + colorText = rgb{34, 34, 34} + colorLink = rgb{0, 0, 238} + colorRule = rgb{204, 204, 204} + colorCode = rgb{244, 244, 244} +) + +// style describes the inline formatting in effect while collecting tokens. +type style struct { + bold, italic, mono, link bool +} + +// token is one word with its formatting. Width fields are filled in during layout. +type token struct { + text string + family string + size float64 + color rgb + spaceBefore bool + lineBreak bool + width float64 + space float64 +} + +type line struct { + tokens []token + height float64 +} + +type pdfRenderer struct { + pdf *gopdf.GoPdf + left, right float64 + y float64 + page int + err error +} + +func newPDFRenderer() (*pdfRenderer, error) { + pdf := &gopdf.GoPdf{} + pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: pageWidth, H: pageHeight}}) + + fonts := map[string][]byte{ + fontRegular: goregular.TTF, + fontBold: gobold.TTF, + fontItalic: goitalic.TTF, + fontBoldItal: gobolditalic.TTF, + fontMono: gomono.TTF, + } + for name, data := range fonts { + if err := pdf.AddTTFFontData(name, data); err != nil { + return nil, fmt.Errorf("failed to load font %s: %w", name, err) + } + } + + pdf.AddPage() + return &pdfRenderer{pdf: pdf, left: pageMargin, right: pageWidth - pageMargin, y: pageMargin, page: 1}, nil +} + +func (r *pdfRenderer) fail(err error) { + if err != nil && r.err == nil { + r.err = err + } +} + +// ensureSpace starts a new page when h points do not fit below the current position. +func (r *pdfRenderer) ensureSpace(h float64) { + if r.y+h > pageHeight-pageMargin { + r.pdf.AddPage() + r.page++ + r.y = pageMargin + } +} + +func (r *pdfRenderer) setFont(family string, size float64) { + r.fail(r.pdf.SetFont(family, "", size)) +} + +func (r *pdfRenderer) measure(family string, size float64, text string) float64 { + r.setFont(family, size) + w, err := r.pdf.MeasureTextWidth(text) + r.fail(err) + return w +} + +// blocks renders block level nodes. Runs of adjacent inline nodes (as found in tight list items) +// are treated as one paragraph. +func (r *pdfRenderer) blocks(nodes []ast.Node, x, width float64) { + var inline []ast.Node + flush := func() { + if len(inline) > 0 { + r.paragraph(r.collect(inline, style{}, bodySize, colorText), x, width) + inline = nil + } + } + + for _, n := range nodes { + switch n := n.(type) { + case *ast.Paragraph: + flush() + r.blocks(n.Children, x, width) + case *ast.Heading: + flush() + r.heading(n, x, width) + case *ast.List: + flush() + r.list(n, x, width) + case *ast.CodeBlock: + flush() + r.codeBlock(string(n.Literal), x, width) + case *ast.BlockQuote: + flush() + r.blockQuote(n, x, width) + case *ast.HorizontalRule: + flush() + r.ensureSpace(blockGap * 2) + r.y += blockGap + r.rule(x, x+width, r.y) + r.y += blockGap + case *ast.Table: + flush() + r.table(n, x, width) + case *ast.HTMLBlock: + flush() + default: + inline = append(inline, n) + } + } + flush() +} + +func (r *pdfRenderer) heading(h *ast.Heading, x, width float64) { + sizes := [...]float64{24, 20, 16, 14, 12, 11} + size := sizes[min(max(h.Level, 1), len(sizes))-1] + + r.y += size * 0.5 + toks := r.collect(h.Children, style{bold: true}, size, colorText) + lines := r.layout(toks, width) + r.ensureSpace(lines[0].height + blockGap) + r.drawLines(lines, x) + if h.Level <= 2 { + r.rule(x, x+width, r.y) + r.y += 2 + } + r.y += blockGap +} + +func (r *pdfRenderer) paragraph(toks []token, x, width float64) { + if len(toks) == 0 { + return + } + r.drawLines(r.layout(toks, width), x) + r.y += blockGap +} + +func (r *pdfRenderer) list(l *ast.List, x, width float64) { + ordered := l.ListFlags&ast.ListTypeOrdered != 0 + for i, item := range l.Children { + marker := "•" + if ordered { + marker = strconv.Itoa(i+1) + "." + } + + r.ensureSpace(bodySize * lineSpacing * 2) + r.drawText(marker, fontRegular, bodySize, colorText, x, r.y+bodySize*(lineSpacing-1)/2) + r.blocks(item.GetChildren(), x+listIndent, width-listIndent) + } +} + +func (r *pdfRenderer) blockQuote(q *ast.BlockQuote, x, width float64) { + startPage, startY := r.page, r.y + r.blocks(q.Children, x+quoteIndent, width-quoteIndent) + if r.page == startPage { + r.pdf.SetLineWidth(2) + r.pdf.SetStrokeColor(colorRule.r, colorRule.g, colorRule.b) + r.pdf.Line(x+2, startY, x+2, r.y-blockGap) + } +} + +func (r *pdfRenderer) codeBlock(code string, x, width float64) { + const pad = 4.0 + lineH := codeSize * lineSpacing + textW := width - 2*pad + + code = strings.ReplaceAll(strings.Trim(code, "\n"), "\t", tabWidth) + var rows []string + for _, src := range strings.Split(code, "\n") { + rows = append(rows, r.wrapChars(src, fontMono, codeSize, textW)...) + } + + r.pdf.SetFillColor(colorCode.r, colorCode.g, colorCode.b) + r.ensureSpace(pad + lineH) + r.fillRect(x, r.y, width, pad) + r.y += pad + for i, row := range rows { + extra := 0.0 + if i == len(rows)-1 { + extra = pad + } + r.ensureSpace(lineH + extra) + r.pdf.SetFillColor(colorCode.r, colorCode.g, colorCode.b) + r.fillRect(x, r.y, width, lineH+extra) + r.drawText(row, fontMono, codeSize, colorText, x+pad, r.y+(lineH-codeSize)/2) + r.y += lineH + } + r.y += pad + blockGap +} + +func (r *pdfRenderer) fillRect(x, y, w, h float64) { + r.pdf.RectFromUpperLeftWithStyle(x, y, w, h, "F") +} + +func (r *pdfRenderer) table(t *ast.Table, x, width float64) { + type row struct { + toks [][]token + cells [][]line + header bool + height float64 + } + + var rows []row + cols := 0 + var walk func(nodes []ast.Node, header bool) + walk = func(nodes []ast.Node, header bool) { + for _, n := range nodes { + switch n := n.(type) { + case *ast.TableHeader: + walk(n.Children, true) + case *ast.TableBody, *ast.TableFooter: + walk(n.GetChildren(), false) + case *ast.TableRow: + rw := row{header: header} + for _, cell := range n.Children { + rw.toks = append(rw.toks, r.collect(cell.GetChildren(), style{bold: header}, bodySize, colorText)) + } + rows = append(rows, rw) + cols = max(cols, len(n.Children)) + } + } + } + walk(t.Children, false) + if cols == 0 { + return + } + + // Size columns from their content: natural is the width on one line, minimum the longest word. + natural := make([]float64, cols) + minimum := make([]float64, cols) + for i := range natural { + natural[i], minimum[i] = 2*cellPadding, 2*cellPadding + } + for _, rw := range rows { + for ci, toks := range rw.toks { + var one float64 + for _, l := range r.layout(toks, 1e9) { + for _, tk := range l.tokens { + one += tk.space + tk.width + minimum[ci] = max(minimum[ci], tk.width+2*cellPadding) + } + } + natural[ci] = max(natural[ci], one+2*cellPadding) + } + } + colW := columnWidths(natural, minimum, width) + + for i := range rows { + rw := &rows[i] + rw.cells = make([][]line, len(rw.toks)) + for ci, toks := range rw.toks { + lines := r.layout(toks, colW[ci]-2*cellPadding) + rw.cells[ci] = lines + h := 0.0 + for _, l := range lines { + h += l.height + } + rw.height = max(rw.height, h+2*cellPadding) + } + } + + for _, rw := range rows { + r.ensureSpace(rw.height) + cx := x + for ci := 0; ci < cols; ci++ { + w := colW[ci] + if rw.header { + r.pdf.SetFillColor(colorCode.r, colorCode.g, colorCode.b) + r.fillRect(cx, r.y, w, rw.height) + } + r.pdf.SetStrokeColor(colorRule.r, colorRule.g, colorRule.b) + r.pdf.SetLineWidth(0.5) + r.pdf.RectFromUpperLeftWithStyle(cx, r.y, w, rw.height, "D") + + if ci < len(rw.cells) { + cellY := r.y + cellPadding + for _, l := range rw.cells[ci] { + r.drawLine(l, cx+cellPadding, cellY) + cellY += l.height + } + } + cx += w + } + r.y += rw.height + } + r.y += blockGap +} + +// columnWidths splits width between columns: each gets at least its minimum, and any +// remaining space goes to the columns that would otherwise wrap, in proportion to need. +func columnWidths(natural, minimum []float64, width float64) []float64 { + n := len(natural) + out := make([]float64, n) + + var sumNat, sumMin float64 + for i := range natural { + sumNat += natural[i] + sumMin += minimum[i] + } + + switch { + case sumNat <= width: + for i := range out { + out[i] = natural[i] * width / sumNat + } + case sumMin >= width: + for i := range out { + out[i] = width / float64(n) + } + default: + spare, need := width-sumMin, sumNat-sumMin + for i := range out { + out[i] = minimum[i] + spare*(natural[i]-minimum[i])/need + } + } + return out +} + +func (r *pdfRenderer) rule(x1, x2, y float64) { + r.pdf.SetLineWidth(0.5) + r.pdf.SetStrokeColor(colorRule.r, colorRule.g, colorRule.b) + r.pdf.Line(x1, y, x2, y) +} + +// collect flattens inline nodes into styled word tokens. +func (r *pdfRenderer) collect(nodes []ast.Node, st style, size float64, color rgb) []token { + c := &collector{size: size, color: color} + c.walk(nodes, st) + return c.tokens +} + +type collector struct { + tokens []token + size float64 + color rgb + pendingSpace bool +} + +func (c *collector) walk(nodes []ast.Node, st style) { + for _, n := range nodes { + switch n := n.(type) { + case *ast.Text: + c.text(string(n.Literal), st) + case *ast.Code: + s := st + s.mono = true + c.text(string(n.Literal), s) + case *ast.Emph: + s := st + s.italic = true + c.walk(n.Children, s) + case *ast.Strong: + s := st + s.bold = true + c.walk(n.Children, s) + case *ast.Del: + c.walk(n.Children, st) + case *ast.Link: + s := st + s.link = true + c.walk(n.Children, s) + case *ast.Image: + s := st + s.italic = true + c.text("[image:", s) + c.walk(n.Children, s) + c.text("]", s) + c.pendingSpace = false + case *ast.Softbreak: + c.pendingSpace = true + case *ast.Hardbreak: + c.tokens = append(c.tokens, token{lineBreak: true}) + c.pendingSpace = false + case *ast.HTMLSpan: + default: + c.walk(n.GetChildren(), st) + } + } +} + +func (c *collector) text(s string, st style) { + if s == "" { + return + } + family := fontRegular + switch { + case st.mono: + family = fontMono + case st.bold && st.italic: + family = fontBoldItal + case st.bold: + family = fontBold + case st.italic: + family = fontItalic + } + color := c.color + if st.link { + color = colorLink + } + + if unicode.IsSpace([]rune(s)[0]) { + c.pendingSpace = true + } + words := strings.Fields(s) + for i, w := range words { + c.tokens = append(c.tokens, token{ + text: w, + family: family, + size: c.size, + color: color, + spaceBefore: c.pendingSpace && len(c.tokens) > 0, + }) + // Words within one text run are always separated by whitespace. + c.pendingSpace = i < len(words)-1 + } + runes := []rune(s) + if unicode.IsSpace(runes[len(runes)-1]) { + c.pendingSpace = true + } +} + +// layout greedily wraps tokens into lines no wider than width. +func (r *pdfRenderer) layout(toks []token, width float64) []line { + var lines []line + var cur line + curW := 0.0 + + endLine := func() { + if cur.height == 0 { + cur.height = bodySize * lineSpacing + } + lines = append(lines, cur) + cur, curW = line{}, 0 + } + + for _, t := range toks { + if t.lineBreak { + endLine() + continue + } + + for _, piece := range r.fit(t, width) { + piece.width = r.measure(piece.family, piece.size, piece.text) + piece.space = 0 + if piece.spaceBefore && len(cur.tokens) > 0 { + piece.space = r.measure(piece.family, piece.size, " ") + } + if len(cur.tokens) > 0 && curW+piece.space+piece.width > width { + endLine() + piece.space = 0 + } + curW += piece.space + piece.width + cur.tokens = append(cur.tokens, piece) + cur.height = max(cur.height, piece.size*lineSpacing) + } + } + if len(cur.tokens) > 0 || len(lines) == 0 { + endLine() + } + return lines +} + +// fit splits a token wider than width into pieces that each fit. +func (r *pdfRenderer) fit(t token, width float64) []token { + if r.measure(t.family, t.size, t.text) <= width { + return []token{t} + } + + var out []token + for i, chunk := range r.wrapChars(t.text, t.family, t.size, width) { + piece := t + piece.text = chunk + piece.spaceBefore = t.spaceBefore && i == 0 + out = append(out, piece) + } + return out +} + +// wrapChars breaks text on character boundaries so each piece fits within width. +func (r *pdfRenderer) wrapChars(text, family string, size, width float64) []string { + if text == "" { + return []string{""} + } + + var out []string + var cur []rune + for _, ch := range text { + next := string(append(cur, ch)) + if len(cur) > 0 && r.measure(family, size, next) > width { + out = append(out, string(cur)) + cur = nil + } + cur = append(cur, ch) + } + return append(out, string(cur)) +} + +func (r *pdfRenderer) drawLines(lines []line, x float64) { + for _, l := range lines { + r.ensureSpace(l.height) + r.drawLine(l, x, r.y) + r.y += l.height + } +} + +func (r *pdfRenderer) drawLine(l line, x, y float64) { + for _, t := range l.tokens { + x += t.space + r.drawText(t.text, t.family, t.size, t.color, x, y+(l.height-t.size)/2) + x += t.width + } +} + +func (r *pdfRenderer) drawText(text, family string, size float64, color rgb, x, y float64) { + r.setFont(family, size) + r.pdf.SetTextColor(color.r, color.g, color.b) + // gopdf positions text by a point near the baseline rather than the top of the glyphs, + // so shift down to make y the top of a size-high box. + r.pdf.SetXY(x, y+size*baselineShift) + r.fail(r.pdf.Text(text)) +} diff --git a/internal/engine/html.go b/internal/engine/html.go new file mode 100644 index 0000000..5e48ada --- /dev/null +++ b/internal/engine/html.go @@ -0,0 +1,8 @@ +package engine + +import "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document" + +// markdownToHTML renders a complete HTML document for the browser based engines. +func markdownToHTML(md []byte) []byte { + return document.HTML(md) +} diff --git a/internal/engine/wkhtmltopdf.go b/internal/engine/wkhtmltopdf.go new file mode 100644 index 0000000..b557f41 --- /dev/null +++ b/internal/engine/wkhtmltopdf.go @@ -0,0 +1,95 @@ +package engine + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + + "github.com/SebastiaanKlippert/go-wkhtmltopdf" +) + +type wkhtmltopdfEngine struct { + pathOnce sync.Once + pathErr error +} + +func (e *wkhtmltopdfEngine) Name() string { return Wkhtmltopdf } + +func (e *wkhtmltopdfEngine) Close() error { return nil } + +func (e *wkhtmltopdfEngine) Render(md []byte, outputFile string) error { + e.pathOnce.Do(func() { e.pathErr = ensureWkhtmltopdfInPath() }) + if e.pathErr != nil { + return e.pathErr + } + + pdfg, err := wkhtmltopdf.NewPDFGenerator() + if err != nil { + return fmt.Errorf("failed to create PDF generator: %w", err) + } + + page := wkhtmltopdf.NewPageReader(strings.NewReader(string(markdownToHTML(md)))) + page.EnableLocalFileAccess.Set(true) + pdfg.AddPage(page) + + pdfg.Dpi.Set(300) + pdfg.MarginTop.Set(15) + pdfg.MarginBottom.Set(15) + pdfg.MarginLeft.Set(15) + pdfg.MarginRight.Set(15) + + if err := pdfg.Create(); err != nil { + return fmt.Errorf("failed to create PDF: %w", err) + } + if err := pdfg.WriteFile(outputFile); err != nil { + return fmt.Errorf("failed to write PDF file: %w", err) + } + return nil +} + +func ensureWkhtmltopdfInPath() error { + var wkhtmlPath string + + switch runtime.GOOS { + case "windows": + wkhtmlPath = `C:\Program Files\wkhtmltopdf\bin` + case "linux": + wkhtmlPath = findInDirs("wkhtmltopdf", "/usr/local/bin", "/usr/bin", "/opt/wkhtmltopdf/bin") + case "darwin": + wkhtmlPath = findInDirs("wkhtmltopdf", "/usr/local/bin", "/opt/homebrew/bin", "/opt/local/bin") + default: + return fmt.Errorf("unsupported operating system: %s", runtime.GOOS) + } + + if wkhtmlPath == "" { + return fmt.Errorf("wkhtmltopdf not found in common installation paths") + } + if _, err := os.Stat(wkhtmlPath); os.IsNotExist(err) { + return fmt.Errorf("wkhtmltopdf directory not found at: %s", wkhtmlPath) + } + + currentPath := os.Getenv("PATH") + if strings.Contains(currentPath, wkhtmlPath) { + return nil + } + + newPath := currentPath + string(os.PathListSeparator) + wkhtmlPath + if err := os.Setenv("PATH", newPath); err != nil { + return fmt.Errorf("failed to update PATH: %w", err) + } + + fmt.Printf("Added wkhtmltopdf to PATH: %s\n", wkhtmlPath) + return nil +} + +func findInDirs(binary string, dirs ...string) string { + for _, dir := range dirs { + if _, err := os.Stat(filepath.Join(dir, binary)); err == nil { + return dir + } + } + return "" +} diff --git a/main.go b/main.go deleted file mode 100644 index 60cad14..0000000 --- a/main.go +++ /dev/null @@ -1,331 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "flag" - "fmt" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "sync" - - "github.com/SebastiaanKlippert/go-wkhtmltopdf" - "github.com/gomarkdown/markdown" - "github.com/gomarkdown/markdown/parser" -) - -const ( - Windows = "windows" - Linux = "linux" - MacOS = "darwin" -) - -type Converter struct { - inputDir string - recursive bool - parallel bool - hookMode bool -} - -func init() { - if err := ensureWkhtmltopdfInPath(); err != nil { - fmt.Fprintf(os.Stderr, "Error setting up PATH: %v\n", err) - os.Exit(1) - } -} -func ensureWkhtmltopdfInPath() error { - var wkhtmlPath string - pathSeparator := string(os.PathListSeparator) - - switch runtime.GOOS { - case Windows: - wkhtmlPath = `C:\Program Files\wkhtmltopdf\bin` - case Linux: - // Common Linux installation paths - possiblePaths := []string{ - "/usr/local/bin", - "/usr/bin", - "/opt/wkhtmltopdf/bin", - } - - for _, path := range possiblePaths { - if _, err := os.Stat(filepath.Join(path, "wkhtmltopdf")); err == nil { - wkhtmlPath = path - break - } - } - case MacOS: - // Common MacOS installation paths - possiblePaths := []string{ - "/usr/local/bin", - "/opt/homebrew/bin", - "/opt/local/bin", - } - - for _, path := range possiblePaths { - if _, err := os.Stat(filepath.Join(path, "wkhtmltopdf")); err == nil { - wkhtmlPath = path - break - } - } - default: - return fmt.Errorf("unsupported operating system: %s", runtime.GOOS) - } - - if wkhtmlPath == "" { - return fmt.Errorf("wkhtmltopdf not found in common installation paths") - } - - // Check if the directory exists - if _, err := os.Stat(wkhtmlPath); os.IsNotExist(err) { - return fmt.Errorf("wkhtmltopdf directory not found at: %s", wkhtmlPath) - } - - // Get current PATH - currentPath := os.Getenv("PATH") - - // Check if the path is already in PATH - if strings.Contains(currentPath, wkhtmlPath) { - return nil // Already in PATH - } - - // Add to PATH using OS-specific path separator - newPath := currentPath + pathSeparator + wkhtmlPath - if err := os.Setenv("PATH", newPath); err != nil { - return fmt.Errorf("failed to update PATH: %w", err) - } - - fmt.Printf("Added wkhtmltopdf to PATH: %s\n", wkhtmlPath) - return nil -} - -// Add this helper function to get the executable name based on OS -func getExecutableName() string { - if runtime.GOOS == Windows { - return "wkhtmltopdf.exe" - } - return "wkhtmltopdf" -} - -func main() { - conv := &Converter{} - - // Parse command line flags - flag.StringVar(&conv.inputDir, "dir", ".", "Directory to scan for markdown files") - flag.BoolVar(&conv.recursive, "recursive", true, "Scan directories recursively") - flag.BoolVar(&conv.parallel, "parallel", true, "Convert files in parallel") - flag.BoolVar(&conv.hookMode, "hook", false, "Run as git pre-commit hook") - flag.Parse() - - if conv.hookMode { - if err := conv.runAsHook(); err != nil { - fmt.Fprintf(os.Stderr, "Hook error: %v\n", err) - os.Exit(1) - } - } else { - if err := conv.Run(); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) - } - } -} - -func (c *Converter) runAsHook() error { - // Ask user if they want to proceed - if !c.confirmConversion() { - fmt.Println("Skipping PDF conversion") - return nil - } - - // Get staged markdown files - files, err := c.getStagedMarkdownFiles() - if err != nil { - return fmt.Errorf("failed to get staged files: %w", err) - } - - if len(files) == 0 { - return nil - } - - // Convert files - if err := c.convertFiles(files); err != nil { - return err - } - - // Stage generated PDFs - return c.stageGeneratedPDFs(files) -} - -func (c *Converter) confirmConversion() bool { - fmt.Print("Convert Markdown files to PDF? [Y/n] ") - reader := bufio.NewReader(os.Stdin) - response, err := reader.ReadString('\n') - if err != nil { - return false - } - - response = strings.ToLower(strings.TrimSpace(response)) - return response == "" || response == "y" || response == "yes" -} - -func (c *Converter) getStagedMarkdownFiles() ([]string, error) { - cmd := exec.Command("git", "diff", "--cached", "--name-only", "--diff-filter=d") - output, err := cmd.Output() - if err != nil { - return nil, err - } - - var files []string - scanner := bufio.NewScanner(bytes.NewReader(output)) - for scanner.Scan() { - file := scanner.Text() - if strings.HasSuffix(file, ".md") || strings.HasSuffix(file, ".markdown") { - files = append(files, file) - } - } - - return files, scanner.Err() -} - -func (c *Converter) stageGeneratedPDFs(files []string) error { - for _, file := range files { - pdfFile := strings.TrimSuffix(file, filepath.Ext(file)) + ".pdf" - // Convert to OS-specific path - pdfFile = filepath.FromSlash(pdfFile) - cmd := exec.Command("git", "add", pdfFile) - if err := cmd.Run(); err != nil { - fmt.Printf("Warning: Could not stage %s\n", pdfFile) - } - } - return nil -} - -func (c *Converter) Run() error { - files, err := c.findMarkdownFiles() - if err != nil { - return fmt.Errorf("failed to find markdown files: %w", err) - } - - if len(files) == 0 { - fmt.Println("No markdown files found") - return nil - } - - return c.convertFiles(files) -} - -func (c *Converter) convertFiles(files []string) error { - if c.parallel { - return c.convertFilesParallel(files) - } - return c.convertFilesSerial(files) -} - -func (c *Converter) findMarkdownFiles() ([]string, error) { - var files []string - - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if info.IsDir() && !c.recursive && path != c.inputDir { - return filepath.SkipDir - } - - if !info.IsDir() && (strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".markdown")) { - files = append(files, path) - } - - return nil - } - - if err := filepath.Walk(c.inputDir, walkFn); err != nil { - return nil, err - } - - return files, nil -} - -func (c *Converter) convertFilesParallel(files []string) error { - var wg sync.WaitGroup - errors := make(chan error, len(files)) - - for _, file := range files { - wg.Add(1) - go func(f string) { - defer wg.Done() - if err := c.convertFile(f); err != nil { - errors <- fmt.Errorf("failed to convert %s: %w", f, err) - } - }(file) - } - - wg.Wait() - close(errors) - - for err := range errors { - if err != nil { - return err - } - } - - return nil -} - -func (c *Converter) convertFilesSerial(files []string) error { - for _, file := range files { - if err := c.convertFile(file); err != nil { - return fmt.Errorf("failed to convert %s: %w", file, err) - } - } - return nil -} - -func (c *Converter) convertFile(inputFile string) error { - mdContent, err := os.ReadFile(inputFile) - if err != nil { - return fmt.Errorf("failed to read file: %w", err) - } - - extensions := parser.CommonExtensions | parser.AutoHeadingIDs - p := parser.NewWithExtensions(extensions) - html := markdown.ToHTML(mdContent, p, nil) - - outputFile := strings.TrimSuffix(inputFile, filepath.Ext(inputFile)) + ".pdf" - - pdfg, err := wkhtmltopdf.NewPDFGenerator() - if err != nil { - if runtime.GOOS == Windows { - // Check if wkhtmltopdf exists in the expected path - expectedPath := filepath.Join(`C:\Program Files\wkhtmltopdf\bin`, "wkhtmltopdf.exe") - if _, err := os.Stat(expectedPath); os.IsNotExist(err) { - return fmt.Errorf("wkhtmltopdf not found at %s. Please ensure it's installed correctly", expectedPath) - } - } - return fmt.Errorf("failed to create PDF generator: %w", err) - } - page := wkhtmltopdf.NewPageReader(strings.NewReader(string(html))) - page.EnableLocalFileAccess.Set(true) - pdfg.AddPage(page) - - pdfg.Dpi.Set(300) - pdfg.MarginTop.Set(15) - pdfg.MarginBottom.Set(15) - pdfg.MarginLeft.Set(15) - pdfg.MarginRight.Set(15) - - if err := pdfg.Create(); err != nil { - return fmt.Errorf("failed to create PDF: %w", err) - } - - if err := pdfg.WriteFile(outputFile); err != nil { - return fmt.Errorf("failed to write PDF file: %w", err) - } - - fmt.Printf("Successfully converted %s to %s\n", inputFile, outputFile) - return nil -}