feat(pdf): write simple text documents as PDF
Standard fonts with WinAnsi encoding cover German text without a dependency; output is checked with pdftotext where available. Refs #66 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
4182097542
commit
f892f7c03a
2 files changed
+251
No files matched your search
@@ -0,0 +1,195 @@
|
|||||||
|
// Package pdf writes simple text documents as PDF: headings, wrapped
|
||||||
|
// paragraphs and key–value lines on A4 pages.
|
||||||
|
//
|
||||||
|
// It uses the standard Helvetica and Courier fonts, which every PDF reader
|
||||||
|
// has built in, with WinAnsi encoding. That covers German and other Western
|
||||||
|
// European text; characters outside it print as "?".
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/text/encoding/charmap"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
pageWidth = 595.0
|
||||||
|
pageHeight = 842.0
|
||||||
|
margin = 50.0
|
||||||
|
bodySize = 9.0
|
||||||
|
lineHeight = 12.0
|
||||||
|
// Courier advances 0.6 em per character, which makes wrapping exact.
|
||||||
|
charWidth = 0.6 * bodySize
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxChars is how many Courier characters fit on a line.
|
||||||
|
const maxChars = 91
|
||||||
|
|
||||||
|
type font string
|
||||||
|
|
||||||
|
const (
|
||||||
|
regular font = "F1"
|
||||||
|
bold font = "F2"
|
||||||
|
mono font = "F3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Document collects pages; call Write to produce the file.
|
||||||
|
type Document struct {
|
||||||
|
title string
|
||||||
|
pages []*bytes.Buffer
|
||||||
|
y float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// New starts a document whose metadata title is title.
|
||||||
|
func New(title string) *Document {
|
||||||
|
d := &Document{title: title}
|
||||||
|
d.newPage()
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Document) newPage() {
|
||||||
|
d.pages = append(d.pages, &bytes.Buffer{})
|
||||||
|
d.y = pageHeight - margin
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Document) room(height float64) {
|
||||||
|
if d.y-height < margin {
|
||||||
|
d.newPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Document) text(f font, size float64, x float64, s string) {
|
||||||
|
fmt.Fprintf(d.pages[len(d.pages)-1], "BT /%s %.1f Tf %.1f %.1f Td (%s) Tj ET\n", f, size, x, d.y, escape(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title writes the document heading.
|
||||||
|
func (d *Document) Title(s string) {
|
||||||
|
d.room(30)
|
||||||
|
d.y -= 18
|
||||||
|
d.text(bold, 16, margin, s)
|
||||||
|
d.y -= 14
|
||||||
|
}
|
||||||
|
|
||||||
|
// Heading starts a section.
|
||||||
|
func (d *Document) Heading(s string) {
|
||||||
|
d.room(40)
|
||||||
|
d.y -= 16
|
||||||
|
d.text(bold, 11, margin, s)
|
||||||
|
d.y -= 6
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paragraph writes wrapped text.
|
||||||
|
func (d *Document) Paragraph(s string) {
|
||||||
|
for _, line := range wrap(s, maxChars) {
|
||||||
|
d.room(lineHeight)
|
||||||
|
d.y -= lineHeight
|
||||||
|
d.text(regular, bodySize, margin, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Field writes "key: value", indenting continuation lines of long values.
|
||||||
|
func (d *Document) Field(indent int, key, value string) {
|
||||||
|
pad := strings.Repeat(" ", indent)
|
||||||
|
lines := wrap(pad+key+": "+value, maxChars)
|
||||||
|
cont := strings.Repeat(" ", min(len(pad)+len(key)+2, maxChars/2))
|
||||||
|
for i, line := range lines {
|
||||||
|
if i > 0 {
|
||||||
|
line = cont + strings.TrimLeft(line, " ")
|
||||||
|
}
|
||||||
|
d.room(lineHeight)
|
||||||
|
d.y -= lineHeight
|
||||||
|
d.text(mono, bodySize, margin, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gap adds vertical space.
|
||||||
|
func (d *Document) Gap() { d.y -= lineHeight / 2 }
|
||||||
|
|
||||||
|
// wrap breaks s into lines of at most n characters, at spaces where
|
||||||
|
// possible. Existing line breaks are kept.
|
||||||
|
func wrap(s string, n int) []string {
|
||||||
|
var out []string
|
||||||
|
for _, para := range strings.Split(s, "\n") {
|
||||||
|
r := []rune(para)
|
||||||
|
for len(r) > n {
|
||||||
|
cut := n
|
||||||
|
for i := n; i > n/2; i-- {
|
||||||
|
if r[i] == ' ' {
|
||||||
|
cut = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, string(r[:cut]))
|
||||||
|
r = r[cut:]
|
||||||
|
if len(r) > 0 && r[0] == ' ' {
|
||||||
|
r = r[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, string(r))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
var encoder = charmap.Windows1252.NewEncoder()
|
||||||
|
|
||||||
|
// escape encodes s as WinAnsi and escapes PDF string delimiters.
|
||||||
|
func escape(s string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range s {
|
||||||
|
enc, err := encoder.String(string(r))
|
||||||
|
if err != nil || r < 0x20 {
|
||||||
|
enc = "?"
|
||||||
|
}
|
||||||
|
switch enc {
|
||||||
|
case "(", ")", `\`:
|
||||||
|
b.WriteByte('\\')
|
||||||
|
}
|
||||||
|
b.WriteString(enc)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write renders the document.
|
||||||
|
func (d *Document) Write(w io.Writer) error {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
var offsets []int
|
||||||
|
obj := func(body string) {
|
||||||
|
offsets = append(offsets, buf.Len())
|
||||||
|
fmt.Fprintf(&buf, "%d 0 obj\n%s\nendobj\n", len(offsets), body)
|
||||||
|
}
|
||||||
|
buf.WriteString("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
|
||||||
|
|
||||||
|
// Objects 1–5: catalog, page tree, fonts. Pages and contents follow
|
||||||
|
// in pairs from object 6.
|
||||||
|
n := len(d.pages)
|
||||||
|
kids := make([]string, n)
|
||||||
|
for i := range n {
|
||||||
|
kids[i] = fmt.Sprintf("%d 0 R", 6+2*i)
|
||||||
|
}
|
||||||
|
obj("<< /Type /Catalog /Pages 2 0 R >>")
|
||||||
|
obj(fmt.Sprintf("<< /Type /Pages /Kids [%s] /Count %d >>", strings.Join(kids, " "), n))
|
||||||
|
for _, f := range []string{"Helvetica", "Helvetica-Bold", "Courier"} {
|
||||||
|
obj("<< /Type /Font /Subtype /Type1 /BaseFont /" + f + " /Encoding /WinAnsiEncoding >>")
|
||||||
|
}
|
||||||
|
for i, p := range d.pages {
|
||||||
|
footer := fmt.Sprintf("BT /F1 8 Tf %.1f %.1f Td (%d / %d) Tj ET\n", pageWidth-margin-20, margin/2, i+1, n)
|
||||||
|
content := p.String() + footer
|
||||||
|
obj(fmt.Sprintf("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.0f %.0f] /Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R >> >> /Contents %d 0 R >>",
|
||||||
|
pageWidth, pageHeight, 7+2*i))
|
||||||
|
obj(fmt.Sprintf("<< /Length %d >>\nstream\n%sendstream", len(content), content))
|
||||||
|
}
|
||||||
|
obj(fmt.Sprintf("<< /Title (%s) /Producer (uptimesebi) >>", escape(d.title)))
|
||||||
|
info := len(offsets)
|
||||||
|
|
||||||
|
xref := buf.Len()
|
||||||
|
fmt.Fprintf(&buf, "xref\n0 %d\n0000000000 65535 f \n", len(offsets)+1)
|
||||||
|
for _, o := range offsets {
|
||||||
|
fmt.Fprintf(&buf, "%010d 00000 n \n", o)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&buf, "trailer\n<< /Size %d /Root 1 0 R /Info %d 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(offsets)+1, info, xref)
|
||||||
|
_, err := w.Write(buf.Bytes())
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWrap(t *testing.T) {
|
||||||
|
got := wrap("aaa bbb ccc", 7)
|
||||||
|
if strings.Join(got, "|") != "aaa bbb|ccc" {
|
||||||
|
t.Errorf("wrap() = %q", got)
|
||||||
|
}
|
||||||
|
if got := wrap(strings.Repeat("x", 10), 4); len(got) != 3 || got[0] != "xxxx" {
|
||||||
|
t.Errorf("wrap() of an unbreakable word = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEscape(t *testing.T) {
|
||||||
|
if got := escape(`Grüße (a\b) 漢`); got != "Gr\xfc\xdfe \\(a\\\\b\\) ?" {
|
||||||
|
t.Errorf("escape() = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDocumentIsReadable(t *testing.T) {
|
||||||
|
d := New("Export")
|
||||||
|
d.Title("Datenexport für Jörg")
|
||||||
|
for i := range 200 {
|
||||||
|
d.Heading("Abschnitt")
|
||||||
|
d.Field(1, "Schlüssel", strings.Repeat("Wert ", i%40))
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := d.Write(&buf); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(d.pages) < 2 {
|
||||||
|
t.Fatalf("200 sections fit on %d page", len(d.pages))
|
||||||
|
}
|
||||||
|
if !bytes.HasPrefix(buf.Bytes(), []byte("%PDF-1.4")) || !bytes.HasSuffix(buf.Bytes(), []byte("%%EOF\n")) {
|
||||||
|
t.Fatal("not a PDF file")
|
||||||
|
}
|
||||||
|
// Validate structure and text with poppler when available.
|
||||||
|
if _, err := exec.LookPath("pdftotext"); err != nil {
|
||||||
|
t.Skip("pdftotext not installed")
|
||||||
|
}
|
||||||
|
cmd := exec.Command("pdftotext", "-", "-")
|
||||||
|
cmd.Stdin = &buf
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pdftotext: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(out), "Datenexport für Jörg") || strings.Contains(string(out), "Syntax Error") {
|
||||||
|
t.Errorf("pdftotext output lacks the title or reports errors:\n%.300s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user