// 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 ) // maxChars is how many Courier characters fit on a line: Courier advances // 0.6 em per character, which makes wrapping exact. 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 }