Compare commits

3 Commits
Author SHA1 Message Date
Hein b2d6ebd382 feat(Makefile): add release-version target for versioning
CI / Run Tests (push) Successful in 1m34s
2026-10-08 17:11:07 +02:00
Hein 5bf9c3673d feat: add DOCX/HTML output, go-tomd reverse converter, and input/output flags
- go-mdtopdf-helper: -format pdf,html,docx; new internal/document writers
  (standalone HTML, pure Go DOCX)
- new go-tomd command converting PDF/HTML/DOCX back to Markdown, skipping
  existing .md files unless -force
- -input/-output on both commands (single file with chosen name, or output
  directory mirroring the scan layout)
- restructure README and build config (Makefile, goreleaser) for both binaries
2026-10-08 17:05:01 +02:00
Hein 50b7246c21 feat(engine): add Chromedp and Wkhtmltopdf engines for PDF conversion
* implement gopdfEngine for direct PDF rendering
* create HTML rendering function for markdown
* add tests for engine functionality
* remove main.go as entry point
2026-10-08 16:42:47 +02:00
30 changed files with 3814 additions and 413 deletions

No files matched your search

+1 -1
View File
@@ -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: |
+3
View File
@@ -23,3 +23,6 @@ go.work.sum
# env file
.env
# Build output
/bin/
+18 -1
View File
@@ -14,10 +14,27 @@ 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}}
- id: go-tomd
env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm64
ignore:
- goos: windows
goarch: arm64
main: ./cmd/go-tomd
binary: go-tomd
ldflags:
- -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}}
archives:
- id: default
+58
View File
@@ -0,0 +1,58 @@
BINARY := go-mdtopdf-helper
TOMD_BINARY := go-tomd
BIN_DIR := bin
CMD := ./cmd/go-mdtopdf-helper
TOMD_CMD := ./cmd/go-tomd
.PHONY: all build run run-tomd test lint format clean release-version
all: format lint test build
build:
go build -o $(BIN_DIR)/$(BINARY) $(CMD)
go build -o $(BIN_DIR)/$(TOMD_BINARY) $(TOMD_CMD)
run:
go run $(CMD) $(ARGS)
run-tomd:
go run $(TOMD_CMD) $(ARGS)
test:
go test ./...
lint:
golangci-lint run ./...
format:
gofmt -s -w .
clean:
rm -rf $(BIN_DIR)
# Bump the latest vMAJOR.MINOR.PATCH tag and push the new tag, which triggers the release workflow.
# make release-version patch bump (v1.0.0 -> v1.0.1)
# make release-version BUMP=minor minor bump (v1.0.1 -> v1.1.0)
# make release-version BUMP=major major bump (v1.1.0 -> v2.0.0)
# make release-version DRY_RUN=1 show the next version without tagging or pushing
BUMP ?= patch
release-version:
@set -e; \
case "$(BUMP)" in patch|minor|major) ;; *) echo "BUMP must be patch, minor or major (got '$(BUMP)')" >&2; exit 1;; esac; \
git fetch --tags --quiet; \
latest=$$(git tag --list 'v*' --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -n1 || true); \
latest=$${latest:-v0.0.0}; \
ver=$${latest#v}; major=$${ver%%.*}; rest=$${ver#*.}; minor=$${rest%%.*}; patch=$${rest#*.}; \
case "$(BUMP)" in \
major) major=$$((major + 1)); minor=0; patch=0;; \
minor) minor=$$((minor + 1)); patch=0;; \
patch) patch=$$((patch + 1));; \
esac; \
next="v$$major.$$minor.$$patch"; \
echo "Latest tag: $$latest -> next: $$next"; \
if [ -n "$(DRY_RUN)" ]; then echo "Dry run: nothing tagged or pushed"; exit 0; fi; \
if [ -n "$$(git status --porcelain)" ]; then echo "Working tree is not clean; commit or stash first" >&2; exit 1; fi; \
if [ -n "$$(git rev-list '@{u}..HEAD' 2>/dev/null)" ]; then echo "HEAD has unpushed commits; push them first" >&2; exit 1; fi; \
git tag -a "$$next" -m "Release $$next"; \
git push origin "$$next"; \
echo "Pushed $$next"
+137 -35
View File
@@ -1,61 +1,89 @@
# 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.
Two command-line tools for keeping documentation in sync with your Markdown:
- **`go-mdtopdf-helper`** converts Markdown files to PDF, HTML or DOCX.
- **`go-tomd`** does the reverse, converting PDF, HTML and DOCX documents back to Markdown.
Perfect for maintaining PDF documentation alongside your Markdown files in Git repositories.
## Features
- Converts Markdown files to high-quality PDFs
- Markdown to PDF, HTML or DOCX, one or several formats at once
- Documents back to Markdown (`go-tomd`)
- Works out of the box: the default PDF engine, the DOCX writer and the DOCX reader are pure Go with no external dependencies
- Choice of PDF engines (pure Go, headless Chrome, or wkhtmltopdf)
- Convert a single file or scan a directory; choose where the output goes
- Can run as a Git pre-commit hook
- Recursive directory scanning
- Parallel file processing
- Recursive directory scanning and parallel processing
- Cross-platform support (Windows, Linux, macOS)
- Automatic detection of wkhtmltopdf installation
## Prerequisites
This tool requires [wkhtmltopdf](https://wkhtmltopdf.org/) to be installed on your system. The application will check for its presence in standard installation locations:
- Windows: `C:\Program Files\wkhtmltopdf\bin`
- Linux: `/usr/local/bin/wkhtmltopdf` or `/usr/bin/wkhtmltopdf`
- macOS: `/usr/local/bin/wkhtmltopdf` or via Homebrew
If wkhtmltopdf is not found, you will be prompted to install it.
## Installation
Download the archive for your platform from the project's GitHub releases. Each archive contains both `go-mdtopdf-helper` and `go-tomd`.
Or build from source (requires Go and, optionally, `golangci-lint` for `make lint`):
```bash
go get github.com/Warky-Devs/go-mdtopdf-helper
git clone https://github.com/Warky-Devs/go-mdtopdf-helper.git
cd go-mdtopdf-helper
make build # writes bin/go-mdtopdf-helper and bin/go-tomd
```
## Usage
## go-mdtopdf-helper: Markdown to PDF, HTML and DOCX
### Basic Usage
Convert Markdown files in the current directory:
Convert every Markdown file under the current directory to PDF:
```bash
go-mdtopdf-helper
```
### Command Line Options
### Options
```bash
```
go-mdtopdf-helper [options]
Options:
-dir string
Directory to scan for markdown files (default ".")
-input string
Convert only this markdown file (instead of scanning -dir)
-output string
With -input: output file name, extension added per format
Without -input: directory to write results to
-recursive
Scan directories recursively (default true)
-parallel
Convert files in parallel (default true)
-format string
Output formats, comma separated: pdf, html, docx (default "pdf")
-engine string
PDF engine: gopdf, wkhtmltopdf, chromedp (default "gopdf")
-hook
Run as git pre-commit hook
```
### Git Pre-commit Hook
### Output formats
To use as a Git pre-commit hook:
Select formats with `-format`, for example `-format pdf,html,docx`. By default each file is written next to its Markdown source with the matching extension (`README.md` becomes `README.pdf`, `README.html` and `README.docx`).
- **pdf**: rendered by the selected engine (see below). A4 with 15mm margins.
- **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.
### PDF engines
The engine only applies to PDF output. Select one 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). |
### Git pre-commit hook
To run it as a Git pre-commit hook:
1. Create a file named `pre-commit` in your repository's `.git/hooks/` directory
2. Add the following content:
@@ -74,16 +102,84 @@ chmod +x .git/hooks/pre-commit
When enabled as a pre-commit hook, the tool will:
1. Detect staged Markdown files
2. Ask for confirmation before conversion
3. Convert files to PDF
4. Automatically stage the generated PDFs
3. Convert the files to the formats given by `-format` (PDF by default)
4. Automatically stage every generated file
## PDF Output Configuration
To keep HTML or DOCX copies up to date as well, add the formats to the hook, for example `go-mdtopdf-helper -hook -format pdf,html`. The hook cannot be combined with `-input` or `-output`.
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
## go-tomd: documents to Markdown
`go-tomd` scans a directory for `.pdf`, `.html`/`.htm` and `.docx` files and writes `<name>.md` next to each one.
```bash
go-tomd
```
### Options
```
go-tomd [options]
Options:
-dir string
Directory to scan for documents (default ".")
-input string
Convert only this document (instead of scanning -dir); -format is ignored
-output string
With -input: Markdown file name to write (.md added if missing)
Without -input: directory to write results to
-recursive
Scan directories recursively (default true)
-parallel
Convert files in parallel (default true)
-format string
Input formats to convert, comma separated: docx, html, pdf (default "docx,html,pdf")
-force
Overwrite Markdown files that already exist
```
An existing `.md` is never overwritten unless you pass `-force`, so converting `doc.html` will not clobber a `doc.md` you wrote by hand. If several documents map to the same Markdown file (for example `doc.docx` and `doc.pdf`), one is chosen in the order docx, html, pdf and a warning is printed.
### How each format is read
| Input | How | Fidelity |
|-------|-----|----------|
| `docx` | Parsed directly (no Word needed). Headings, bold/italic/code, links, nested bulleted and numbered lists, code blocks, quotes, rules and tables. | High |
| `html` | [html-to-markdown](https://github.com/JohannesKaufmann/html-to-markdown), including tables and strikethrough. | High |
| `pdf` | Best effort, pure Go. PDFs have no real structure, so headings are inferred from font size, code from monospaced fonts, and lists from bullet or number prefixes. Tables and images are not recovered, and text in multi-column layouts may interleave. | Good on PDFs made by this tool, rougher on arbitrary ones |
## Input and output names
Both commands take `-input` and `-output`:
```bash
# Convert one file, choosing the output name (the extension is added per format)
go-mdtopdf-helper -input docs/guide.md -output build/manual -format pdf,html
# -> build/manual.pdf, build/manual.html
# Scan a directory but write results elsewhere, mirroring the folder layout
go-mdtopdf-helper -dir docs -output build
# And the reverse
go-tomd -input report.docx -output notes/report # -> notes/report.md
go-tomd -dir exports -output imported
```
- `-input` replaces the directory scan, so it cannot be combined with `-dir` or `-recursive` (or `-hook`). `go-mdtopdf-helper` expects a `.md`/`.markdown` file, and `go-tomd` a `.pdf`, `.html`/`.htm` or `.docx` file.
- With `-input`, `-output` is a file name. For `go-mdtopdf-helper` it is a base name that gets each format's extension; a name that already ends in the extension of the single requested format (`-output out.pdf -format pdf`) is used as is, and a mismatched extension is an error. For `go-tomd`, `.md` is added unless the name already ends in `.md` or `.markdown`.
- Without `-input`, `-output` is a directory, created if needed.
- Parent directories of the output are created automatically.
## Project layout
```
cmd/go-mdtopdf-helper/ Markdown to PDF/HTML/DOCX CLI (flags, hook mode)
cmd/go-tomd/ PDF/HTML/DOCX to Markdown CLI
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
internal/tomd/ PDF, HTML and DOCX readers (to Markdown)
```
## Contributing
@@ -95,7 +191,7 @@ Contributions are welcome! Please feel free to submit a Pull Request. Here's how
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
### Development Setup
### Development setup
1. Clone the repository
2. Install dependencies:
@@ -103,15 +199,21 @@ Contributions are welcome! Please feel free to submit a Pull Request. Here's how
go mod download
```
3. Make your changes
4. Run tests:
4. Run the checks:
```bash
go test ./...
make all
```
Make targets: `build` (both binaries into `bin/`), `run` and `run-tomd` (pass arguments with `ARGS="..."`), `test`, `lint` (golangci-lint), `format` (gofmt), `clean`, and `all` (format, lint, test, build). 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
- [pdf](https://github.com/ledongthuc/pdf) - Pure Go PDF text extraction (go-tomd)
- [html-to-markdown](https://github.com/JohannesKaufmann/html-to-markdown) - HTML to Markdown (go-tomd)
## License
BIN
View File
Binary file not shown.
+82
View File
@@ -0,0 +1,82 @@
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.StringVar(&conv.InputFile, "input", "",
"Convert only this markdown file (instead of scanning -dir)")
flag.StringVar(&conv.Output, "output", "",
"With -input: output file name, extension added per format (-output report -> report.pdf). "+
"Without -input: directory to write results to instead of next to the sources")
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()
set := map[string]bool{}
flag.Visit(func(f *flag.Flag) { set[f.Name] = true })
if conv.InputFile != "" && (set["dir"] || set["recursive"]) {
fmt.Fprintln(os.Stderr, "Error: -input cannot be combined with -dir or -recursive")
return 2
}
formats, err := converter.ParseFormats(formatList)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 2
}
conv.Formats = formats
if !hookMode {
if err := conv.Validate(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 2
}
}
// 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
}
+57
View File
@@ -0,0 +1,57 @@
// Command go-tomd converts PDF, HTML and DOCX documents to Markdown.
package main
import (
"flag"
"fmt"
"os"
"strings"
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/tomd"
)
func main() {
os.Exit(run())
}
func run() int {
r := &tomd.Runner{}
var formatList string
flag.StringVar(&r.InputDir, "dir", ".", "Directory to scan for documents")
flag.StringVar(&r.InputFile, "input", "",
"Convert only this document (instead of scanning -dir); -format is ignored")
flag.StringVar(&r.Output, "output", "",
"With -input: Markdown file name to write (.md added if missing). "+
"Without -input: directory to write results to instead of next to the sources")
flag.BoolVar(&r.Recursive, "recursive", true, "Scan directories recursively")
flag.BoolVar(&r.Parallel, "parallel", true, "Convert files in parallel")
flag.BoolVar(&r.Force, "force", false, "Overwrite Markdown files that already exist")
flag.StringVar(&formatList, "format", strings.Join(tomd.FormatNames, ","),
"Input formats to convert, comma separated: "+strings.Join(tomd.FormatNames, ", "))
flag.Parse()
set := map[string]bool{}
flag.Visit(func(f *flag.Flag) { set[f.Name] = true })
if r.InputFile != "" && (set["dir"] || set["recursive"]) {
fmt.Fprintln(os.Stderr, "Error: -input cannot be combined with -dir or -recursive")
return 2
}
formats, err := tomd.ParseFormats(formatList)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 2
}
r.Formats = formats
if err := r.Validate(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 2
}
if err := r.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
return 0
}
-44
View File
@@ -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")
}
}
+15 -1
View File
@@ -1,8 +1,22 @@
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/JohannesKaufmann/dom v0.3.1 // indirect
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 // indirect
github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875 // indirect
github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0 // indirect
github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311 // indirect
github.com/pkg/errors v0.8.1 // indirect
golang.org/x/net v0.55.0 // indirect
)
+22
View File
@@ -1,12 +1,34 @@
github.com/JohannesKaufmann/dom v0.3.1 h1:J16l9JAHWgkFPR3VIPbQ1gvS0cWab6laK1q7PFL3qh0=
github.com/JohannesKaufmann/dom v0.3.1/go.mod h1:BZPkf8ZeYrBgABjwJn9iiKt8aiCtkxpHkevms+Yp2DE=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 h1:XFJZFWESIWlUEHHjzBuv8RvrtCWnSGlimEX17ysSDb8=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2/go.mod h1:BHWO8lJzttJLqwuV8Rb1B3OG2OSzLbssZDI1FRg2eAA=
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/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0 h1:7Q+xNAZFmnfYOMweHN3c/PDFUKKfY1pVJ26K++QvVfU=
github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0/go.mod h1:1fEHWurg7pvf5SG6XNE5Q8UZmOwex51Mkx3SLhrW5B4=
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=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+266
View File
@@ -0,0 +1,266 @@
// 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.
//
// When InputFile is set only that file is converted and Output, if given, is the output name:
// a base name that gets the format's extension (or a full name when it already has the extension
// of the single requested format). Otherwise Output, if given, is a directory that receives the
// results, mirroring the layout under InputDir. With neither, output goes next to each source.
type Converter struct {
InputDir string
Recursive bool
Parallel bool
InputFile string
Output string
Formats []string
Engine engine.Engine
}
func (c *Converter) formats() []string {
if len(c.Formats) == 0 {
return []string{FormatPDF}
}
return c.Formats
}
// Validate checks the input and output options before any work is done.
func (c *Converter) Validate() error {
if c.InputFile != "" {
info, err := os.Stat(c.InputFile)
if err != nil {
return fmt.Errorf("input file: %w", err)
}
if info.IsDir() {
return fmt.Errorf("input %s is a directory; use -dir to scan a directory", c.InputFile)
}
if !isMarkdown(c.InputFile) {
return fmt.Errorf("input %s must be a .md or .markdown file", c.InputFile)
}
}
if c.Output == "" {
return nil
}
if c.InputFile == "" {
if info, err := os.Stat(c.Output); err == nil && !info.IsDir() {
return fmt.Errorf("output %s exists and is not a directory", c.Output)
}
return nil
}
if info, err := os.Stat(c.Output); err == nil && info.IsDir() {
return fmt.Errorf("output %s is a directory; give a file name when using -input", c.Output)
}
if ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(c.Output)), "."); slices.Contains(FormatNames, ext) {
if formats := c.formats(); len(formats) != 1 || formats[0] != ext {
return fmt.Errorf("output %s has a .%s extension but the requested formats are %s",
c.Output, ext, strings.Join(formats, ","))
}
}
return nil
}
// outputFor returns the file written for input in the given format.
func (c *Converter) outputFor(input, format string) string {
switch {
case c.InputFile != "" && c.Output != "":
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(c.Output)), ".")
if ext == format {
return c.Output
}
return c.Output + "." + format
case c.InputFile == "" && c.Output != "":
rel, err := filepath.Rel(c.InputDir, input)
if err != nil {
rel = filepath.Base(input)
}
return filepath.Join(c.Output, replaceExt(rel, format))
default:
return replaceExt(input, format)
}
}
func replaceExt(path, ext string) string {
return strings.TrimSuffix(path, filepath.Ext(path)) + "." + ext
}
// Run converts InputFile, or every Markdown file under InputDir.
func (c *Converter) Run() error {
if err := c.Validate(); err != nil {
return err
}
files, err := c.inputFiles()
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) inputFiles() ([]string, error) {
if c.InputFile != "" {
return []string{c.InputFile}, nil
}
return c.findMarkdownFiles()
}
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)
}
for _, format := range c.formats() {
outputFile := c.outputFor(inputFile, format)
if err := os.MkdirAll(filepath.Dir(outputFile), 0o755); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
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)
}
}
+203
View File
@@ -0,0 +1,203 @@
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")
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func TestInputFileWithOutputName(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "a.md"), "# A")
writeFile(t, filepath.Join(dir, "b.md"), "# B")
conv := &Converter{
InputFile: filepath.Join(dir, "a.md"),
Output: filepath.Join(dir, "out", "report"),
Formats: []string{FormatHTML, FormatDOCX},
}
if err := conv.Run(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"out/report.html", "out/report.docx"} {
if !exists(filepath.Join(dir, want)) {
t.Errorf("expected %s", want)
}
}
if exists(filepath.Join(dir, "b.html")) || exists(filepath.Join(dir, "a.html")) {
t.Error("only the output name should be written, and only the input file converted")
}
}
func TestInputFileOutputWithMatchingExtension(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "a.md"), "# A")
conv := &Converter{InputFile: filepath.Join(dir, "a.md"), Output: filepath.Join(dir, "x.html"), Formats: []string{FormatHTML}}
if err := conv.Run(); err != nil {
t.Fatal(err)
}
if !exists(filepath.Join(dir, "x.html")) || exists(filepath.Join(dir, "x.html.html")) {
t.Error("an output name that already has the format's extension should be used as is")
}
}
func TestOutputValidation(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "a.md"), "# A")
writeFile(t, filepath.Join(dir, "notes.txt"), "text")
md := filepath.Join(dir, "a.md")
cases := map[string]*Converter{
"missing input": {InputFile: filepath.Join(dir, "nope.md")},
"input is a dir": {InputFile: dir},
"input not markdown": {InputFile: filepath.Join(dir, "notes.txt")},
"output is a dir": {InputFile: md, Output: dir},
"extension mismatch": {InputFile: md, Output: filepath.Join(dir, "x.docx"), Formats: []string{FormatHTML}},
"ext with many fmts": {InputFile: md, Output: filepath.Join(dir, "x.html"), Formats: []string{FormatHTML, FormatDOCX}},
"scan output is file": {InputDir: dir, Output: md},
}
for name, c := range cases {
if err := c.Validate(); err == nil {
t.Errorf("%s: expected a validation error", name)
}
}
}
func TestOutputDirMirrorsLayout(t *testing.T) {
src, out := t.TempDir(), filepath.Join(t.TempDir(), "dist")
writeFile(t, filepath.Join(src, "a.md"), "# A")
writeFile(t, filepath.Join(src, "sub", "b.md"), "# B")
conv := &Converter{InputDir: src, Recursive: true, Output: out, Formats: []string{FormatHTML}}
if err := conv.Run(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"a.html", "sub/b.html"} {
if !exists(filepath.Join(out, want)) {
t.Errorf("expected %s in output dir", want)
}
}
if exists(filepath.Join(src, "a.html")) {
t.Error("nothing should be written next to the sources when -output is a directory")
}
}
func TestHookRejectsInputAndOutput(t *testing.T) {
if err := (&Converter{InputFile: "a.md"}).RunAsHook(); err == nil {
t.Error("expected error combining hook with -input")
}
}
+80
View File
@@ -0,0 +1,80 @@
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 c.InputFile != "" || c.Output != "" {
return fmt.Errorf("-input and -output cannot be combined with -hook")
}
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 {
for _, file := range files {
for _, format := range c.formats() {
out := filepath.FromSlash(c.outputFor(file, format))
if err := exec.Command("git", "add", out).Run(); err != nil {
fmt.Printf("Warning: Could not stage %s\n", out)
}
}
}
return nil
}
+73
View File
@@ -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{"<!DOCTYPE html>", "<style>", `<h1 id="title">Title</h1>`, "<strong>bold</strong>", "</html>"} {
if !strings.Contains(out, want) {
t.Errorf("HTML output missing %q", want)
}
}
}
func TestDOCX(t *testing.T) {
data, err := DOCX([]byte(sample))
if err != nil {
t.Fatal(err)
}
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("not a valid zip: %v", err)
}
parts := map[string]string{}
for _, f := range zr.File {
rc, err := f.Open()
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(rc)
_ = rc.Close()
// Every part must be well-formed XML or Word will refuse the file.
dec := xml.NewDecoder(bytes.NewReader(b))
for {
if _, err := dec.Token(); err == io.EOF {
break
} else if err != nil {
t.Fatalf("%s is not well-formed XML: %v", f.Name, err)
}
}
parts[f.Name] = string(b)
}
for _, name := range []string{"[Content_Types].xml", "_rels/.rels", "word/document.xml", "word/styles.xml",
"word/numbering.xml", "word/_rels/document.xml.rels"} {
if _, ok := parts[name]; !ok {
t.Errorf("missing part %s", name)
}
}
doc := parts["word/document.xml"]
for _, want := range []string{`w:val="Heading1"`, "<w:b/>", "<w:i/>", "Courier New", "w:numPr", "code in item", "<w:tbl>", `w:val="Quote"`} {
if !strings.Contains(doc, want) {
t.Errorf("document.xml missing %q", want)
}
}
if !strings.Contains(parts["word/_rels/document.xml.rels"], "http://example.com/?a=1&amp;b=2") {
t.Error("hyperlink target missing or not escaped")
}
}
+381
View File
@@ -0,0 +1,381 @@
package document
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"strings"
"github.com/gomarkdown/markdown/ast"
)
const (
nsMain = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
nsRel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
nsPkg = "http://schemas.openxmlformats.org/package/2006/relationships"
relStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
relNumbering = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"
relHyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
relDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
bulletNumID = 1
maxListLvl = 8
)
// DOCX renders Markdown as a Word document (.docx). It is built directly as zipped OOXML.
func DOCX(md []byte) ([]byte, error) {
b := &docxBuilder{nextNum: bulletNumID + 1}
b.blocks(NewParser().Parse(md).GetChildren(), blockCtx{})
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
parts := []struct{ name, data string }{
{"[Content_Types].xml", contentTypesXML},
{"_rels/.rels", rootRelsXML},
{"word/document.xml", b.documentXML()},
{"word/styles.xml", stylesXML},
{"word/numbering.xml", b.numberingXML()},
{"word/_rels/document.xml.rels", b.documentRelsXML()},
}
for _, p := range parts {
w, err := zw.Create(p.name)
if err != nil {
return nil, fmt.Errorf("failed to write docx part %s: %w", p.name, err)
}
if _, err := w.Write([]byte(xml.Header + p.data)); err != nil {
return nil, fmt.Errorf("failed to write docx part %s: %w", p.name, err)
}
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("failed to finish docx: %w", err)
}
return buf.Bytes(), nil
}
// blockCtx carries the list and quote nesting while walking block nodes.
type blockCtx struct {
listLevel int // 0 when not in a list, otherwise the nesting depth (1-based)
numID int // numbering instance of the enclosing list
quote bool
// bullet holds a list item's marker until the first paragraph consumes it.
bullet *bool
}
type docxBuilder struct {
body strings.Builder
links []string // hyperlink targets, relationship ids are rId10+index
ordered []int // numbering ids created for ordered lists
nextNum int
}
func (b *docxBuilder) blocks(nodes []ast.Node, ctx blockCtx) {
var inline []ast.Node
flush := func() {
if len(inline) > 0 {
b.paragraph(b.runs(inline, runStyle{}), ctx)
inline = nil
}
}
for _, n := range nodes {
switch n := n.(type) {
case *ast.Paragraph:
flush()
// gomarkdown nests fenced code blocks and lists inside paragraphs.
b.blocks(n.Children, ctx)
case *ast.Heading:
flush()
level := min(max(n.Level, 1), 6)
fmt.Fprintf(&b.body, `<w:p><w:pPr><w:pStyle w:val="Heading%d"/></w:pPr>%s</w:p>`,
level, b.runs(n.Children, runStyle{}))
case *ast.List:
flush()
b.list(n, ctx)
case *ast.CodeBlock:
flush()
b.codeBlock(string(n.Literal), ctx)
case *ast.BlockQuote:
flush()
q := ctx
q.quote = true
b.blocks(n.Children, q)
case *ast.HorizontalRule:
flush()
b.body.WriteString(`<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="CCCCCC"/></w:pBdr></w:pPr></w:p>`)
case *ast.Table:
flush()
b.table(n)
case *ast.HTMLBlock:
flush()
default:
inline = append(inline, n)
}
}
flush()
}
// paragraph writes runs as one paragraph, applying list and quote formatting from ctx.
func (b *docxBuilder) paragraph(runs string, ctx blockCtx) {
if runs == "" {
return
}
var ppr string
switch {
case ctx.listLevel > 0 && ctx.bullet != nil && *ctx.bullet:
*ctx.bullet = false
ppr = fmt.Sprintf(`<w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="%d"/><w:numId w:val="%d"/></w:numPr>`,
min(ctx.listLevel-1, maxListLvl), ctx.numID)
case ctx.listLevel > 0:
ppr = fmt.Sprintf(`<w:ind w:left="%d"/>`, 360*ctx.listLevel+360)
case ctx.quote:
ppr = `<w:pStyle w:val="Quote"/>`
}
if ppr != "" {
ppr = "<w:pPr>" + ppr + "</w:pPr>"
}
b.body.WriteString("<w:p>" + ppr + runs + "</w:p>")
}
func (b *docxBuilder) list(l *ast.List, ctx blockCtx) {
numID := bulletNumID
if l.ListFlags&ast.ListTypeOrdered != 0 {
numID = b.nextNum
b.nextNum++
b.ordered = append(b.ordered, numID)
}
for _, item := range l.Children {
marker := true
inner := ctx
inner.listLevel++
inner.numID = numID
inner.bullet = &marker
b.blocks(item.GetChildren(), inner)
}
}
func (b *docxBuilder) codeBlock(code string, ctx blockCtx) {
indent := ""
if ctx.listLevel > 0 {
indent = fmt.Sprintf(`<w:ind w:left="%d"/>`, 360*ctx.listLevel+360)
}
code = strings.Trim(code, "\n")
lines := strings.Split(code, "\n")
for i, line := range lines {
spacing := ""
if i == len(lines)-1 {
spacing = `<w:spacing w:after="160"/>`
}
b.body.WriteString(`<w:p><w:pPr><w:pStyle w:val="Code"/>` + spacing + indent + `</w:pPr>`)
b.body.WriteString(`<w:r><w:t xml:space="preserve">` + escape(strings.ReplaceAll(line, "\t", " ")) + `</w:t></w:r></w:p>`)
}
}
func (b *docxBuilder) table(t *ast.Table) {
b.body.WriteString(`<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="pct"/><w:tblBorders>`)
for _, edge := range []string{"top", "left", "bottom", "right", "insideH", "insideV"} {
fmt.Fprintf(&b.body, `<w:%s w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>`, edge)
}
b.body.WriteString(`</w:tblBorders><w:tblCellMar><w:left w:w="100" w:type="dxa"/><w:right w:w="100" w:type="dxa"/></w:tblCellMar></w:tblPr>`)
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:
b.tableRow(n, header)
}
}
}
walk(t.Children, false)
// Word requires a paragraph after a table, and it also separates it from what follows.
b.body.WriteString(`</w:tbl><w:p/>`)
}
func (b *docxBuilder) tableRow(row *ast.TableRow, header bool) {
b.body.WriteString("<w:tr>")
for _, cell := range row.Children {
tcPr := ""
if header {
tcPr = `<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="F4F4F4"/></w:tcPr>`
}
runs := b.runs(cell.GetChildren(), runStyle{bold: header})
b.body.WriteString("<w:tc>" + tcPr + "<w:p>" + runs + "</w:p></w:tc>")
}
b.body.WriteString("</w:tr>")
}
// runStyle describes the inline formatting in effect.
type runStyle struct {
bold, italic, code bool
link bool
}
func (b *docxBuilder) runs(nodes []ast.Node, st runStyle) string {
var out strings.Builder
for _, n := range nodes {
switch n := n.(type) {
case *ast.Text:
out.WriteString(textRun(string(n.Literal), st))
case *ast.Code:
s := st
s.code = true
out.WriteString(textRun(string(n.Literal), s))
case *ast.Emph:
s := st
s.italic = true
out.WriteString(b.runs(n.Children, s))
case *ast.Strong:
s := st
s.bold = true
out.WriteString(b.runs(n.Children, s))
case *ast.Del:
out.WriteString(b.runs(n.Children, st))
case *ast.Link:
s := st
s.link = true
inner := b.runs(n.Children, s)
if dest := string(n.Destination); dest != "" {
b.links = append(b.links, dest)
inner = fmt.Sprintf(`<w:hyperlink r:id="rId%d" w:history="1">%s</w:hyperlink>`, linkRelBase+len(b.links)-1, inner)
}
out.WriteString(inner)
case *ast.Image:
s := st
s.italic = true
out.WriteString(textRun("[image: ", s) + b.runs(n.Children, s) + textRun("]", s))
case *ast.Softbreak:
out.WriteString(textRun(" ", st))
case *ast.Hardbreak:
out.WriteString(`<w:r><w:br/></w:r>`)
case *ast.HTMLSpan:
default:
out.WriteString(b.runs(n.GetChildren(), st))
}
}
return out.String()
}
func textRun(text string, st runStyle) string {
if text == "" {
return ""
}
var props string
if st.code {
props += `<w:rFonts w:ascii="Courier New" w:hAnsi="Courier New" w:cs="Courier New"/>`
}
if st.bold {
props += `<w:b/>`
}
if st.italic {
props += `<w:i/>`
}
if st.link {
props += `<w:color w:val="0000EE"/><w:u w:val="single"/>`
}
if props != "" {
props = "<w:rPr>" + props + "</w:rPr>"
}
text = strings.NewReplacer("\r", "", "\n", " ").Replace(text)
return `<w:r>` + props + `<w:t xml:space="preserve">` + escape(text) + `</w:t></w:r>`
}
func escape(s string) string {
var buf bytes.Buffer
_ = xml.EscapeText(&buf, []byte(s))
return buf.String()
}
// linkRelBase is the first relationship id used for hyperlinks; lower ids are fixed parts.
const linkRelBase = 10
func (b *docxBuilder) documentXML() string {
return fmt.Sprintf(`<w:document xmlns:w="%s" xmlns:r="%s"><w:body>%s<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>`+
`<w:pgMar w:top="851" w:right="851" w:bottom="851" w:left="851" w:header="708" w:footer="708" w:gutter="0"/></w:sectPr></w:body></w:document>`,
nsMain, nsRel, b.body.String())
}
func (b *docxBuilder) documentRelsXML() string {
var s strings.Builder
fmt.Fprintf(&s, `<Relationships xmlns="%s">`, nsPkg)
fmt.Fprintf(&s, `<Relationship Id="rId1" Type="%s" Target="styles.xml"/>`, relStyles)
fmt.Fprintf(&s, `<Relationship Id="rId2" Type="%s" Target="numbering.xml"/>`, relNumbering)
for i, target := range b.links {
fmt.Fprintf(&s, `<Relationship Id="rId%d" Type="%s" Target="%s" TargetMode="External"/>`,
linkRelBase+i, relHyperlink, escape(target))
}
s.WriteString(`</Relationships>`)
return s.String()
}
// numberingXML defines one bullet list and one decimal list, each with nine indent levels.
// Every ordered list gets its own instance so numbering restarts at 1.
func (b *docxBuilder) numberingXML() string {
level := func(i int, format, text string) string {
return fmt.Sprintf(`<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="%s"/><w:lvlText w:val="%s"/>`+
`<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="%d" w:hanging="360"/></w:pPr></w:lvl>`,
i, format, text, 720*(i+1))
}
var bullets, decimals strings.Builder
for i := 0; i <= maxListLvl; i++ {
bullets.WriteString(level(i, "bullet", "•"))
decimals.WriteString(level(i, "decimal", fmt.Sprintf("%%%d.", i+1)))
}
var s strings.Builder
fmt.Fprintf(&s, `<w:numbering xmlns:w="%s">`, nsMain)
s.WriteString(`<w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>` + bullets.String() + `</w:abstractNum>`)
s.WriteString(`<w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>` + decimals.String() + `</w:abstractNum>`)
fmt.Fprintf(&s, `<w:num w:numId="%d"><w:abstractNumId w:val="0"/></w:num>`, bulletNumID)
for _, id := range b.ordered {
fmt.Fprintf(&s, `<w:num w:numId="%d"><w:abstractNumId w:val="1"/>`+
`<w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride></w:num>`, id)
}
s.WriteString(`</w:numbering>`)
return s.String()
}
const contentTypesXML = `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
`<Default Extension="xml" ContentType="application/xml"/>` +
`<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>` +
`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>` +
`<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>` +
`</Types>`
const rootRelsXML = `<Relationships xmlns="` + nsPkg + `">` +
`<Relationship Id="rId1" Type="` + relDocument + `" Target="word/document.xml"/>` +
`</Relationships>`
func headingStyle(level, halfPoints int) string {
return fmt.Sprintf(`<w:style w:type="paragraph" w:styleId="Heading%d"><w:name w:val="heading %d"/><w:basedOn w:val="Normal"/>`+
`<w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="120"/><w:outlineLvl w:val="%d"/></w:pPr>`+
`<w:rPr><w:b/><w:sz w:val="%d"/></w:rPr></w:style>`, level, level, level-1, halfPoints)
}
var stylesXML = `<w:styles xmlns:w="` + nsMain + `">` +
`<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:cs="Calibri"/><w:sz w:val="22"/></w:rPr></w:rPrDefault>` +
`<w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` +
`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>` +
headingStyle(1, 48) + headingStyle(2, 40) + headingStyle(3, 32) +
headingStyle(4, 28) + headingStyle(5, 24) + headingStyle(6, 22) +
`<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:spacing w:after="60"/><w:ind w:left="720"/></w:pPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="CCCCCC"/></w:pBdr><w:ind w:left="360"/></w:pPr>` +
`<w:rPr><w:color w:val="555555"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:shd w:val="clear" w:color="auto" w:fill="F4F4F4"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>` +
`<w:rPr><w:rFonts w:ascii="Courier New" w:hAnsi="Courier New" w:cs="Courier New"/><w:sz w:val="18"/></w:rPr></w:style>` +
`</w:styles>`
+40
View File
@@ -0,0 +1,40 @@
// Package document renders Markdown into document formats that need no external tools.
package document
import (
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/parser"
)
const htmlHead = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: sans-serif; line-height: 1.5; color: #222; }
pre { background: #f4f4f4; padding: 8px; overflow-x: auto; }
code { font-family: monospace; }
blockquote { border-left: 3px solid #ccc; margin-left: 0; padding-left: 12px; color: #555; }
table { border-collapse: collapse; }
th, td { border: 1px solid #ccc; padding: 4px 8px; }
img { max-width: 100%; }
</style>
</head>
<body>
`
const htmlFoot = "\n</body>\n</html>\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...)
}
+100
View File
@@ -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
}
+43
View File
@@ -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, ", "))
}
}
+79
View File
@@ -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")
}
+599
View File
@@ -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))
}
+8
View File
@@ -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)
}
+95
View File
@@ -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 ""
}
+426
View File
@@ -0,0 +1,426 @@
package tomd
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"io"
"regexp"
"strconv"
"strings"
)
// node is a namespace-less XML element, enough to walk WordprocessingML.
type node struct {
name string
attrs map[string]string
children []*node
text string
}
func parseXML(data []byte) (*node, error) {
dec := xml.NewDecoder(bytes.NewReader(data))
root := &node{}
stack := []*node{root}
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
switch t := tok.(type) {
case xml.StartElement:
n := &node{name: t.Name.Local, attrs: map[string]string{}}
for _, a := range t.Attr {
n.attrs[a.Name.Local] = a.Value
}
parent := stack[len(stack)-1]
parent.children = append(parent.children, n)
stack = append(stack, n)
case xml.EndElement:
stack = stack[:len(stack)-1]
case xml.CharData:
stack[len(stack)-1].text += string(t)
}
}
return root, nil
}
func (n *node) child(name string) *node {
if n == nil {
return nil
}
for _, c := range n.children {
if c.name == name {
return c
}
}
return nil
}
func (n *node) attr(name string) string {
if n == nil {
return ""
}
return n.attrs[name]
}
// docxDoc holds what is needed from the package to interpret the body.
type docxDoc struct {
styles map[string]string // styleId -> lower-cased style name
listKinds map[string]bool // "numId:ilvl" -> ordered
links map[string]string // relationship id -> target
}
// DOCX converts a Word document to Markdown.
func DOCX(data []byte) ([]byte, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, fmt.Errorf("not a valid docx file: %w", err)
}
parts := map[string][]byte{}
for _, f := range zr.File {
switch f.Name {
case "word/document.xml", "word/styles.xml", "word/numbering.xml", "word/_rels/document.xml.rels":
rc, err := f.Open()
if err != nil {
return nil, err
}
b, err := io.ReadAll(rc)
_ = rc.Close()
if err != nil {
return nil, err
}
parts[f.Name] = b
}
}
if parts["word/document.xml"] == nil {
return nil, fmt.Errorf("docx has no word/document.xml")
}
doc := &docxDoc{styles: map[string]string{}, listKinds: map[string]bool{}, links: map[string]string{}}
doc.loadStyles(parts["word/styles.xml"])
doc.loadNumbering(parts["word/numbering.xml"])
doc.loadLinks(parts["word/_rels/document.xml.rels"])
root, err := parseXML(parts["word/document.xml"])
if err != nil {
return nil, fmt.Errorf("failed to parse document.xml: %w", err)
}
w := &mdWriter{}
w.body(doc, root.child("document").child("body"))
return []byte(w.String()), nil
}
func (d *docxDoc) loadStyles(data []byte) {
root, err := parseXML(data)
if err != nil {
return
}
for _, s := range root.child("styles").children {
if s.name == "style" {
d.styles[s.attr("styleId")] = strings.ToLower(s.child("name").attr("val"))
}
}
}
func (d *docxDoc) loadNumbering(data []byte) {
root, err := parseXML(data)
if err != nil {
return
}
// abstractNumId -> level -> ordered
abstract := map[string]map[string]bool{}
var nums []*node
for _, n := range root.child("numbering").children {
switch n.name {
case "abstractNum":
levels := map[string]bool{}
for _, lvl := range n.children {
if lvl.name == "lvl" {
levels[lvl.attr("ilvl")] = lvl.child("numFmt").attr("val") != "bullet"
}
}
abstract[n.attr("abstractNumId")] = levels
case "num":
nums = append(nums, n)
}
}
for _, n := range nums {
for lvl, ordered := range abstract[n.child("abstractNumId").attr("val")] {
d.listKinds[n.attr("numId")+":"+lvl] = ordered
}
}
}
func (d *docxDoc) loadLinks(data []byte) {
root, err := parseXML(data)
if err != nil {
return
}
for _, r := range root.child("Relationships").children {
if r.attr("TargetMode") == "External" {
d.links[r.attr("Id")] = r.attr("Target")
}
}
}
var headingStyle = regexp.MustCompile(`^heading (\d)$`)
type paraKind int
const (
kindParagraph paraKind = iota
kindHeading
kindList
kindCode
kindQuote
kindRule
)
// mdWriter assembles blocks, keeping consecutive code lines and list items together.
type mdBlock struct {
kind paraKind
text string
}
type mdWriter struct {
blocks []mdBlock
last paraKind
// code and list blocks grow as consecutive paragraphs arrive.
open bool
}
func (w *mdWriter) String() string {
texts := make([]string, len(w.blocks))
for i, b := range w.blocks {
texts[i] = b.text
if b.kind == kindCode {
texts[i] = "```\n" + b.text + "\n```"
}
}
return strings.TrimSpace(strings.Join(texts, "\n\n")) + "\n"
}
func (w *mdWriter) add(kind paraKind, text string) {
w.blocks = append(w.blocks, mdBlock{kind, text})
w.last, w.open = kind, kind == kindCode || kind == kindList
}
// extend appends to the previous block when it is of the same grouped kind.
func (w *mdWriter) extend(kind paraKind, text, sep string) {
if w.open && w.last == kind {
w.blocks[len(w.blocks)-1].text += sep + text
return
}
w.add(kind, text)
}
func (w *mdWriter) body(d *docxDoc, body *node) {
if body == nil {
return
}
for _, n := range body.children {
switch n.name {
case "p":
w.paragraph(d, n)
case "tbl":
if t := d.table(n); t != "" {
w.add(kindParagraph, t)
}
}
}
}
func (w *mdWriter) paragraph(d *docxDoc, p *node) {
ppr := p.child("pPr")
styleID := ppr.child("pStyle").attr("val")
style := d.styles[styleID]
if style == "" {
style = strings.ToLower(styleID)
}
segs := d.runs(p)
text := strings.TrimSpace(renderSegs(segs))
plain := plainText(segs)
switch {
case ppr.child("pBdr").child("bottom") != nil && plain == "":
w.add(kindRule, "---")
case isCodeStyle(style):
w.extend(kindCode, plain, "\n")
case plain == "":
w.open = false
default:
if m := headingStyle.FindStringSubmatch(style); m != nil {
level, _ := strconv.Atoi(m[1])
w.add(kindHeading, strings.Repeat("#", min(max(level, 1), 6))+" "+collapseSpace(text))
} else if style == "title" {
w.add(kindHeading, "# "+collapseSpace(text))
} else if numPr := ppr.child("numPr"); numPr != nil {
w.extend(kindList, d.listItem(numPr, text), "\n")
} else if strings.Contains(style, "quote") {
w.add(kindQuote, "> "+strings.ReplaceAll(text, "\n", "\n> "))
} else {
w.add(kindParagraph, escapeBlockStart(text))
}
}
}
func isCodeStyle(style string) bool {
return style == "code" || strings.Contains(style, "source code") || strings.Contains(style, "preformatted") ||
strings.Contains(style, "html code")
}
func (d *docxDoc) listItem(numPr *node, text string) string {
level, _ := strconv.Atoi(numPr.child("ilvl").attr("val"))
numID := numPr.child("numId").attr("val")
marker := "-"
if d.listKinds[numID+":"+strconv.Itoa(level)] {
marker = "1."
}
return strings.Repeat(" ", level) + marker + " " + collapseSpace(text)
}
// runs collects the formatted text of a paragraph, resolving hyperlinks.
func (d *docxDoc) runs(p *node) []seg {
var segs []seg
var walk func(n *node, href string)
walk = func(n *node, href string) {
for _, c := range n.children {
switch c.name {
case "r":
segs = append(segs, d.run(c, href)...)
case "hyperlink":
walk(c, d.links[c.attr("id")])
case "ins", "smartTag", "sdt", "sdtContent":
walk(c, href)
}
}
}
walk(p, "")
return segs
}
func (d *docxDoc) run(r *node, href string) []seg {
rpr := r.child("rPr")
base := seg{
bold: on(rpr.child("b")),
italic: on(rpr.child("i")),
strike: on(rpr.child("strike")),
code: isMono(rpr.child("rFonts").attr("ascii")),
href: href,
}
var out []seg
for _, c := range r.children {
s := base
switch c.name {
case "t":
s.text = c.text
case "tab":
s.text = " "
case "br":
s.text = "\n"
default:
continue
}
out = append(out, s)
}
return out
}
// on reports whether a toggle property such as <w:b/> is switched on.
func on(n *node) bool {
if n == nil {
return false
}
switch n.attr("val") {
case "0", "false", "off":
return false
}
return true
}
func isMono(font string) bool {
f := strings.ToLower(font)
for _, m := range []string{"courier", "consolas", "mono", "menlo", "lucida console"} {
if strings.Contains(f, m) {
return true
}
}
return false
}
func plainText(segs []seg) string {
var b strings.Builder
for _, s := range segs {
b.WriteString(s.text)
}
return strings.TrimRight(b.String(), "\n")
}
func (d *docxDoc) table(tbl *node) string {
var rows [][]string
for _, tr := range tbl.children {
if tr.name != "tr" {
continue
}
var cells []string
for _, tc := range tr.children {
if tc.name != "tc" {
continue
}
var parts []string
for _, p := range tc.children {
if p.name == "p" {
segs := d.runs(p)
if len(rows) == 0 {
// The first row becomes the Markdown header, which is already bold.
for i := range segs {
segs[i].bold = false
}
}
if t := collapseSpace(renderSegs(segs)); t != "" {
parts = append(parts, t)
}
}
}
cell := strings.Join(parts, "<br>")
cells = append(cells, strings.ReplaceAll(cell, "|", `\|`))
}
rows = append(rows, cells)
}
if len(rows) == 0 {
return ""
}
cols := 0
for _, r := range rows {
cols = max(cols, len(r))
}
line := func(cells []string) string {
for len(cells) < cols {
cells = append(cells, "")
}
return "| " + strings.Join(cells, " | ") + " |"
}
var b strings.Builder
b.WriteString(line(rows[0]) + "\n")
b.WriteString("|" + strings.Repeat(" --- |", cols))
for _, r := range rows[1:] {
b.WriteString("\n" + line(r))
}
return b.String()
}
+28
View File
@@ -0,0 +1,28 @@
package tomd
import (
"fmt"
"strings"
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/strikethrough"
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table"
)
// HTML converts an HTML document or fragment to Markdown.
func HTML(data []byte) ([]byte, error) {
conv := converter.NewConverter(converter.WithPlugins(
base.NewBasePlugin(),
commonmark.NewCommonmarkPlugin(),
strikethrough.NewStrikethroughPlugin(),
table.NewTablePlugin(),
))
md, err := conv.ConvertString(string(data))
if err != nil {
return nil, fmt.Errorf("failed to convert HTML: %w", err)
}
return []byte(strings.TrimSpace(md) + "\n"), nil
}
+132
View File
@@ -0,0 +1,132 @@
package tomd
import (
"regexp"
"strings"
"unicode"
)
// seg is a run of text with uniform inline formatting.
type seg struct {
text string
bold, italic, code, strike bool
href string
}
func (s seg) sameFormat(o seg) bool {
return s.bold == o.bold && s.italic == o.italic && s.code == o.code && s.strike == o.strike && s.href == o.href
}
// renderSegs turns formatted runs into inline Markdown. Adjacent runs with the same formatting
// are merged first, because sources such as Word split text into many runs.
func renderSegs(segs []seg) string {
var merged []seg
for _, s := range segs {
if s.text == "" {
continue
}
if n := len(merged); n > 0 && merged[n-1].sameFormat(s) {
merged[n-1].text += s.text
continue
}
merged = append(merged, s)
}
var out strings.Builder
for i := 0; i < len(merged); {
// Group consecutive runs of one link so the whole group sits inside a single [..](..).
j := i + 1
if merged[i].href != "" {
for j < len(merged) && merged[j].href == merged[i].href {
j++
}
}
var inner strings.Builder
for _, s := range merged[i:j] {
inner.WriteString(renderSeg(s))
}
if href := merged[i].href; href != "" {
lead, core, trail := splitSpace(inner.String())
out.WriteString(lead + "[" + core + "](" + href + ")" + trail)
} else {
out.WriteString(inner.String())
}
i = j
}
return out.String()
}
func renderSeg(s seg) string {
lead, core, trail := splitSpace(s.text)
if core == "" {
return s.text
}
if s.code {
fence := "`"
if strings.Contains(core, "`") {
fence = "``"
}
return lead + fence + core + fence + trail
}
core = escapeInline(core)
switch {
case s.bold && s.italic:
core = "***" + core + "***"
case s.bold:
core = "**" + core + "**"
case s.italic:
core = "*" + core + "*"
}
if s.strike {
core = "~~" + core + "~~"
}
return lead + core + trail
}
// splitSpace separates leading and trailing whitespace, which must stay outside emphasis markers.
func splitSpace(s string) (lead, core, trail string) {
core = strings.TrimLeftFunc(s, unicode.IsSpace)
lead = s[:len(s)-len(core)]
trimmed := strings.TrimRightFunc(core, unicode.IsSpace)
return lead, trimmed, core[len(trimmed):]
}
// escapeInline backslash-escapes characters that would otherwise be read as Markdown.
func escapeInline(s string) string {
runes := []rune(s)
var b strings.Builder
for i, r := range runes {
switch r {
case '\\', '*', '`', '[', ']', '<':
b.WriteByte('\\')
case '_':
// Underscores inside a word are literal in CommonMark.
inWord := i > 0 && i < len(runes)-1 && isAlnum(runes[i-1]) && isAlnum(runes[i+1])
if !inWord {
b.WriteByte('\\')
}
}
b.WriteRune(r)
}
return b.String()
}
func isAlnum(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
var blockStart = regexp.MustCompile(`^(#{1,6}\s|[-+*]\s|\d+[.)]\s|>)`)
// escapeBlockStart stops a paragraph from being read as a heading, list or quote.
func escapeBlockStart(s string) string {
if blockStart.MatchString(s) {
return `\` + s
}
return s
}
// collapseSpace squeezes runs of whitespace (including newlines) into single spaces.
func collapseSpace(s string) string {
return strings.Join(strings.Fields(s), " ")
}
+340
View File
@@ -0,0 +1,340 @@
package tomd
import (
"bytes"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
"github.com/ledongthuc/pdf"
)
// pdfLine is one visual line of text on a page.
type pdfLine struct {
x, y, size float64
segs []seg
plain string
raw string // like plain but keeps leading indentation, for code
mono bool
}
// PDF converts a PDF to Markdown on a best-effort basis. PDFs carry no document structure, so
// headings are inferred from font size, code from monospaced fonts, and lists from bullet or
// number prefixes. Tables and images are not recovered.
func PDF(data []byte) (out []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("failed to read PDF: %v", r)
}
}()
r, err := pdf.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, fmt.Errorf("failed to read PDF: %w", err)
}
var pages [][]pdfLine
for i := 1; i <= r.NumPage(); i++ {
page := r.Page(i)
if page.V.IsNull() {
continue
}
if lines := groupLines(page.Content().Text); len(lines) > 0 {
pages = append(pages, lines)
}
}
return []byte(buildMarkdown(pages)), nil
}
func fontFlags(font string) (bold, italic, mono bool) {
f := strings.ToLower(font)
has := func(subs ...string) bool {
for _, s := range subs {
if strings.Contains(f, s) {
return true
}
}
return false
}
return has("bold", "black", "heavy"), has("italic", "oblique"), isMono(f)
}
// groupLines clusters text items into lines and turns them into formatted runs.
func groupLines(items []pdf.Text) []pdfLine {
items = append([]pdf.Text(nil), items...)
sort.SliceStable(items, func(i, j int) bool { return items[i].Y > items[j].Y })
var clusters [][]pdf.Text
for _, it := range items {
n := len(clusters)
if n > 0 && math.Abs(clusters[n-1][0].Y-it.Y) <= math.Max(2, 0.35*it.FontSize) {
clusters[n-1] = append(clusters[n-1], it)
continue
}
clusters = append(clusters, []pdf.Text{it})
}
var lines []pdfLine
for _, c := range clusters {
if l, ok := buildLine(c); ok {
lines = append(lines, l)
}
}
return lines
}
func buildLine(items []pdf.Text) (pdfLine, bool) {
sort.SliceStable(items, func(i, j int) bool { return items[i].X < items[j].X })
line := pdfLine{x: items[0].X, y: items[0].Y}
sizeChars := map[float64]int{}
monoChars, chars := 0, 0
var prev *pdf.Text
for i := range items {
it := items[i]
if it.S == "�" || it.S == "" {
continue
}
bold, italic, mono := fontFlags(it.Font)
s := seg{text: it.S, bold: bold, italic: italic, code: mono}
if prev != nil && needsSpace(*prev, it) {
s.text = " " + s.text
}
prev = &items[i]
if n := len(line.segs); n > 0 && line.segs[n-1].sameFormat(s) {
line.segs[n-1].text += s.text
} else {
line.segs = append(line.segs, s)
}
if !unicode.IsSpace([]rune(it.S)[0]) {
sizeChars[math.Round(it.FontSize*2)/2]++
chars++
if mono {
monoChars++
}
}
}
line.raw = strings.TrimRight(plainText(line.segs), " \t")
line.plain = strings.TrimSpace(line.raw)
if line.plain == "" {
return line, false
}
best := 0
for size, n := range sizeChars {
if n > best {
best, line.size = n, size
}
}
line.mono = monoChars == chars
return line, true
}
// needsSpace decides whether a space separates two consecutive text items. When the extractor knows
// glyph widths the real gap is used; otherwise (positions only advance per text-show operator) any
// new position starts a new word, except before closing punctuation.
func needsSpace(prev, next pdf.Text) bool {
if unicode.IsSpace([]rune(prev.S)[0]) || unicode.IsSpace([]rune(next.S)[0]) {
return false
}
if prev.W > 0 {
return next.X-(prev.X+prev.W) > 0.2*next.FontSize
}
if next.X-prev.X < 0.01 {
return false // same show operator: part of the same word
}
first := []rune(next.S)[0]
last := []rune(prev.S)[len([]rune(prev.S))-1]
return !strings.ContainsRune(",.;:!?)]}%’”", first) && !strings.ContainsRune("([{‘“", last)
}
var listMarker = regexp.MustCompile(`^([•·▪‣◦●○▫–\-*]|\d{1,3}[.)])\s+`)
// trimPrefix removes the first n runes from the runs.
func trimPrefix(segs []seg, n int) []seg {
out := make([]seg, 0, len(segs))
for _, s := range segs {
r := []rune(s.text)
switch {
case n >= len(r):
n -= len(r)
continue
case n > 0:
s.text = string(r[n:])
n = 0
}
out = append(out, s)
}
return out
}
func buildMarkdown(pages [][]pdfLine) string {
body := bodySize(pages)
headings := headingSizes(pages, body)
w := &mdWriter{}
var (
para []seg // paragraph or list item being accumulated
paraKind paraKind
paraMark string // list marker line prefix
textX float64
lastY float64
codeX float64
)
flush := func() {
if len(para) == 0 {
return
}
text := collapseSpace(renderSegs(para))
if paraKind == kindList {
w.extend(kindList, paraMark+text, "\n")
} else {
w.add(kindParagraph, escapeBlockStart(text))
}
para = nil
}
for _, page := range pages {
if paraKind != kindCode {
flush()
}
left := page[0].x
for _, l := range page {
left = math.Min(left, l.x)
}
for _, l := range page {
switch level := headingLevel(l, headings); {
case l.mono:
flush()
if paraKind != kindCode {
codeX = l.x
}
if blanks := int(math.Round((lastY-l.y)/(l.size*1.4))) - 1; paraKind == kindCode && blanks > 0 && lastY > l.y {
for range blanks {
w.extend(kindCode, "", "\n")
}
}
indent := strings.Repeat(" ", max(0, int(math.Round((l.x-codeX)/(l.size*0.6)))))
w.extend(kindCode, indent+l.raw, "\n")
paraKind = kindCode
case level > 0:
flush()
w.add(kindHeading, strings.Repeat("#", level)+" "+collapseSpace(renderSegs(stripCode(l.segs))))
paraKind = kindHeading
default:
segs := l.segs
if m := listMarker.FindString(l.plain); m != "" {
flush()
depth := int(math.Round((l.x - left) / (l.size * 1.6)))
paraKind = kindList
paraMark = strings.Repeat(" ", max(depth, 0)) + markdownMarker(strings.TrimSpace(m))
segs = trimPrefix(trimLeadingSpace(segs), len([]rune(strings.TrimSpace(m))))
textX = l.x + l.size
} else if len(para) > 0 && paraKind != kindCode && lastY-l.y > 0 && lastY-l.y <= l.size*1.7 &&
(paraKind != kindList || l.x >= textX-2) {
segs = append([]seg{{text: " "}}, segs...)
} else {
flush()
paraKind = kindParagraph
}
para = append(para, segs...)
}
lastY = l.y
}
}
flush()
return w.String()
}
func trimLeadingSpace(segs []seg) []seg {
if len(segs) > 0 {
segs = append([]seg(nil), segs...)
segs[0].text = strings.TrimLeftFunc(segs[0].text, unicode.IsSpace)
}
return segs
}
func markdownMarker(m string) string {
if n, err := strconv.Atoi(strings.TrimRight(m, ".)")); err == nil {
return strconv.Itoa(n) + ". "
}
return "- "
}
// stripCode removes inline-code styling, which is meaningless inside a heading.
func stripCode(segs []seg) []seg {
out := append([]seg(nil), segs...)
for i := range out {
out[i].code, out[i].bold = false, false
}
return out
}
// bodySize is the font size that carries the most (non-code) text.
func bodySize(pages [][]pdfLine) float64 {
counts := map[float64]int{}
for _, p := range pages {
for _, l := range p {
if !l.mono {
counts[l.size] += len([]rune(l.plain))
}
}
}
var body float64
best := 0
for size, n := range counts {
if n > best || (n == best && size < body) {
body, best = size, n
}
}
return body
}
// headingSizes lists the distinct sizes clearly larger than body text, largest first.
func headingSizes(pages [][]pdfLine, body float64) []float64 {
seen := map[float64]bool{}
for _, p := range pages {
for _, l := range p {
if !l.mono && l.size > body*1.12 {
seen[l.size] = true
}
}
}
sizes := make([]float64, 0, len(seen))
for s := range seen {
sizes = append(sizes, s)
}
sort.Sort(sort.Reverse(sort.Float64Slice(sizes)))
return sizes
}
func headingLevel(l pdfLine, headings []float64) int {
if l.mono {
return 0
}
for i, s := range headings {
if l.size == s {
return min(i+1, 6)
}
}
return 0
}
+279
View File
@@ -0,0 +1,279 @@
// Package tomd converts PDF, HTML and DOCX documents back into Markdown.
package tomd
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
)
// Input formats accepted by ParseFormats, in order of preference when several files share a name.
const (
FormatDOCX = "docx"
FormatHTML = "html"
FormatPDF = "pdf"
)
// FormatNames lists every supported input format.
var FormatNames = []string{FormatDOCX, FormatHTML, FormatPDF}
// ParseFormats turns a comma separated list such as "html,docx" into validated formats.
func ParseFormats(list string) ([]string, error) {
var formats []string
for _, f := range strings.Split(list, ",") {
f = strings.ToLower(strings.TrimSpace(f))
if f == "" || slices.Contains(formats, f) {
continue
}
if !slices.Contains(FormatNames, f) {
return nil, fmt.Errorf("unknown format %q (available: %s)", f, strings.Join(FormatNames, ", "))
}
formats = append(formats, f)
}
if len(formats) == 0 {
return nil, fmt.Errorf("no input format given (available: %s)", strings.Join(FormatNames, ", "))
}
return formats, nil
}
// formatOf returns the format of path from its extension, or "" when it is not a supported input.
func formatOf(path string) string {
switch strings.ToLower(filepath.Ext(path)) {
case ".docx":
return FormatDOCX
case ".html", ".htm":
return FormatHTML
case ".pdf":
return FormatPDF
}
return ""
}
func isMarkdownName(path string) bool {
ext := strings.ToLower(filepath.Ext(path))
return ext == ".md" || ext == ".markdown"
}
// OutputPath returns the Markdown file written next to input.
func OutputPath(input string) string {
return strings.TrimSuffix(input, filepath.Ext(input)) + ".md"
}
// Convert converts the file at path to Markdown according to its extension.
func Convert(path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
switch formatOf(path) {
case FormatDOCX:
return DOCX(data)
case FormatHTML:
return HTML(data)
case FormatPDF:
return PDF(data)
default:
return nil, fmt.Errorf("unsupported file type %q", filepath.Ext(path))
}
}
// Runner converts documents to Markdown.
//
// When InputFile is set only that file is converted (regardless of Formats) and Output, if given,
// is the name of the Markdown file to write; ".md" is added unless it already ends in .md or
// .markdown. Otherwise every matching document under InputDir is converted, and Output, if given,
// is a directory that receives the results, mirroring the layout under InputDir. With neither,
// each Markdown file is written next to its source.
type Runner struct {
InputDir string
Recursive bool
Parallel bool
InputFile string
Output string
// Force overwrites Markdown files that already exist; otherwise they are skipped.
Force bool
Formats []string
}
// Validate checks the input and output options before any work is done.
func (r *Runner) Validate() error {
if r.InputFile != "" {
info, err := os.Stat(r.InputFile)
if err != nil {
return fmt.Errorf("input file: %w", err)
}
if info.IsDir() {
return fmt.Errorf("input %s is a directory; use -dir to scan a directory", r.InputFile)
}
if formatOf(r.InputFile) == "" {
return fmt.Errorf("input %s must be a .pdf, .html, .htm or .docx file", r.InputFile)
}
}
if r.Output == "" {
return nil
}
info, err := os.Stat(r.Output)
exists := err == nil
if r.InputFile == "" {
if exists && !info.IsDir() {
return fmt.Errorf("output %s exists and is not a directory", r.Output)
}
return nil
}
if exists && info.IsDir() {
return fmt.Errorf("output %s is a directory; give a file name when using -input", r.Output)
}
if formatOf(r.Output) != "" {
return fmt.Errorf("output %s must be a Markdown file, not a %s file", r.Output, filepath.Ext(r.Output))
}
return nil
}
// outputFor returns the Markdown file written for input.
func (r *Runner) outputFor(input string) string {
switch {
case r.InputFile != "" && r.Output != "":
if isMarkdownName(r.Output) {
return r.Output
}
return r.Output + ".md"
case r.InputFile == "" && r.Output != "":
rel, err := filepath.Rel(r.InputDir, input)
if err != nil {
rel = filepath.Base(input)
}
return filepath.Join(r.Output, OutputPath(rel))
default:
return OutputPath(input)
}
}
// Run converts InputFile, or all matching documents under InputDir.
func (r *Runner) Run() error {
if err := r.Validate(); err != nil {
return err
}
files, err := r.inputFiles()
if err != nil {
return fmt.Errorf("failed to find documents: %w", err)
}
if len(files) == 0 {
fmt.Println("No documents found")
return nil
}
return r.convertFiles(files)
}
func (r *Runner) inputFiles() ([]string, error) {
if r.InputFile != "" {
return []string{r.InputFile}, nil
}
return r.findFiles()
}
func (r *Runner) findFiles() ([]string, error) {
byOutput := map[string]string{}
var order []string
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if !r.Recursive && path != r.InputDir {
return filepath.SkipDir
}
return nil
}
format := formatOf(path)
// Skip Word's "~$" owner files, which carry a .docx extension but are not documents.
if format == "" || !slices.Contains(r.Formats, format) || strings.HasPrefix(info.Name(), "~$") {
return nil
}
out := r.outputFor(path)
prev, clash := byOutput[out]
switch {
case !clash:
byOutput[out] = path
order = append(order, out)
case slices.Index(FormatNames, format) < slices.Index(FormatNames, formatOf(prev)):
fmt.Printf("Warning: %s and %s both produce %s, using %s\n", prev, path, out, path)
byOutput[out] = path
default:
fmt.Printf("Warning: %s and %s both produce %s, using %s\n", prev, path, out, prev)
}
return nil
}
if err := filepath.Walk(r.InputDir, walkFn); err != nil {
return nil, err
}
files := make([]string, 0, len(order))
for _, out := range order {
files = append(files, byOutput[out])
}
return files, nil
}
func (r *Runner) convertFiles(files []string) error {
if !r.Parallel {
for _, f := range files {
if err := r.convertFile(f); err != nil {
return fmt.Errorf("failed to convert %s: %w", f, err)
}
}
return nil
}
var wg sync.WaitGroup
errs := make(chan error, len(files))
for _, f := range files {
wg.Add(1)
go func(f string) {
defer wg.Done()
if err := r.convertFile(f); err != nil {
errs <- fmt.Errorf("failed to convert %s: %w", f, err)
}
}(f)
}
wg.Wait()
close(errs)
for err := range errs {
return err
}
return nil
}
func (r *Runner) convertFile(input string) error {
output := r.outputFor(input)
if _, err := os.Stat(output); err == nil && !r.Force {
fmt.Printf("Skipping %s: %s already exists (use -force to overwrite)\n", input, output)
return nil
}
md, err := Convert(input)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
if err := os.WriteFile(output, md, 0o644); err != nil {
return fmt.Errorf("failed to write %s: %w", output, err)
}
fmt.Printf("Successfully converted %s to %s\n", input, output)
return nil
}
+249
View File
@@ -0,0 +1,249 @@
package tomd
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document"
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine"
)
const sample = "# Title\n\nSome **bold**, *italic* and `code` with a [link](http://example.com).\n\n" +
"## Lists\n\n- one\n- two\n - nested\n\n1. first\n2. second\n\n" +
"```\nfunc main() {\n run()\n}\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n"
func requireContains(t *testing.T, got string, wants ...string) {
t.Helper()
for _, want := range wants {
if !strings.Contains(got, want) {
t.Errorf("output missing %q\n--- output ---\n%s", want, got)
}
}
}
func TestDOCXRoundTrip(t *testing.T) {
data, err := document.DOCX([]byte(sample))
if err != nil {
t.Fatal(err)
}
md, err := DOCX(data)
if err != nil {
t.Fatal(err)
}
requireContains(t, string(md),
"# Title", "## Lists", "**bold**", "*italic*", "`code`", "[link](http://example.com)",
"- one\n- two\n - nested", "1. first\n1. second",
"```\nfunc main() {\n run()\n}\n```", "| a | b |\n| --- | --- |\n| 1 | 2 |")
}
func TestHTMLRoundTrip(t *testing.T) {
md, err := HTML(document.HTML([]byte(sample)))
if err != nil {
t.Fatal(err)
}
requireContains(t, string(md),
"# Title", "## Lists", "**bold**", "*italic*", "`code`", "[link](http://example.com)", "- one", "1. first", "```")
if strings.Contains(string(md), "font-family") {
t.Error("stylesheet leaked into Markdown")
}
}
func TestPDFRoundTrip(t *testing.T) {
eng, err := engine.New(engine.GoPDF)
if err != nil {
t.Fatal(err)
}
out := filepath.Join(t.TempDir(), "doc.pdf")
if err := eng.Render([]byte(sample), out); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(out)
if err != nil {
t.Fatal(err)
}
md, err := PDF(data)
if err != nil {
t.Fatal(err)
}
requireContains(t, string(md),
"# Title", "## Lists", "**bold**", "*italic*", "`code`", "- one", " - nested", "1. first", "2. second",
"```\nfunc main() {\n run()\n}\n```")
}
func TestInvalidInputs(t *testing.T) {
if _, err := DOCX([]byte("not a zip")); err == nil {
t.Error("expected error for invalid docx")
}
if _, err := PDF([]byte("not a pdf")); err == nil {
t.Error("expected error for invalid pdf")
}
}
func TestParseFormats(t *testing.T) {
got, err := ParseFormats("HTML, docx,html")
if err != nil || len(got) != 2 || got[0] != FormatHTML || got[1] != FormatDOCX {
t.Errorf("got %v, %v", got, err)
}
for _, bad := range []string{"", "md", "pdf,txt"} {
if _, err := ParseFormats(bad); err == nil {
t.Errorf("ParseFormats(%q) should fail", bad)
}
}
}
func TestRunnerSkipsExistingUnlessForced(t *testing.T) {
dir := t.TempDir()
write := func(name, content string) {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
write("page.html", "<h1>From HTML</h1>")
write("page.md", "original")
r := &Runner{InputDir: dir, Recursive: true, Formats: FormatNames}
if err := r.Run(); err != nil {
t.Fatal(err)
}
if got, _ := os.ReadFile(filepath.Join(dir, "page.md")); string(got) != "original" {
t.Errorf("existing markdown was overwritten: %q", got)
}
r.Force = true
if err := r.Run(); err != nil {
t.Fatal(err)
}
if got, _ := os.ReadFile(filepath.Join(dir, "page.md")); !strings.Contains(string(got), "# From HTML") {
t.Errorf("force did not overwrite: %q", got)
}
}
func TestRunnerPrefersFormatOnClash(t *testing.T) {
dir := t.TempDir()
docx, err := document.DOCX([]byte("# From DOCX"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "x.docx"), docx, 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "x.html"), []byte("<h1>From HTML</h1>"), 0o644); err != nil {
t.Fatal(err)
}
r := &Runner{InputDir: dir, Recursive: true, Formats: FormatNames}
if err := r.Run(); err != nil {
t.Fatal(err)
}
got, _ := os.ReadFile(filepath.Join(dir, "x.md"))
if !strings.Contains(string(got), "From DOCX") {
t.Errorf("expected docx to win the clash, got %q", got)
}
}
func TestRunnerFormatFilter(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "a.html"), []byte("<p>hi</p>"), 0o644); err != nil {
t.Fatal(err)
}
r := &Runner{InputDir: dir, Formats: []string{FormatDOCX}}
if err := r.Run(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, "a.md")); err == nil {
t.Error("html should be ignored when only docx is selected")
}
}
func writeDoc(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func TestInputFileWithOutputName(t *testing.T) {
dir := t.TempDir()
writeDoc(t, filepath.Join(dir, "a.html"), "<h1>A</h1>")
writeDoc(t, filepath.Join(dir, "b.html"), "<h1>B</h1>")
// The format filter does not apply to an explicit input.
r := &Runner{InputFile: filepath.Join(dir, "a.html"), Output: filepath.Join(dir, "out", "notes"), Formats: []string{FormatDOCX}}
if err := r.Run(); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(dir, "out", "notes.md"))
if err != nil || !strings.Contains(string(got), "# A") {
t.Fatalf("expected out/notes.md with the converted content: %v %q", err, got)
}
if fileExists(filepath.Join(dir, "a.md")) || fileExists(filepath.Join(dir, "b.md")) {
t.Error("only the named output should be written")
}
}
func TestOutputNameKeepsMarkdownExtension(t *testing.T) {
dir := t.TempDir()
writeDoc(t, filepath.Join(dir, "a.html"), "<h1>A</h1>")
r := &Runner{InputFile: filepath.Join(dir, "a.html"), Output: filepath.Join(dir, "x.markdown")}
if err := r.Run(); err != nil {
t.Fatal(err)
}
if !fileExists(filepath.Join(dir, "x.markdown")) || fileExists(filepath.Join(dir, "x.markdown.md")) {
t.Error("a .markdown output name should be used as is")
}
}
func TestOutputValidation(t *testing.T) {
dir := t.TempDir()
writeDoc(t, filepath.Join(dir, "a.html"), "<p>x</p>")
writeDoc(t, filepath.Join(dir, "notes.txt"), "text")
in := filepath.Join(dir, "a.html")
cases := map[string]*Runner{
"missing input": {InputFile: filepath.Join(dir, "nope.html")},
"input is a dir": {InputFile: dir},
"unsupported input": {InputFile: filepath.Join(dir, "notes.txt")},
"output is a dir": {InputFile: in, Output: dir},
"output not markdown": {InputFile: in, Output: filepath.Join(dir, "x.pdf")},
"scan output is file": {InputDir: dir, Output: in},
}
for name, r := range cases {
if err := r.Validate(); err == nil {
t.Errorf("%s: expected a validation error", name)
}
}
}
func TestOutputDirMirrorsLayout(t *testing.T) {
src, out := t.TempDir(), filepath.Join(t.TempDir(), "docs")
writeDoc(t, filepath.Join(src, "a.html"), "<h1>A</h1>")
writeDoc(t, filepath.Join(src, "sub", "b.html"), "<h1>B</h1>")
r := &Runner{InputDir: src, Recursive: true, Output: out, Formats: FormatNames}
if err := r.Run(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"a.md", "sub/b.md"} {
if !fileExists(filepath.Join(out, want)) {
t.Errorf("expected %s in output dir", want)
}
}
if fileExists(filepath.Join(src, "a.md")) {
t.Error("nothing should be written next to the sources when -output is a directory")
}
}
-331
View File
@@ -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
}