mirror of
https://github.com/Warky-Devs/go-mdtopdf-helper.git
synced 2026-11-25 13:48:47 +00:00
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
This commit is contained in:
1 parent
73f258aa95
commit
50b7246c21
23 files changed
+1948
-393
No files matched your search
@@ -0,0 +1,186 @@
|
||||
// Package converter finds Markdown files and converts them to PDF, HTML or DOCX.
|
||||
package converter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document"
|
||||
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine"
|
||||
)
|
||||
|
||||
// Output formats accepted by ParseFormats.
|
||||
const (
|
||||
FormatPDF = "pdf"
|
||||
FormatHTML = "html"
|
||||
FormatDOCX = "docx"
|
||||
)
|
||||
|
||||
// FormatNames lists every supported output format.
|
||||
var FormatNames = []string{FormatPDF, FormatHTML, FormatDOCX}
|
||||
|
||||
// ParseFormats turns a comma separated list such as "pdf,html" into validated, de-duplicated formats.
|
||||
func ParseFormats(list string) ([]string, error) {
|
||||
var formats []string
|
||||
seen := map[string]bool{}
|
||||
for _, f := range strings.Split(list, ",") {
|
||||
f = strings.ToLower(strings.TrimSpace(f))
|
||||
if f == "" || seen[f] {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(FormatNames, f) {
|
||||
return nil, fmt.Errorf("unknown format %q (available: %s)", f, strings.Join(FormatNames, ", "))
|
||||
}
|
||||
seen[f] = true
|
||||
formats = append(formats, f)
|
||||
}
|
||||
if len(formats) == 0 {
|
||||
return nil, fmt.Errorf("no output format given (available: %s)", strings.Join(FormatNames, ", "))
|
||||
}
|
||||
return formats, nil
|
||||
}
|
||||
|
||||
// Converter converts Markdown files found under InputDir into each of Formats.
|
||||
// Engine renders the PDF format and may be nil when PDF is not requested.
|
||||
type Converter struct {
|
||||
InputDir string
|
||||
Recursive bool
|
||||
Parallel bool
|
||||
Formats []string
|
||||
Engine engine.Engine
|
||||
}
|
||||
|
||||
// outputPath returns the file written for inputFile in the given format.
|
||||
func outputPath(inputFile, format string) string {
|
||||
return strings.TrimSuffix(inputFile, filepath.Ext(inputFile)) + "." + format
|
||||
}
|
||||
|
||||
// Run converts every Markdown file under InputDir.
|
||||
func (c *Converter) Run() error {
|
||||
files, err := c.findMarkdownFiles()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to find markdown files: %w", err)
|
||||
}
|
||||
|
||||
if len(files) == 0 {
|
||||
fmt.Println("No markdown files found")
|
||||
return nil
|
||||
}
|
||||
|
||||
return c.ConvertFiles(files)
|
||||
}
|
||||
|
||||
// ConvertFiles converts the given Markdown files, in parallel when enabled.
|
||||
func (c *Converter) ConvertFiles(files []string) error {
|
||||
if c.Parallel {
|
||||
return c.convertFilesParallel(files)
|
||||
}
|
||||
return c.convertFilesSerial(files)
|
||||
}
|
||||
|
||||
func isMarkdown(path string) bool {
|
||||
return strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".markdown")
|
||||
}
|
||||
|
||||
func (c *Converter) findMarkdownFiles() ([]string, error) {
|
||||
var files []string
|
||||
|
||||
walkFn := func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() && !c.Recursive && path != c.InputDir {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
|
||||
if !info.IsDir() && isMarkdown(path) {
|
||||
files = append(files, path)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := filepath.Walk(c.InputDir, walkFn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (c *Converter) convertFilesParallel(files []string) error {
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, len(files))
|
||||
|
||||
for _, file := range files {
|
||||
wg.Add(1)
|
||||
go func(f string) {
|
||||
defer wg.Done()
|
||||
if err := c.convertFile(f); err != nil {
|
||||
errs <- fmt.Errorf("failed to convert %s: %w", f, err)
|
||||
}
|
||||
}(file)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
for err := range errs {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Converter) convertFilesSerial(files []string) error {
|
||||
for _, file := range files {
|
||||
if err := c.convertFile(file); err != nil {
|
||||
return fmt.Errorf("failed to convert %s: %w", file, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Converter) convertFile(inputFile string) error {
|
||||
mdContent, err := os.ReadFile(inputFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read file: %w", err)
|
||||
}
|
||||
|
||||
formats := c.Formats
|
||||
if len(formats) == 0 {
|
||||
formats = []string{FormatPDF}
|
||||
}
|
||||
|
||||
for _, format := range formats {
|
||||
outputFile := outputPath(inputFile, format)
|
||||
if err := c.write(mdContent, format, outputFile); err != nil {
|
||||
return fmt.Errorf("%s: %w", format, err)
|
||||
}
|
||||
fmt.Printf("Successfully converted %s to %s\n", inputFile, outputFile)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Converter) write(md []byte, format, outputFile string) error {
|
||||
switch format {
|
||||
case FormatPDF:
|
||||
if c.Engine == nil {
|
||||
return fmt.Errorf("no PDF engine configured")
|
||||
}
|
||||
return c.Engine.Render(md, outputFile)
|
||||
case FormatHTML:
|
||||
return os.WriteFile(outputFile, document.HTML(md), 0o644)
|
||||
case FormatDOCX:
|
||||
data, err := document.DOCX(md)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(outputFile, data, 0o644)
|
||||
default:
|
||||
return fmt.Errorf("unknown format %q", format)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package converter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine"
|
||||
)
|
||||
|
||||
func TestRunConvertsMarkdownFiles(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
content := "# Test Document\nThis is a basic test."
|
||||
if err := os.WriteFile(filepath.Join(tmpDir, "test.md"), []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("Failed to create test file: %v", err)
|
||||
}
|
||||
|
||||
eng, err := engine.New(engine.Default)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = eng.Close() }()
|
||||
|
||||
conv := &Converter{InputDir: tmpDir, Engine: eng}
|
||||
if err := conv.Run(); err != nil {
|
||||
t.Fatalf("Conversion failed: %v", err)
|
||||
}
|
||||
|
||||
pdf, err := os.ReadFile(filepath.Join(tmpDir, "test.pdf"))
|
||||
if err != nil {
|
||||
t.Fatalf("PDF file was not created: %v", err)
|
||||
}
|
||||
if !bytes.HasPrefix(pdf, []byte("%PDF")) {
|
||||
t.Error("output is not a PDF")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNonRecursiveSkipsSubdirs(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
sub := filepath.Join(tmpDir, "sub")
|
||||
if err := os.Mkdir(sub, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range []string{filepath.Join(tmpDir, "a.md"), filepath.Join(sub, "b.md")} {
|
||||
if err := os.WriteFile(p, []byte("# hi"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
eng, _ := engine.New(engine.Default)
|
||||
conv := &Converter{InputDir: tmpDir, Engine: eng}
|
||||
if err := conv.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(tmpDir, "a.pdf")); err != nil {
|
||||
t.Errorf("expected a.pdf: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(sub, "b.pdf")); err == nil {
|
||||
t.Error("b.pdf should not exist when not recursive")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFormats(t *testing.T) {
|
||||
got, err := ParseFormats("PDF, html,pdf,docx")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []string{FormatPDF, FormatHTML, FormatDOCX}; !slices.Equal(got, want) {
|
||||
t.Errorf("got %v, want %v", got, want)
|
||||
}
|
||||
|
||||
for _, bad := range []string{"", ",", "odt", "pdf,rtf"} {
|
||||
if _, err := ParseFormats(bad); err == nil {
|
||||
t.Errorf("ParseFormats(%q) should fail", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunWritesAllFormats(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(tmpDir, "doc.md"), []byte("# Hi\n\ntext"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// No engine needed when PDF is not requested.
|
||||
conv := &Converter{InputDir: tmpDir, Formats: []string{FormatHTML, FormatDOCX}}
|
||||
if err := conv.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, ext := range []string{"html", "docx"} {
|
||||
if _, err := os.Stat(filepath.Join(tmpDir, "doc."+ext)); err != nil {
|
||||
t.Errorf("expected doc.%s: %v", ext, err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tmpDir, "doc.pdf")); err == nil {
|
||||
t.Error("doc.pdf should not be written")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package converter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RunAsHook converts the staged Markdown files and stages the generated output.
|
||||
func (c *Converter) RunAsHook() error {
|
||||
if !confirmConversion() {
|
||||
fmt.Println("Skipping conversion")
|
||||
return nil
|
||||
}
|
||||
|
||||
files, err := stagedMarkdownFiles()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get staged files: %w", err)
|
||||
}
|
||||
|
||||
if len(files) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := c.ConvertFiles(files); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.stageGeneratedFiles(files)
|
||||
}
|
||||
|
||||
func confirmConversion() bool {
|
||||
fmt.Print("Convert Markdown files? [Y/n] ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
response, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
response = strings.ToLower(strings.TrimSpace(response))
|
||||
return response == "" || response == "y" || response == "yes"
|
||||
}
|
||||
|
||||
func stagedMarkdownFiles() ([]string, error) {
|
||||
cmd := exec.Command("git", "diff", "--cached", "--name-only", "--diff-filter=d")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var files []string
|
||||
scanner := bufio.NewScanner(bytes.NewReader(output))
|
||||
for scanner.Scan() {
|
||||
if file := scanner.Text(); isMarkdown(file) {
|
||||
files = append(files, file)
|
||||
}
|
||||
}
|
||||
|
||||
return files, scanner.Err()
|
||||
}
|
||||
|
||||
func (c *Converter) stageGeneratedFiles(files []string) error {
|
||||
formats := c.Formats
|
||||
if len(formats) == 0 {
|
||||
formats = []string{FormatPDF}
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
for _, format := range formats {
|
||||
out := filepath.FromSlash(outputPath(file, format))
|
||||
if err := exec.Command("git", "add", out).Run(); err != nil {
|
||||
fmt.Printf("Warning: Could not stage %s\n", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -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&b=2") {
|
||||
t.Error("hyperlink target missing or not escaped")
|
||||
}
|
||||
}
|
||||
@@ -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>`
|
||||
@@ -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...)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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, ", "))
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 ""
|
||||
}
|
||||
Reference in new issue
Block a user