Browse Source

Add outline bookmarks to Office PDF exports

PDFs exported from Docs, Slides and Sheets now carry an outline (bookmarks) so readers can navigate them.

- Docs: headings h1-h6 (not the Title paragraph) become nested outline entries, both in the client-side exporter (docs.js, docs_pdf.js, pdfdraw.js) and the server-side Go exporter (mod/office/pdf/document.go). Each entry opens its page at the heading's top.
- Slides: one entry per slide, named by its title placeholder, else "Slide N".
- Sheets: one entry per sheet, named by sheet name, else "Sheet N".
- Go bookmark titles are encoded as UTF-16BE (pdfTextString), so non-Latin-1 scripts survive.
- Added outline_test.go covering nesting, skipped levels, page breaks, destinations, and encoding.
- Updated the AGI README, Office README and Terminal api.json.
Toby Chui 3 weeks ago
parent
commit
a0297c15ab

+ 6 - 4
src/mod/agi/README.md

@@ -1550,8 +1550,10 @@ bold/italic/underline/color/size/highlight, clickable links, lists, tables with
 column widths, cell shading and cell content (block text, lists and
 images inside cells), inline data-URL images, explicit page
 breaks, page size/orientation/margins, and header/footer text with
-optional page numbers. Core PDF fonts are Latin-1; characters outside
-that range are transliterated. Returns `true` on success.
+optional page numbers. The headings (`h1`-`h6`, not the Title paragraph)
+become the PDF's outline (bookmarks), nested by level. Core PDF fonts are
+Latin-1; characters outside that range are transliterated in the text
+(outline titles keep them). Returns `true` on success.
 
 ### `office.workbookPrintToPdf(printJson, destVpath)`
 Build a real-text PDF from a Sheets **print model** (not the raw
@@ -1559,8 +1561,8 @@ workbook JSON): `{"sheets":[{"name","colW":[px],"rowH":[px],"rows":
 [[{"t","b","i","u","fc","bg","al"}]]}]}` — formatted display strings
 plus print-relevant styles, computed by the web client (which owns
 formula evaluation). One A4-landscape section per sheet, columns scaled
-down to fit when the sheet is wider than the page. Returns `true` on
-success.
+down to fit when the sheet is wider than the page; each sheet is an entry
+of the PDF's outline (bookmarks). Returns `true` on success.
 
 ```javascript
 requirelib("office");

+ 64 - 3
src/mod/office/pdf/document.go

@@ -20,7 +20,9 @@ package pdf
 	Supported: paragraphs and headings, inline bold/italic/underline/color/
 	size/font, links (clickable), lists, tables (colgroup widths, cell
 	shading, rich cell content), inline images, explicit page breaks, page
-	geometry and header/footer text with optional page numbers.
+	geometry and header/footer text with optional page numbers. The
+	headings are the PDF's outline (bookmarks), as in the editor's own
+	export (docs/docs_pdf.js).
 */
 
 import (
@@ -97,6 +99,9 @@ type docPdf struct {
 	topY   float64 // first usable y on a page
 	botY   float64 // last usable y on a page
 	pre    bool    // inside <pre>: preserve whitespace
+	// heading levels of the outline entries a new one may nest under,
+	// outermost first
+	outline []int
 }
 
 // BuildDoc renders a Document into PDF bytes
@@ -327,12 +332,17 @@ func (d *docPdf) blockBox(n *html.Node, x, w float64) ([]pdfItem, float64, float
 		base := pdfSeg{b: true, i: n.Data == "h4", sizePt: sizes[n.Data]}
 		mt, mb := 14*ptToMM, 6*ptToMM
 		factor := 1.25
-		if strings.Contains(class, " doc-title ") {
+		title := strings.Contains(class, " doc-title ")
+		if title {
 			// .doc-title: 26pt, regular weight, margin 0 0 12pt
 			base = pdfSeg{sizePt: 26}
 			mt, mb = 0, 12*ptToMM
 		}
-		return d.paraItems(n, x, w, base, factor), mt, mb
+		items := d.paraItems(n, x, w, base, factor)
+		if !title {
+			d.bookmark(items, n, int(n.Data[1]-'0'))
+		}
+		return items, mt, mb
 	case "ul", "ol":
 		return d.listItems(n, x, w, n.Data == "ol")
 	case "table":
@@ -375,6 +385,57 @@ func (d *docPdf) blockBox(n *html.Node, x, w float64) ([]pdfItem, float64, float
 	}
 }
 
+// bookmark makes a heading an entry of the PDF outline, written with its
+// first line so it lands on the page the heading does. Entries nest by
+// level - a level 3 right after a level 1 goes under the 1 - which also
+// keeps fpdf's outline, whose depth may only grow one step at a time, well
+// formed. The Title paragraph is no heading, as in the table of contents.
+func (d *docPdf) bookmark(items []pdfItem, n *html.Node, level int) {
+	text := headingText(n)
+	if text == "" || len(items) == 0 {
+		return
+	}
+	for len(d.outline) > 0 && d.outline[len(d.outline)-1] >= level {
+		d.outline = d.outline[:len(d.outline)-1]
+	}
+	depth := len(d.outline)
+	d.outline = append(d.outline, level)
+	title := pdfTextString(text)
+	draw := items[0].draw
+	items[0].draw = func(y float64) {
+		d.pdf.Bookmark(title, depth, y)
+		if draw != nil {
+			draw(y)
+		}
+	}
+}
+
+// headingText is a heading's text on one line, without footnote markers
+func headingText(n *html.Node) string {
+	var sb strings.Builder
+	var walk func(*html.Node)
+	walk = func(x *html.Node) {
+		if x.Type == html.TextNode {
+			sb.WriteString(x.Data)
+			return
+		}
+		if x.Type == html.ElementNode {
+			if x.Data == "sup" && strings.Contains(" "+htmlutil.Attr(x, "class")+" ", " doc-fnref ") {
+				return
+			}
+			if x.Data == "br" {
+				sb.WriteString(" ")
+			}
+		}
+		for c := x.FirstChild; c != nil; c = c.NextSibling {
+			walk(c)
+		}
+	}
+	walk(n)
+	text := strings.ReplaceAll(sb.String(), string(rune(0x200B)), "")
+	return strings.Join(strings.Fields(text), " ")
+}
+
 // containerBox renders a wrapper element: its block children when it has
 // any, otherwise its inline content as one paragraph
 func (d *docPdf) containerBox(n *html.Node, x, w float64, base pdfSeg, bfc bool) ([]pdfItem, float64, float64) {

+ 223 - 0
src/mod/office/pdf/outline_test.go

@@ -0,0 +1,223 @@
+package pdf
+
+import (
+	"bytes"
+	"math"
+	"regexp"
+	"strconv"
+	"testing"
+	"unicode/utf16"
+
+	"imuslab.com/arozos/mod/office/model"
+)
+
+// outlineEntry is one bookmark read back from a PDF
+type outlineEntry struct {
+	title string
+	depth int     // 0 = top level
+	page  int     // 1-based
+	top   float64 // the /XYZ top of its destination, pt
+}
+
+var (
+	pdfObjRe    = regexp.MustCompile(`(?s)(\d+) 0 obj\s*(.*?)endobj`)
+	pdfParentRe = regexp.MustCompile(`/Parent (\d+) 0 R`)
+	pdfDestRe   = regexp.MustCompile(`/Dest \[(\d+) 0 R /XYZ [\d.]+ ([\d.]+) null\]`)
+)
+
+// pdfLiteral reads the PDF literal string that starts at s[0] == '(' and
+// decodes a UTF-16BE text string behind a byte order mark
+func pdfLiteral(t *testing.T, s []byte) string {
+	t.Helper()
+	var out []byte
+	for i := 1; i < len(s); i++ {
+		c := s[i]
+		if c == ')' {
+			if len(out) >= 2 && out[0] == 0xFE && out[1] == 0xFF {
+				u := make([]uint16, 0, len(out)/2)
+				for j := 2; j+1 < len(out); j += 2 {
+					u = append(u, uint16(out[j])<<8|uint16(out[j+1]))
+				}
+				return string(utf16.Decode(u))
+			}
+			return string(out)
+		}
+		if c == '\\' && i+1 < len(s) {
+			i++
+			switch s[i] {
+			case 'r':
+				out = append(out, '\r')
+			case 'n':
+				out = append(out, '\n')
+			default:
+				out = append(out, s[i])
+			}
+			continue
+		}
+		out = append(out, c)
+	}
+	t.Fatal("unterminated string in outline entry")
+	return ""
+}
+
+// pdfOutlineOf lists the outline entries of a PDF fpdf wrote, in order
+func pdfOutlineOf(t *testing.T, data []byte) []outlineEntry {
+	t.Helper()
+	objs := map[int][]byte{}
+	var order []int
+	pageNo := map[int]int{}
+	for _, m := range pdfObjRe.FindAllSubmatch(data, -1) {
+		n, _ := strconv.Atoi(string(m[1]))
+		objs[n] = m[2]
+		order = append(order, n)
+		if bytes.Contains(m[2], []byte("/Type /Page\n")) || bytes.Contains(m[2], []byte("/Type /Page ")) {
+			pageNo[n] = len(pageNo) + 1
+		}
+	}
+	var out []outlineEntry
+	for _, n := range order {
+		body := objs[n]
+		if !bytes.HasPrefix(body, []byte("<</Title (")) {
+			continue
+		}
+		e := outlineEntry{title: pdfLiteral(t, body[len("<</Title "):])}
+		for p := n; ; e.depth++ {
+			m := pdfParentRe.FindSubmatch(objs[p])
+			if m == nil {
+				t.Fatalf("outline entry %q has no parent chain", e.title)
+			}
+			p, _ = strconv.Atoi(string(m[1]))
+			if bytes.Contains(objs[p], []byte("/Type /Outlines")) {
+				break
+			}
+		}
+		if m := pdfDestRe.FindSubmatch(body); m != nil {
+			ref, _ := strconv.Atoi(string(m[1]))
+			e.page = pageNo[ref]
+			e.top, _ = strconv.ParseFloat(string(m[2]), 64)
+		}
+		out = append(out, e)
+	}
+	return out
+}
+
+func TestDocPdfOutline(t *testing.T) {
+	type want struct {
+		title string
+		depth int
+		page  int
+	}
+	cases := []struct {
+		name string
+		html string
+		want []want
+	}{
+		{"nests by level", `<h1>A</h1><h2>B</h2><h3>C</h3><h2>D</h2><h1>E</h1>`,
+			[]want{{"A", 0, 1}, {"B", 1, 1}, {"C", 2, 1}, {"D", 1, 1}, {"E", 0, 1}}},
+		{"skipped levels nest one step", `<h1>A</h1><h3>B</h3><h2>C</h2><h4>D</h4>`,
+			[]want{{"A", 0, 1}, {"B", 1, 1}, {"C", 1, 1}, {"D", 2, 1}}},
+		{"starts below level 1", `<h3>Intro</h3><h4>Detail</h4><h3>Features</h3>`,
+			[]want{{"Intro", 0, 1}, {"Detail", 1, 1}, {"Features", 0, 1}}},
+		{"title, empty headings and footnote markers",
+			`<h1 class="doc-title">Report</h1><h2> </h2><h2>Intro<sup class="doc-fnref">1</sup></h2>`,
+			[]want{{"Intro", 0, 1}}},
+		{"whitespace and line breaks", "<h2>Two\n   lines<br>here</h2>",
+			[]want{{"Two lines here", 0, 1}}},
+		{"any script", `<h1>系統概覽 (Overview)</h1><h2>Ünïcödé \ path</h2>`,
+			[]want{{"系統概覽 (Overview)", 0, 1}, {"Ünïcödé \\ path", 1, 1}}},
+		{"headings inside a table", `<table><tbody><tr><td><h2>In a cell</h2></td></tr></tbody></table>`,
+			[]want{{"In a cell", 0, 1}}},
+		{"follows page breaks", `<h1>One</h1><div class="doc-pagebreak"></div><h1>Two</h1><h2>Sub</h2>`,
+			[]want{{"One", 0, 1}, {"Two", 0, 2}, {"Sub", 1, 2}}},
+		{"no headings", `<p>Just text</p>`, nil},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			data, err := BuildDoc(&model.Document{HTML: tc.html})
+			if err != nil {
+				t.Fatalf("BuildDoc: %v", err)
+			}
+			got := pdfOutlineOf(t, data)
+			if len(got) != len(tc.want) {
+				t.Fatalf("got %d outline entries %+v, want %d", len(got), got, len(tc.want))
+			}
+			for i, w := range tc.want {
+				g := got[i]
+				if g.title != w.title || g.depth != w.depth || g.page != w.page {
+					t.Errorf("entry %d = %q depth %d page %d, want %q depth %d page %d",
+						i, g.title, g.depth, g.page, w.title, w.depth, w.page)
+				}
+			}
+			if tc.want == nil && bytes.Contains(data, []byte("/Outlines")) {
+				t.Errorf("a document without headings has an outline")
+			}
+		})
+	}
+}
+
+// a bookmark opens its page with the heading's line at the top of the view
+func TestDocPdfOutlineDestination(t *testing.T) {
+	data, err := BuildDoc(&model.Document{HTML: `<p>first</p><div class="doc-pagebreak"></div><h1>Top of page 2</h1>`})
+	if err != nil {
+		t.Fatalf("BuildDoc: %v", err)
+	}
+	got := pdfOutlineOf(t, data)
+	if len(got) != 1 {
+		t.Fatalf("got %d outline entries, want 1", len(got))
+	}
+	// A4, 25.4mm top margin, then the heading's 14pt margin-top, which
+	// applies again below a break: where its first line box starts
+	wantTop := (297.0-25.4)*72/25.4 - 14
+	if got[0].page != 2 || math.Abs(got[0].top-wantTop) > 0.5 {
+		t.Errorf("destination page %d top %.2f, want page 2 top %.2f", got[0].page, got[0].top, wantTop)
+	}
+}
+
+func TestSheetPdfOutline(t *testing.T) {
+	long := make([][]*SheetPrintCell, 40)
+	for i := range long {
+		long[i] = []*SheetPrintCell{{T: "row " + strconv.Itoa(i)}}
+	}
+	m := &SheetPrintModel{Sheets: []*SheetPrintSheet{
+		{Name: "Data", Rows: long},
+		{Name: "  ", Rows: [][]*SheetPrintCell{{{T: "x"}}}},
+		{Name: "總表  Summary"},
+	}}
+	data, err := BuildSheet(m)
+	if err != nil {
+		t.Fatalf("BuildSheet: %v", err)
+	}
+	got := pdfOutlineOf(t, data)
+	want := []outlineEntry{{title: "Data", page: 1}, {title: "Sheet 2", page: 3}, {title: "總表 Summary", page: 4}}
+	if pdfPageCount(data) != 4 {
+		// the first sheet's 40 rows run over two pages
+		t.Fatalf("got %d pages, want 4 (the first sheet runs over two)", pdfPageCount(data))
+	}
+	if len(got) != len(want) {
+		t.Fatalf("got %d outline entries %+v, want %d", len(got), got, len(want))
+	}
+	for i, w := range want {
+		if got[i].title != w.title || got[i].page != w.page || got[i].depth != 0 {
+			t.Errorf("entry %d = %q depth %d page %d, want %q depth 0 page %d",
+				i, got[i].title, got[i].depth, got[i].page, w.title, w.page)
+		}
+	}
+}
+
+func TestPdfTextString(t *testing.T) {
+	cases := []struct {
+		in   string
+		want []byte
+	}{
+		{"", []byte{0xFE, 0xFF}},
+		{"AB", []byte{0xFE, 0xFF, 0x00, 0x41, 0x00, 0x42}},
+		{"系", []byte{0xFE, 0xFF, 0x7C, 0xFB}},
+		// outside the BMP: a surrogate pair
+		{string(rune(0x20000)), []byte{0xFE, 0xFF, 0xD8, 0x40, 0xDC, 0x00}},
+	}
+	for _, tc := range cases {
+		if got := []byte(pdfTextString(tc.in)); !bytes.Equal(got, tc.want) {
+			t.Errorf("pdfTextString(%q) = % X, want % X", tc.in, got, tc.want)
+		}
+	}
+}

+ 15 - 0
src/mod/office/pdf/pdf.go

@@ -16,6 +16,7 @@ import (
 	"bytes"
 	"fmt"
 	"strings"
+	"unicode/utf16"
 
 	"github.com/go-pdf/fpdf"
 	"imuslab.com/arozos/mod/office/internal/htmlutil"
@@ -106,6 +107,20 @@ func pdfOutput(pdf *fpdf.Fpdf) ([]byte, error) {
 	return buf.Bytes(), nil
 }
 
+// pdfTextString encodes s as a PDF text string for metadata such as outline
+// titles: UTF-16BE behind a byte order mark, so any script survives. fpdf
+// writes the bytes of a Bookmark title as they are while a core font is
+// set, which is always the case here.
+func pdfTextString(s string) string {
+	u := utf16.Encode([]rune(s))
+	b := make([]byte, 2, 2+2*len(u))
+	b[0], b[1] = 0xFE, 0xFF
+	for _, c := range u {
+		b = append(b, byte(c>>8), byte(c))
+	}
+	return string(b)
+}
+
 // pdfNbsp normalizes non-breaking / typographic spaces to plain spaces:
 // contenteditable HTML is full of &nbsp;, and fpdf only wraps lines at
 // real spaces, so leaving them in causes early / mid-word line breaks

+ 11 - 2
src/mod/office/pdf/sheet.go

@@ -9,12 +9,15 @@ package pdf
 	(bold/italic/underline, font and fill colors, alignment) and the
 	column widths in CSS pixels. The server lays that grid out on A4
 	landscape pages, scaling the columns down when the sheet is wider
-	than the printable area and splitting rows across pages.
+	than the printable area and splitting rows across pages. Every sheet
+	is an entry of the PDF's outline (bookmarks), at its name heading.
 */
 
 import (
 	"encoding/json"
 	"errors"
+	"strconv"
+	"strings"
 
 	"github.com/go-pdf/fpdf"
 )
@@ -112,8 +115,14 @@ func BuildSheet(m *SheetPrintModel) ([]byte, error) {
 	pageW, pageH := pdf.GetPageSize()
 	usableW := pageW - 2*marginMM
 
-	for _, sheet := range m.Sheets {
+	for i, sheet := range m.Sheets {
 		pdf.AddPage()
+		// every sheet is an entry of the PDF outline, at its name heading
+		name := strings.Join(strings.Fields(sheet.Name), " ")
+		if name == "" {
+			name = "Sheet " + strconv.Itoa(i+1)
+		}
+		pdf.Bookmark(pdfTextString(name), 0, marginMM)
 		// sheet name heading
 		pdf.SetFont("Arial", "B", 12)
 		pdf.SetTextColor(31, 35, 40)

+ 9 - 1
src/web/Office/README.md

@@ -552,7 +552,15 @@ model allows) in its `.docx`, because there is only one layout:
   same `pdfdraw.js` runs in the page when a worker cannot be started.
   Progress shows in `OfficeApp.showProgress`, as in Slides, and the
   document can be edited meanwhile without changing the file that comes
-  out. Font resolution against the shipped Noto faces, text runs and the
+  out. The PDF always gets an **outline** (bookmarks) of the headings,
+  whether or not the document has a table of contents: the same headings
+  `tocEntries()` would list, at all six levels (the Title paragraph is no
+  heading), measured in the export state and written by `pdfdraw.js`
+  (`job.outline`, nested by level, each opening its page at the heading's
+  top). The other PDFs have one too: Slides lists every slide by its title
+  placeholder, else "Slide N" (`slideOutline` in `slides/slides_pdf.js`),
+  Sheets every sheet by name, and the server-side Docs exporter the same
+  headings (both in `mod/office/pdf`). Font resolution against the shipped Noto faces, text runs and the
   raster fallback live in [`common/pdfcore.js`](common/pdfcore.js), also
   used by Slides. `docs/backend/convert.agi`'s `export-pdf` and
   `mod/office/pdf/document.go` remain for AGI callers (`office.documentToPdf`),

+ 49 - 2
src/web/Office/common/pdfdraw.js

@@ -16,8 +16,10 @@
         {
           title, sheetW, sheetH,              // px (96/in)
           images: { id: { src } | { bytes } },  // data URL / URL, or JPEG/PNG bytes
-          pages: [ [op, ...], ... ]
-        }
+          pages: [ [op, ...], ... ],
+          outline: [ { title, level, page, y } ]   // optional bookmarks: level
+                                                   // 1-6, page index, y px
+        }                                          // from the page's top
     Coordinates are px from the page's top-left corner. Ops are arrays:
         ["rect", x, y, w, h, rgb, alpha]
         ["image", id, x, y, w, h, crop]       crop {t,r,b,l} fractions | null
@@ -405,11 +407,56 @@ var OfficePdfDraw = (function () {
             });
             return chain;
         }).then(function () {
+            if (job.outline && job.outline.length) writeOutline(pdfDoc, job.outline);
             if (opts.onProgress) opts.onProgress(total, total, "save");
             return pdfDoc.save({ objectsPerTick: 20 });
         });
     }
 
+    /* The document outline (bookmarks). Entries nest by level - a level 3
+       right after a level 1 goes under the 1 - and all start open; each
+       opens its page with the entry's y at the top of the view. */
+    function writeOutline(doc, items) {
+        var ctx = doc.context;
+        var pages = doc.getPages();
+        var root = { ref: ctx.nextRef(), level: 0, kids: [] };
+        var stack = [root];
+        items.forEach(function (it) {
+            var page = pages[it.page];
+            if (!page || !it.title) return;
+            while (stack.length > 1 && stack[stack.length - 1].level >= it.level) stack.pop();
+            var node = { ref: ctx.nextRef(), level: it.level, kids: [], it: it, page: page };
+            stack[stack.length - 1].kids.push(node);
+            stack.push(node);
+        });
+        if (!root.kids.length) return;
+        function count(n) {
+            return n.kids.reduce(function (sum, k) { return sum + 1 + count(k); }, 0);
+        }
+        function linkKids(n, dict) {
+            if (!n.kids.length) return dict;
+            dict.First = n.kids[0].ref;
+            dict.Last = n.kids[n.kids.length - 1].ref;
+            dict.Count = count(n);
+            return dict;
+        }
+        (function write(n) {
+            n.kids.forEach(function (k, i) {
+                var dict = {
+                    Title: PDFLib.PDFHexString.fromText(k.it.title),
+                    Parent: n.ref,
+                    Dest: [k.page.ref, "XYZ", null, k.page.getHeight() - (k.it.y || 0) * PX, null]
+                };
+                if (i > 0) dict.Prev = n.kids[i - 1].ref;
+                if (i < n.kids.length - 1) dict.Next = n.kids[i + 1].ref;
+                ctx.assign(k.ref, ctx.obj(linkKids(k, dict)));
+                write(k);
+            });
+        })(root);
+        ctx.assign(root.ref, ctx.obj(linkKids(root, { Type: "Outlines" })));
+        doc.catalog.set(PDFLib.PDFName.of("Outlines"), root.ref);
+    }
+
     /* ---------------- recording (in the page) ---------------- */
 
     function encodeArg(v) {

+ 9 - 0
src/web/Office/docs/docs.js

@@ -4812,6 +4812,14 @@
     function canExportPdf() {
         return typeof PDFLib !== "undefined" && !!window.DocsPdf;
     }
+    /* the PDF's outline (bookmarks): every heading the table of contents
+       would list at all six levels, whether or not the document has one,
+       and where it sits in #page */
+    function pdfOutline() {
+        return tocEntries([1, 2, 3, 4, 5, 6]).map(function (e) {
+            return { title: e.text, level: e.level, y: offsetTopInPage(e.el) };
+        });
+    }
     function renderPdf(onProgress) {
         var prevZoom = 100;
         var relaid = false;
@@ -4821,6 +4829,7 @@
             pages: function () { return lastPages; },
             sheetW: geo.sheetW, sheetH: geo.sheetH,
             title: exportBaseName(),
+            outline: pdfOutline,
             onProgress: onProgress,
             enter: function () {
                 clearFindHits();

+ 19 - 3
src/web/Office/docs/docs_pdf.js

@@ -26,8 +26,11 @@
     written down as a display list, and common/pdfworker.js (pdfdraw.js)
     assembles the file in a Web Worker while the document stays editable.
 
+    The headings become the PDF's outline (bookmarks), each pointing at the
+    top of the heading on its sheet.
+
     Usage:
-        DocsPdf.build({ pageEl, pages, sheetW, sheetH, title,
+        DocsPdf.build({ pageEl, pages, sheetW, sheetH, title, outline,
                         enter, leave, onProgress }) -> Promise<Uint8Array>
 */
 
@@ -446,8 +449,18 @@ var DocsPdf = (function () {
     /* displayList turns what collect() measured into the job pdfdraw.js
        draws: every coordinate relative to its own sheet, every colour a
        triple, every font a reference, every picture an entry of its own. */
+    // headings as bookmarks: the sheet each one is on and how far down it
+    function outlineOf(o) {
+        return (o.outline || []).map(function (h) {
+            var i = pageIndexOf(o.pages, o.sheetH, h.y);
+            return { title: h.title, level: h.level, page: i, y: Math.max(0, h.y - o.pages[i].sheetTop) };
+        });
+    }
     function displayList(o, data, fonts, frame) {
-        var job = { title: o.title || "", sheetW: o.sheetW, sheetH: o.sheetH, images: {}, pages: [] };
+        var job = {
+            title: o.title || "", sheetW: o.sheetW, sheetH: o.sheetH, images: {}, pages: [],
+            outline: outlineOf(o)
+        };
         var imageIds = new Map();
         var pending = [];
         var nextId = 0;
@@ -559,6 +572,8 @@ var DocsPdf = (function () {
          3. render    a worker turns the list into the file
 
        o: { pageEl, pages() | pages, sheetW, sheetH, title,
+            outline() -> [{ title, level, y }]   (y in #page px, read in
+                         the export state, so it matches the sheets)
             enter(), leave(), onProgress(done, total, stage) }
        stage is "measure", "prepare", "page" or "save". */
     function build(o) {
@@ -575,7 +590,8 @@ var DocsPdf = (function () {
                 snap = {
                     pageEl: o.pageEl,
                     pages: (typeof o.pages === "function" ? o.pages() : o.pages).slice(),
-                    sheetW: o.sheetW, sheetH: o.sheetH, title: o.title
+                    sheetW: o.sheetW, sheetH: o.sheetH, title: o.title,
+                    outline: o.outline ? o.outline() : []
                 };
                 if (!snap.pages.length) throw new Error("nothing to export");
                 data = collect(snap, new Frame(o.pageEl));

+ 25 - 1
src/web/Office/slides/slides_pdf.js

@@ -32,6 +32,9 @@
     Rasterizing is the documented last resort, never the first move, and it
     is always scoped to the one element that needs it.
 
+    Every slide is an entry of the PDF's outline (bookmarks), named by its
+    title placeholder, else "Slide N" (slideOutline).
+
     The font rule. A PDF can only show text in a font it carries, and the
     browser will not hand over the bytes of a system font. Three answers,
     tried in that order, per character:
@@ -945,6 +948,25 @@ var SlidesPdf = (function () {
         })));
     }
 
+    /* the PDF's outline (bookmarks): one entry per slide, named by its
+       title placeholder - an imported deck's title and centre title are one
+       too - else "Slide N" */
+    function slideOutline(slides) {
+        var parser = new DOMParser();
+        return slides.map(function (slide, i) {
+            var title = "";
+            (slide.objects || []).some(function (o) {
+                if (!o || !o.props || o.props.ph !== "title" || !o.props.html) return false;
+                // a line break or a new paragraph reads as a space
+                var html = String(o.props.html).replace(/<(br|\/p|\/div|\/li)\b/gi, " $&");
+                title = (parser.parseFromString(html, "text/html").body.textContent || "")
+                    .split(String.fromCharCode(0x200B)).join("").replace(/\s+/g, " ").trim();
+                return !!title;
+            });
+            return { title: title || "Slide " + (i + 1), level: 1, page: i, y: 0 };
+        });
+    }
+
     function build(body, opts) {
         opts = opts || {};
         if (typeof PDFLib === "undefined") {
@@ -1002,7 +1024,9 @@ var SlidesPdf = (function () {
                 });
             });
             return chain.then(function () {
-                return OfficePdfDraw.run(rec.job(opts.title), {
+                var job = rec.job(opts.title);
+                job.outline = slideOutline(slides);
+                return OfficePdfDraw.run(job, {
                     onProgress: opts.onProgress, loadFontkit: loadFontkit
                 });
             });

+ 2 - 2
src/web/Terminal/docs/api.json

@@ -1050,14 +1050,14 @@
         {
           "name": "office.documentToPdf",
           "sig": "office.documentToPdf(jsonStr, destVpath)",
-          "desc": "Build a PDF with real selectable text from a serialized Docs body JSON and write it to destVpath. Renders headings, inline styles, links, lists, tables, inline images, page breaks, page geometry and header/footer with page numbers. Latin-1 core fonts; other characters are transliterated.",
+          "desc": "Build a PDF with real selectable text from a serialized Docs body JSON and write it to destVpath. Renders headings, inline styles, links, lists, tables, inline images, page breaks, page geometry and header/footer with page numbers; the headings become the PDF outline (bookmarks). Latin-1 core fonts; other characters are transliterated.",
           "ret": "boolean",
           "example": "requirelib(\"office\");\nvar ok = office.documentToPdf(data, \"user:/Desktop/report.pdf\");\nsendResp(ok ? \"OK\" : \"failed\");"
         },
         {
           "name": "office.workbookPrintToPdf",
           "sig": "office.workbookPrintToPdf(printJson, destVpath)",
-          "desc": "Build a real-text PDF from a Sheets print model ({sheets:[{name,colW,rowH,rows:[[{t,b,i,u,fc,bg,al}]]}]}) - formatted display strings plus styles computed by the web client. One A4-landscape section per sheet, columns scaled to fit the page.",
+          "desc": "Build a real-text PDF from a Sheets print model ({sheets:[{name,colW,rowH,rows:[[{t,b,i,u,fc,bg,al}]]}]}) - formatted display strings plus styles computed by the web client. One A4-landscape section per sheet, columns scaled to fit the page; each sheet is a PDF outline entry (bookmark).",
           "ret": "boolean",
           "example": "requirelib(\"office\");\nvar ok = office.workbookPrintToPdf(printModelJson, \"user:/Desktop/sheet.pdf\");\nsendResp(ok ? \"OK\" : \"failed\");"
         },