Files
Docwell/Server/internal/convert/pdf.go
T
tajniak81andClaude Opus 5.5 d28f1e02db Add tables, to-dos, callouts and the rest of editor parity
The editor gains the blocks and formatting it lacked next to AFFiNE:

- Tables with a header row, resizable columns, a toolbar to add, delete,
  merge and split, and rows that move by a drag grip, toolbar buttons or
  Ctrl+Alt+Up/Down.
- To-do lists (also from "[] "), callouts with an emoji and colour, and
  headings down to level 6 (Ctrl+Shift+0-6 for text and headings).
- Text colour and highlights from a fixed palette that follows the theme,
  and left, centre and right alignment.
- Optional line numbers on code blocks, with a default hosts can set.
- PDF attachments show their pages inline; pdf.js loads only then, and
  the mobile bundle leaves it out.
- The selection toolbar adds underline, colour, align, inline math, make a
  linked page and copy block link. A grip beside each block drags it and
  opens a menu: turn into, move, duplicate, copy, copy link, delete.
- The slash menu adds Today, Tomorrow, Yesterday, Now and New page.

The web app translates the new words and makes linked pages as children
of the open page. The mobile bridge gets underline, to-do, callout and
table commands, so its protocol moves to version 2 and the bundle is
rebuilt.

docwell-server's converters learn the new nodes: Markdown writes task
lists, GitHub alerts and tables and reads them back; HTML keeps colours
and alignment and reads its own output back; PDF draws tables, to-dos,
callouts and coloured text; Word import keeps tables, alignment, H4-H6
and colours; Notion import turns databases into tables and keeps
callouts and to-dos. Imported tables and H4-H6 headings no longer
collapse into paragraphs and H3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:20:08 +01:00

597 lines
15 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"bytes"
"fmt"
"image"
"image/draw"
_ "image/gif" // image.Decode reads GIF and JPEG attachments.
_ "image/jpeg"
"image/png"
"strconv"
"strings"
"github.com/go-pdf/fpdf"
"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/gomonobold"
"golang.org/x/image/font/gofont/gomonobolditalic"
"golang.org/x/image/font/gofont/gomonoitalic"
"golang.org/x/image/font/gofont/goregular"
_ "golang.org/x/image/webp" // image.Decode reads WebP attachments too.
)
// PDFOptions adjust a PDF export.
type PDFOptions struct {
Options
// BaseURL makes server paths (/p/<id>, attachments) absolute links.
BaseURL string
// Image loads an image by its document URL; nil, or an error, leaves the
// image's description in its place.
Image func(src string) ([]byte, error)
}
// maxPDFImagePixels keeps one decoded image under about 200 MB of memory.
const maxPDFImagePixels = 50_000_000
// PDF renders a page as an A4 PDF with the title on top, a bookmark per
// heading and page numbers. Diagrams (stored as SVG) and Mermaid charts are
// not drawn: diagrams become a link to their file, Mermaid its source.
func PDF(title string, doc Node, o PDFOptions) (out []byte, err error) {
defer func() {
// fpdf panics on some input instead of failing; one bad page must
// not take the server down.
if r := recover(); r != nil {
out, err = nil, fmt.Errorf("pdf: %v", r)
}
}()
f := fpdf.New("P", "mm", "A4", "")
for _, ft := range []struct {
family, style string
ttf []byte
}{
{"go", "", goregular.TTF}, {"go", "B", gobold.TTF}, {"go", "I", goitalic.TTF}, {"go", "BI", gobolditalic.TTF},
{"mono", "", gomono.TTF}, {"mono", "B", gomonobold.TTF}, {"mono", "I", gomonoitalic.TTF}, {"mono", "BI", gomonobolditalic.TTF},
} {
f.AddUTF8FontFromBytes(ft.family, ft.style, ft.ttf)
}
f.SetMargins(pdfMargin, pdfMargin, pdfMargin)
f.SetAutoPageBreak(true, pdfMargin)
f.SetTitle(pdfText(title), true)
f.SetCreator("Docwell", true)
f.AliasNbPages("")
f.SetFooterFunc(func() {
f.SetY(-12)
f.SetFont("go", "", 8)
f.SetTextColor(130, 130, 130)
f.CellFormat(0, 5, strconv.Itoa(f.PageNo())+" / {nb}", "", 0, "C", false, 0, "")
})
f.AddPage()
pageW, _ := f.GetPageSize()
w := &pdfWriter{f: f, o: o, width: pageW - 2*pdfMargin}
if strings.TrimSpace(title) != "" {
w.heading(title, 0, 22)
}
for _, n := range doc.Content {
w.block(n, 0, pdfGap)
}
var buf bytes.Buffer
if err := f.Output(&buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Layout, in millimetres and points.
const (
pdfMargin = 20.0
pdfGap = 3.0 // after a block
pdfTightGap = 1.2 // after a block in a list item
pdfBody = 11.0
pdfLine = 5.6
pdfIndent = 6.0
pdfTaskIndent = 8.0
pdfCellPad = 1.6
)
type pdfWriter struct {
f *fpdf.Fpdf
o PDFOptions
width float64
images int
quote int // depth of blockquotes, which grey the text
}
func (w *pdfWriter) at(indent float64) {
w.f.SetLeftMargin(pdfMargin + indent)
w.f.SetX(pdfMargin + indent)
}
func (w *pdfWriter) ink() {
if w.quote > 0 {
w.f.SetTextColor(95, 95, 95)
} else {
w.f.SetTextColor(25, 25, 25)
}
}
// link makes a document URL something a PDF reader can open, or "".
func (w *pdfWriter) link(href string) string {
href = w.o.file(href)
if strings.HasPrefix(href, "/") && !strings.HasPrefix(href, "//") {
if w.o.BaseURL == "" {
return ""
}
href = strings.TrimRight(w.o.BaseURL, "/") + href
}
if !safeURL.MatchString(href) || strings.HasPrefix(href, "#") {
return ""
}
return href
}
// room starts a new page unless h millimetres fit on this one.
func (w *pdfWriter) room(h float64) {
_, pageH := w.f.GetPageSize()
if w.f.GetY()+h > pageH-pdfMargin {
w.f.AddPage()
}
}
func (w *pdfWriter) heading(text string, level int, size float64) {
w.room(size*0.35 + 3*pdfLine)
w.at(0)
if level > 0 && w.f.GetY() > pdfMargin+1 {
w.f.Ln(2)
}
text = strings.TrimSpace(pdfText(text))
w.f.Bookmark(text, max(level-1, 0), -1)
w.f.SetFont("go", "B", size)
w.ink()
w.f.MultiCell(w.width, size*0.45, text, "", "L", false)
w.f.Ln(pdfGap)
}
var pdfHeadingSize = map[int]float64{1: 18, 2: 15, 3: 13, 4: 12, 5: 11, 6: 10}
func (w *pdfWriter) block(n Node, indent, gap float64) {
switch n.Type {
case "paragraph":
w.at(indent)
if a := alignOf(n); a != "" {
// fpdf aligns whole cells only, so aligned text loses its inline formatting.
w.f.SetFont("go", "", pdfBody)
w.ink()
w.f.MultiCell(w.width-indent, pdfLine, pdfText(PlainText(n)), "", strings.ToUpper(a[:1]), false)
} else {
w.inline(n.Content, "", pdfBody)
w.f.Ln(pdfLine)
}
w.f.Ln(gap)
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
w.heading(PlainText(n), level, pdfHeadingSize[level])
case "taskList":
for i, item := range n.Content {
marker := "[ ]"
if item.Attrs["checked"] == true {
marker = "[x]"
}
w.room(pdfLine)
w.at(indent)
w.f.SetFont("mono", "", pdfBody-1)
w.ink()
w.f.CellFormat(pdfTaskIndent, pdfLine, marker, "", 0, "L", false, 0, "")
for j, c := range item.Content {
g := pdfTightGap
if j == len(item.Content)-1 && i == len(n.Content)-1 {
g = gap
}
if j == 0 && c.Type == "paragraph" {
w.f.SetLeftMargin(pdfMargin + indent + pdfTaskIndent)
w.inline(c.Content, "", pdfBody)
w.f.Ln(pdfLine)
w.f.Ln(g)
continue
}
if j == 0 {
w.f.Ln(pdfLine)
}
w.block(c, indent+pdfTaskIndent, g)
}
if len(item.Content) == 0 {
w.f.Ln(pdfLine)
}
}
case "callout":
// A quote-like bar in the callout's colour; the Go fonts have no emoji.
_, color := calloutParts(n)
page, top := w.f.PageNo(), w.f.GetY()
for i, c := range n.Content {
g := pdfTightGap
if i == len(n.Content)-1 {
g = 0
}
w.block(c, indent+pdfIndent, g)
}
if w.f.PageNo() != page {
top = pdfMargin
}
r, g, b := rgb(paletteText[color])
w.f.SetDrawColor(r, g, b)
w.f.SetLineWidth(1.2)
x := pdfMargin + indent + 1.5
w.f.Line(x, top, x, w.f.GetY())
w.f.Ln(gap)
case "table":
w.table(n, indent)
w.f.Ln(gap)
case "bulletList", "orderedList":
start := n.intAttr("start", 1)
for i, item := range n.Content {
marker := "•"
if n.Type == "orderedList" {
marker = strconv.Itoa(start+i) + "."
}
w.room(pdfLine)
w.at(indent)
w.f.SetFont("go", "", pdfBody)
w.ink()
w.f.CellFormat(pdfIndent, pdfLine, marker, "", 0, "L", false, 0, "")
for j, c := range item.Content {
g := pdfTightGap
if j == len(item.Content)-1 && i == len(n.Content)-1 {
g = gap
}
if j == 0 && c.Type == "paragraph" {
// Text starts after the marker, on its line.
w.f.SetLeftMargin(pdfMargin + indent + pdfIndent)
w.inline(c.Content, "", pdfBody)
w.f.Ln(pdfLine)
w.f.Ln(g)
continue
}
if j == 0 {
w.f.Ln(pdfLine)
}
w.block(c, indent+pdfIndent, g)
}
if len(item.Content) == 0 {
w.f.Ln(pdfLine)
}
}
case "blockquote":
page, top := w.f.PageNo(), w.f.GetY()
w.quote++
for i, c := range n.Content {
g := pdfTightGap
if i == len(n.Content)-1 {
g = 0
}
w.block(c, indent+pdfIndent, g)
}
w.quote--
if w.f.PageNo() != page {
top = pdfMargin
}
x := pdfMargin + indent + 1.5
w.f.SetDrawColor(200, 200, 200)
w.f.SetLineWidth(0.8)
w.f.Line(x, top, x, w.f.GetY())
w.f.Ln(gap)
case "codeBlock":
w.code(PlainText(n), indent, "")
w.f.Ln(gap)
case "mermaid":
w.code(n.attr("code"), indent, "Mermaid")
w.f.Ln(gap)
case "blockMath":
w.at(indent)
w.f.SetFont("mono", "", 10)
w.ink()
w.f.MultiCell(w.width-indent, pdfLine, pdfText(n.attr("latex")), "", "C", false)
w.f.Ln(gap)
case "horizontalRule":
w.room(4)
y := w.f.GetY() + 1.5
w.f.SetDrawColor(210, 210, 210)
w.f.SetLineWidth(0.3)
w.f.Line(pdfMargin+indent, y, pdfMargin+w.width, y)
w.f.SetY(y + 1.5)
w.f.Ln(gap)
case "image":
w.image(n.attr("src"), n.attr("alt"), indent)
w.f.Ln(gap)
case "drawio", "excalidraw":
label := "Draw.io diagram"
if n.Type == "excalidraw" {
label = "Excalidraw drawing"
}
w.note(label, n.attr("src"), indent)
w.f.Ln(gap)
case "fileAttachment":
w.note("Attachment: "+n.attr("name"), n.attr("url"), indent)
w.f.Ln(gap)
case "tableOfContents":
// PDF readers list the headings as bookmarks.
case "detailsSummary":
// Toggles are drawn open: the summary in bold, then what it hides.
w.at(indent)
w.inline(n.Content, "B", pdfBody)
w.f.Ln(pdfLine)
w.f.Ln(pdfTightGap)
case "embed", "linkCard":
title := n.attr("title")
if title == "" {
title = n.attr("url")
}
w.note(title, n.attr("url"), indent)
if d := n.attr("description"); d != "" {
w.at(indent)
w.f.SetFont("go", "", 10)
w.f.SetTextColor(120, 120, 120)
w.f.MultiCell(w.width-indent, pdfLine, pdfText(d), "", "L", false)
}
w.f.Ln(gap)
default:
for _, c := range n.Content {
w.block(c, indent, gap)
}
}
}
// inline writes text runs from the current position, wrapping at the
// current left margin.
func (w *pdfWriter) inline(nodes []Node, style string, size float64) {
for _, n := range nodes {
switch n.Type {
case "text":
family, st, href, color := "go", style, "", ""
for _, m := range n.Marks {
switch m.Type {
case "textColor":
color = paletteText[m.attr("color")]
case "bold":
st += "B"
case "italic":
st += "I"
case "underline":
st += "U"
case "strike":
st += "S"
case "code":
family = "mono"
case "link":
href = w.link(m.attr("href"))
}
}
fsize := size
if family == "mono" {
fsize = size - 1
}
if href != "" && !strings.Contains(st, "U") {
st += "U"
}
w.f.SetFont(family, pdfStyle(st), fsize)
if href != "" {
w.f.SetTextColor(37, 99, 235)
w.f.WriteLinkString(pdfLine, pdfText(n.Text), href)
} else {
w.ink()
if color != "" {
w.f.SetTextColor(rgb(color))
}
w.f.Write(pdfLine, pdfText(n.Text))
}
case "hardBreak":
w.f.Ln(pdfLine)
case "inlineMath":
w.f.SetFont("mono", pdfStyle(style), size-1)
w.ink()
w.f.Write(pdfLine, pdfText(n.attr("latex")))
case "mention":
w.f.SetFont("go", pdfStyle(style+"B"), size)
w.ink()
w.f.Write(pdfLine, pdfText("@"+mentionLabel(n)))
case "dateMention":
w.f.SetFont("go", pdfStyle(style+"B"), size)
w.ink()
w.f.Write(pdfLine, pdfText(n.attr("date")))
default:
w.inline(n.Content, style, size)
}
}
}
// pdfText keeps characters fpdf can encode: it panics past U+FFFF, and the
// Go fonts have no emoji anyway, so those are left out.
func pdfText(s string) string {
return strings.Map(func(r rune) rune {
if r > 0xFFFF || r == 0xFE0F {
return -1
}
return r
}, s)
}
// pdfStyle orders and deduplicates style letters the way fpdf wants them.
func pdfStyle(s string) string {
var out string
for _, c := range "BIUS" {
if strings.ContainsRune(s, c) {
out += string(c)
}
}
return out
}
// table draws a grid with each cell's text wrapped in its column; columns
// share the width evenly, and header cells are bold on a grey fill. A row
// that does not fit on the page starts a new one.
func (w *pdfWriter) table(n Node, indent float64) {
cols := 0
for _, row := range n.Content {
cols = max(cols, len(row.Content))
}
if cols == 0 {
return
}
colW := (w.width - indent) / float64(cols)
const lineH = 4.8
for _, row := range n.Content {
texts := make([][]string, cols)
lines := 1
for i, cell := range row.Content {
var parts []string
for _, b := range cell.Content {
if t := strings.TrimSpace(PlainText(b)); t != "" {
parts = append(parts, t)
}
}
style := ""
if cell.Type == "tableHeader" {
style = "B"
}
w.f.SetFont("go", style, pdfBody-1)
texts[i] = w.f.SplitText(pdfText(strings.Join(parts, "\n")), colW-2*pdfCellPad)
lines = max(lines, len(texts[i]))
}
h := float64(lines)*lineH + 2*pdfCellPad
w.room(h)
y := w.f.GetY()
for i := range cols {
x := pdfMargin + indent + float64(i)*colW
header := i < len(row.Content) && row.Content[i].Type == "tableHeader"
w.f.SetDrawColor(200, 200, 200)
w.f.SetLineWidth(0.2)
if header {
w.f.SetFillColor(244, 244, 241)
w.f.Rect(x, y, colW, h, "FD")
w.f.SetFont("go", "B", pdfBody-1)
} else {
w.f.Rect(x, y, colW, h, "D")
w.f.SetFont("go", "", pdfBody-1)
}
w.ink()
for j, line := range texts[i] {
w.f.SetXY(x+pdfCellPad, y+pdfCellPad+float64(j)*lineH)
w.f.CellFormat(colW-2*pdfCellPad, lineH, line, "", 0, "L", false, 0, "")
}
}
w.f.SetXY(pdfMargin+indent, y+h)
}
}
func (w *pdfWriter) code(text string, indent float64, label string) {
w.at(indent)
if label != "" {
w.room(2 * pdfLine)
w.f.SetFont("go", "B", 8)
w.f.SetTextColor(130, 130, 130)
w.f.CellFormat(0, 4.5, label, "", 1, "L", false, 0, "")
w.at(indent)
}
w.f.SetFont("mono", "", 9.5)
w.ink()
w.f.SetFillColor(244, 244, 241)
text = pdfText(strings.ReplaceAll(text, "\t", " "))
if text == "" {
text = " "
}
w.f.MultiCell(w.width-indent, 4.6, text, "", "L", true)
}
// note is a line of grey text standing in for something the PDF cannot
// show, linking to it where possible.
func (w *pdfWriter) note(text, href string, indent float64) {
text = pdfText(text)
w.at(indent)
w.f.SetFont("go", "I", 10)
if link := w.link(href); link != "" {
w.f.SetTextColor(37, 99, 235)
w.f.WriteLinkString(pdfLine, text, link)
} else {
w.f.SetTextColor(120, 120, 120)
w.f.Write(pdfLine, text)
}
w.f.Ln(pdfLine)
}
func (w *pdfWriter) image(src, alt string, indent float64) {
placeholder := func() {
text := "Image"
if alt != "" {
text += ": " + alt
}
w.note("["+text+"]", src, indent)
}
if w.o.Image == nil || src == "" {
placeholder()
return
}
data, err := w.o.Image(src)
if err != nil {
placeholder()
return
}
kind, body, px, py, err := pdfImage(data)
if err != nil {
placeholder()
return
}
_, pageH := w.f.GetPageSize()
// 96 pixels to the inch, shrunk to fit the column and a page.
iw, ih := float64(px)*25.4/96, float64(py)*25.4/96
if maxW := w.width - indent; iw > maxW {
iw, ih = maxW, ih*maxW/iw
}
if maxH := pageH - 2*pdfMargin - 10; ih > maxH {
iw, ih = iw*maxH/ih, maxH
}
w.room(ih)
w.images++
name := "img" + strconv.Itoa(w.images)
opts := fpdf.ImageOptions{ImageType: kind}
w.f.RegisterImageOptionsReader(name, opts, bytes.NewReader(body))
if w.f.Err() {
w.f.ClearError()
placeholder()
return
}
y := w.f.GetY()
w.f.ImageOptions(name, pdfMargin+indent, y, iw, ih, false, opts, 0, "")
w.f.SetY(y + ih)
}
// pdfImage checks an image and hands JPEGs through as they are; other
// formats (PNG, GIF, WebP) are drawn again as plain 8-bit PNGs, which fpdf
// always reads (it refuses interlaced and 16-bit PNGs).
func pdfImage(data []byte) (kind string, body []byte, w, h int, err error) {
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return "", nil, 0, 0, err
}
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width*cfg.Height > maxPDFImagePixels {
return "", nil, 0, 0, fmt.Errorf("image is %dx%d", cfg.Width, cfg.Height)
}
if format == "jpeg" {
return "JPG", data, cfg.Width, cfg.Height, nil
}
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return "", nil, 0, 0, err
}
rgba := image.NewNRGBA(img.Bounds())
draw.Draw(rgba, rgba.Bounds(), img, img.Bounds().Min, draw.Src)
var buf bytes.Buffer
if err := png.Encode(&buf, rgba); err != nil {
return "", nil, 0, 0, err
}
return "PNG", buf.Bytes(), cfg.Width, cfg.Height, nil
}