All measurements in the paper backend are now configurable, as are
[sgt/halibut] / bk_pdf.c
CommitLineData
43341922 1/*
2 * PDF backend for Halibut
3 */
4
5#include <assert.h>
6#include "halibut.h"
7#include "paper.h"
8
9#define TREE_BRANCH 2 /* max branching factor in page tree */
10
11paragraph *pdf_config_filename(char *filename)
12{
e4ea58f8 13 return cmdline_cfg_simple("pdf-filename", filename, NULL);
43341922 14}
15
16typedef struct object_Tag object;
17typedef struct objlist_Tag objlist;
18
19struct object_Tag {
20 objlist *list;
21 object *next;
22 int number;
23 rdstringc main, stream;
24 int size, fileoff;
25 char *final;
26};
27
28struct objlist_Tag {
29 int number;
30 object *head, *tail;
31};
32
33static object *new_object(objlist *list);
34static void objtext(object *o, char const *text);
35static void objstream(object *o, char const *text);
7c8c4239 36static void pdf_string(void (*add)(object *, char const *),
37 object *, char const *);
ce1b04aa 38static void pdf_string_len(void (*add)(object *, char const *),
39 object *, char const *, int);
43341922 40static void objref(object *o, object *dest);
41
42static void make_pages_node(object *node, object *parent, page_data *first,
43 page_data *last, object *resources);
f0e51ce1 44static int make_outline(object *parent, outline_element *start, int n,
45 int open);
09358aa7 46static int pdf_versionid(FILE *fp, word *words);
43341922 47
48void pdf_backend(paragraph *sourceform, keywordlist *keywords,
49 indexdata *idx, void *vdoc) {
50 document *doc = (document *)vdoc;
51 int font_index;
52 font_encoding *fe;
53 page_data *page;
54 int pageno;
55 FILE *fp;
56 char *filename;
57 paragraph *p;
58 objlist olist;
59 object *o, *cat, *outlines, *pages, *resources;
60 int fileoff;
61
62 IGNORE(keywords);
63 IGNORE(idx);
64
65 filename = dupstr("output.pdf");
66 for (p = sourceform; p; p = p->next) {
43341922 67 if (p->type == para_Config && p->parent) {
68 if (!ustricmp(p->keyword, L"pdf-filename")) {
69 sfree(filename);
e4ea58f8 70 filename = dupstr(adv(p->origkeyword));
43341922 71 }
72 }
73 }
74
75 olist.head = olist.tail = NULL;
76 olist.number = 1;
77
78 cat = new_object(&olist);
79 outlines = new_object(&olist);
80 pages = new_object(&olist);
81 resources = new_object(&olist);
82
83 /*
43341922 84 * The catalogue just contains references to the outlines and
85 * pages objects.
86 */
87 objtext(cat, "<<\n/Type /Catalog\n/Outlines ");
88 objref(cat, outlines);
89 objtext(cat, "\n/Pages ");
90 objref(cat, pages);
f0e51ce1 91 objtext(cat, "\n/PageMode /UseOutlines\n>>\n");
43341922 92
93 /*
94 * Set up the resources dictionary, which mostly means
95 * providing all the font objects and names to call them by.
96 */
97 font_index = 0;
98 objtext(resources, "<<\n/Font <<\n");
99 for (fe = doc->fonts->head; fe; fe = fe->next) {
100 char fname[40];
101 int i;
102 object *font;
103
104 sprintf(fname, "f%d", font_index++);
105 fe->name = dupstr(fname);
106
107 font = new_object(&olist);
108
109 objtext(resources, "/");
110 objtext(resources, fe->name);
111 objtext(resources, " ");
112 objref(resources, font);
113 objtext(resources, "\n");
114
115 objtext(font, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
116 objtext(font, fe->name);
117 objtext(font, "\n/BaseFont /");
118 objtext(font, fe->font->name);
119 objtext(font, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
120
121 for (i = 0; i < 256; i++) {
122 char buf[20];
123 if (!fe->vector[i])
124 continue;
125 sprintf(buf, "\n%d /", i);
126 objtext(font, buf);
127 objtext(font, fe->vector[i] ? fe->vector[i] : ".notdef");
128 }
129
130 objtext(font, "\n]\n>>\n");
131
132 {
133 object *widths = new_object(&olist);
134 objtext(font, "/FirstChar 0\n/LastChar 255\n/Widths ");
135 objref(font, widths);
136 objtext(font, "\n");
137 objtext(widths, "[\n");
138 for (i = 0; i < 256; i++) {
139 char buf[80];
140 double width;
141 if (fe->indices[i] < 0)
142 width = 0.0;
143 else
144 width = fe->font->widths[fe->indices[i]];
145 sprintf(buf, "%g\n", 1000.0 * width / 4096.0);
146 objtext(widths, buf);
147 }
148 objtext(widths, "]\n");
149 }
150
151 objtext(font, ">>\n");
152 }
153 objtext(resources, ">>\n>>\n");
154
155 /*
156 * Define the page objects for each page, and get each one
157 * ready to have a `Parent' specification added to it.
158 */
159 for (page = doc->pages; page; page = page->next) {
160 object *opage;
161
162 opage = new_object(&olist);
163 page->spare = opage;
164 objtext(opage, "<<\n/Type /Page\n");
165 }
166
167 /*
168 * Recursively build the page tree.
169 */
170 make_pages_node(pages, NULL, doc->pages, NULL, resources);
171
172 /*
173 * Create and render the individual pages.
174 */
175 pageno = 0;
176 for (page = doc->pages; page; page = page->next) {
177 object *opage, *cstr;
23765aeb 178 rect *r;
7c8c4239 179 text_fragment *frag, *frag_end;
43341922 180 char buf[256];
7c8c4239 181 int x, y, lx, ly;
43341922 182
183 opage = (object *)page->spare;
184 /*
185 * At this point the page dictionary is already
186 * half-written, with /Type and /Parent already present. We
187 * continue from there.
188 */
189
190 /*
191 * The PDF spec says /Resources is required, but also says
192 * that it's inheritable and may be omitted if it's present
193 * in a Pages node. In our case it is: it's present in the
194 * topmost /Pages node because we carefully put it there.
195 * So we don't need a /Resources entry here.
196 */
197 sprintf(buf, "/MediaBox [0 0 %g %g]\n",
198 doc->paper_width / 4096.0, doc->paper_height / 4096.0);
199 objtext(opage, buf);
200
201 /*
202 * Now we're ready to define a content stream containing
203 * the actual text on the page.
204 */
205 cstr = new_object(&olist);
206 objtext(opage, "/Contents ");
207 objref(opage, cstr);
208 objtext(opage, "\n");
209
23765aeb 210 /*
211 * Render any rectangles on the page.
212 */
213 for (r = page->first_rect; r; r = r->next) {
214 char buf[512];
215 sprintf(buf, "%g %g %g %g re f\n", r->x / 4096.0,
216 r->y / 4096.0, r->w / 4096.0, r->h / 4096.0);
217 objstream(cstr, buf);
218 }
219
43341922 220 objstream(cstr, "BT\n");
43341922 221
7c8c4239 222 /*
223 * PDF tracks two separate current positions: the position
224 * given in the `line matrix' and the position given in the
225 * `text matrix'. We must therefore track both as well.
226 * They start off at -1 (unset).
227 */
228 lx = ly = -1;
229 x = y = -1;
230
231 frag = page->first_text;
232 while (frag) {
233 /*
234 * For compactness, I'm going to group text fragments
235 * into subsequences that use the same font+size. So
236 * first find the end of this subsequence.
237 */
238 for (frag_end = frag;
239 (frag_end &&
240 frag_end->fe == frag->fe &&
241 frag_end->fontsize == frag->fontsize);
242 frag_end = frag_end->next);
243
244 /*
245 * Now select the text fragment, and prepare to display
246 * the text.
247 */
43341922 248 objstream(cstr, "/");
249 objstream(cstr, frag->fe->name);
7c8c4239 250 sprintf(buf, " %d Tf ", frag->fontsize);
43341922 251 objstream(cstr, buf);
252
7c8c4239 253 while (frag && frag != frag_end) {
254 /*
255 * Place the text position for the first piece of
256 * text.
257 */
258 if (lx < 0) {
259 sprintf(buf, "1 0 0 1 %g %g Tm ",
260 frag->x/4096.0, frag->y/4096.0);
261 } else {
262 sprintf(buf, "%g %g Td ",
263 (frag->x - lx)/4096.0, (frag->y - ly)/4096.0);
264 }
43341922 265 objstream(cstr, buf);
7c8c4239 266 lx = x = frag->x;
267 ly = y = frag->y;
268
269 /*
270 * See if we're going to use Tj (show a single
271 * string) or TJ (show an array of strings with
272 * x-spacings between them). We determine this by
273 * seeing if there's more than one text fragment in
274 * sequence with the same y-coordinate.
275 */
276 if (frag->next && frag->next != frag_end &&
277 frag->next->y == y) {
278 /*
279 * The TJ strategy.
280 */
281 objstream(cstr, "[");
282 while (frag && frag != frag_end && frag->y == y) {
283 if (frag->x != x) {
284 sprintf(buf, "%g",
285 (x - frag->x) * 1000.0 /
286 (4096.0 * frag->fontsize));
287 objstream(cstr, buf);
288 }
289 pdf_string(objstream, cstr, frag->text);
290 x = frag->x + frag->width;
291 frag = frag->next;
292 }
293 objstream(cstr, "]TJ\n");
294 } else
295 {
296 /*
297 * The Tj strategy.
298 */
299 pdf_string(objstream, cstr, frag->text);
300 objstream(cstr, "Tj\n");
301 frag = frag->next;
302 }
43341922 303 }
43341922 304 }
305 objstream(cstr, "ET");
306
138d7ffb 307 /*
308 * Also, we want an annotation dictionary containing the
309 * cross-references from this page.
310 */
311 if (page->first_xref) {
312 xref *xr;
313 objtext(opage, "/Annots [\n");
314
315 for (xr = page->first_xref; xr; xr = xr->next) {
316 object *annot;
317 char buf[256];
318
319 annot = new_object(&olist);
320 objref(opage, annot);
321 objtext(opage, "\n");
322
323 objtext(annot, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
324 sprintf(buf, "%g %g %g %g",
325 xr->lx / 4096.0, xr->by / 4096.0,
326 xr->rx / 4096.0, xr->ty / 4096.0);
327 objtext(annot, buf);
328 objtext(annot, "]\n/Border [0 0 0]\n");
329
330 if (xr->dest.type == PAGE) {
331 objtext(annot, "/Dest [");
332 objref(annot, (object *)xr->dest.page->spare);
333 objtext(annot, " /XYZ null null null]\n");
334 } else {
7c8c4239 335 objtext(annot, "/A <<\n/Type /Action\n/S /URI\n/URI ");
336 pdf_string(objtext, annot, xr->dest.url);
337 objtext(annot, "\n>>\n");
138d7ffb 338 }
339
340 objtext(annot, ">>\n");
341 }
342
343 objtext(opage, "]\n");
344 }
345
43341922 346 objtext(opage, ">>\n");
347 }
348
349 /*
f0e51ce1 350 * Set up the outlines dictionary.
351 */
352 {
353 int topcount;
354 char buf[80];
355
356 objtext(outlines, "<<\n/Type /Outlines\n");
357 topcount = make_outline(outlines, doc->outline_elements,
358 doc->n_outline_elements, TRUE);
359 sprintf(buf, "/Count %d\n>>\n", topcount);
360 objtext(outlines, buf);
361 }
362
363 /*
43341922 364 * Assemble the final linear form of every object.
365 */
366 for (o = olist.head; o; o = o->next) {
367 rdstringc rs = {0, 0, NULL};
368 char text[80];
369
370 sprintf(text, "%d 0 obj\n", o->number);
371 rdaddsc(&rs, text);
372
373 if (!o->main.text && o->stream.text) {
374 sprintf(text, "<<\n/Length %d\n>>\n", o->stream.pos);
375 rdaddsc(&o->main, text);
376 }
377
378 assert(o->main.text);
379 rdaddsc(&rs, o->main.text);
380 sfree(o->main.text);
381
382 if (rs.text[rs.pos-1] != '\n')
383 rdaddc(&rs, '\n');
384
385 if (o->stream.text) {
386 /*
387 * FIXME: If we ever start compressing stream data then
388 * it will have zero bytes in it, so we'll have to be
389 * more careful than this.
390 */
391 rdaddsc(&rs, "stream\n");
392 rdaddsc(&rs, o->stream.text);
393 rdaddsc(&rs, "\nendstream\n");
394 sfree(o->stream.text);
395 }
396
397 rdaddsc(&rs, "endobj\n");
398
399 o->final = rs.text;
400 o->size = rs.pos;
401 }
402
403 /*
404 * Write out the PDF file.
405 */
406
407 fp = fopen(filename, "wb");
408 if (!fp) {
409 error(err_cantopenw, filename);
410 return;
411 }
412
413 /*
09358aa7 414 * Header. I'm going to put the version IDs in the header as
415 * well, simply in PDF comments.
43341922 416 */
417 fileoff = fprintf(fp, "%%PDF-1.3\n");
09358aa7 418 for (p = sourceform; p; p = p->next)
419 if (p->type == para_VersionID)
420 fileoff += pdf_versionid(fp, p->words);
43341922 421
422 /*
423 * Body
424 */
425 for (o = olist.head; o; o = o->next) {
426 o->fileoff = fileoff;
427 fwrite(o->final, 1, o->size, fp);
428 fileoff += o->size;
429 }
430
431 /*
432 * Cross-reference table
433 */
434 fprintf(fp, "xref\n");
435 assert(olist.head->number == 1);
436 fprintf(fp, "0 %d\n", olist.tail->number + 1);
437 fprintf(fp, "0000000000 65535 f \n");
438 for (o = olist.head; o; o = o->next) {
439 char entry[40];
440 sprintf(entry, "%010d 00000 n \n", o->fileoff);
441 assert(strlen(entry) == 20);
442 fputs(entry, fp);
443 }
444
445 /*
446 * Trailer
447 */
448 fprintf(fp, "trailer\n<<\n/Size %d\n/Root %d 0 R\n>>\n",
449 olist.tail->number + 1, cat->number);
450 fprintf(fp, "startxref\n%d\n%%%%EOF\n", fileoff);
451
452 fclose(fp);
453
454 sfree(filename);
455}
456
457static object *new_object(objlist *list)
458{
459 object *obj = mknew(object);
460
461 obj->list = list;
462
463 obj->main.text = NULL;
464 obj->main.pos = obj->main.size = 0;
465 obj->stream.text = NULL;
466 obj->stream.pos = obj->stream.size = 0;
467
468 obj->number = list->number++;
469
470 obj->next = NULL;
471 if (list->tail)
472 list->tail->next = obj;
473 else
474 list->head = obj;
475 list->tail = obj;
476
477 obj->size = 0;
478 obj->final = NULL;
479
480 return obj;
481}
482
483static void objtext(object *o, char const *text)
484{
485 rdaddsc(&o->main, text);
486}
487
488static void objstream(object *o, char const *text)
489{
490 rdaddsc(&o->stream, text);
491}
492
493static void objref(object *o, object *dest)
494{
495 char buf[40];
496 sprintf(buf, "%d 0 R", dest->number);
497 rdaddsc(&o->main, buf);
498}
499
500static void make_pages_node(object *node, object *parent, page_data *first,
501 page_data *last, object *resources)
502{
503 int count;
504 page_data *page;
505 char buf[80];
506
507 objtext(node, "<<\n/Type /Pages\n");
508 if (parent) {
509 objtext(node, "/Parent ");
510 objref(node, parent);
511 objtext(node, "\n");
512 }
513
514 /*
515 * Count the pages in this stretch, to see if there are few
516 * enough to reference directly.
517 */
518 count = 0;
519 for (page = first; page; page = page->next) {
520 count++;
521 if (page == last)
522 break;
523 }
524
525 sprintf(buf, "/Count %d\n/Kids [\n", count);
526 objtext(node, buf);
527
528 if (count > TREE_BRANCH) {
529 int i;
530 page_data *thisfirst, *thislast;
531
532 page = first;
533
534 for (i = 0; i < TREE_BRANCH; i++) {
535 int number = (i+1) * count / TREE_BRANCH - i * count / TREE_BRANCH;
536 thisfirst = page;
537 while (number--) {
538 thislast = page;
539 page = page->next;
540 }
541
542 if (thisfirst == thislast) {
543 objref(node, (object *)thisfirst->spare);
544 objtext((object *)thisfirst->spare, "/Parent ");
545 objref((object *)thisfirst->spare, node);
546 objtext((object *)thisfirst->spare, "\n");
547 } else {
548 object *newnode = new_object(node->list);
549 make_pages_node(newnode, node, thisfirst, thislast, NULL);
550 objref(node, newnode);
551 }
552 objtext(node, "\n");
553 }
554
555 assert(thislast == last || page == NULL);
556
557 } else {
558 for (page = first; page; page = page->next) {
559 objref(node, (object *)page->spare);
560 objtext(node, "\n");
561 objtext((object *)page->spare, "/Parent ");
562 objref((object *)page->spare, node);
563 objtext((object *)page->spare, "\n");
564 if (page == last)
565 break;
566 }
567 }
568
569 objtext(node, "]\n");
570
571 if (resources) {
572 objtext(node, "/Resources ");
573 objref(node, resources);
574 objtext(node, "\n");
575 }
576
577 objtext(node, ">>\n");
578}
f0e51ce1 579
580/*
581 * In text on the page, PDF uses the PostScript font model, which
582 * means that glyphs are identified by PS strings and hence font
583 * encoding can be managed independently of the supplied encoding
584 * of the font. However, in the document outline, the PDF spec
ce1b04aa 585 * encodes in either PDFDocEncoding (a custom superset of
586 * ISO-8859-1) or UTF-16BE.
f0e51ce1 587 */
ce1b04aa 588static char *pdf_outline_convert(wchar_t *s, int *len) {
589 char *ret;
590
591 ret = utoa_careful_dup(s, CS_PDF);
592
593 /*
594 * Very silly special case: if the returned string begins with
595 * FE FF, then the PDF reader will mistake it for a UTF-16BE
596 * string. So in this case we give up on PDFDocEncoding and
597 * encode it in UTF-16 straight away.
598 */
599 if (ret && ret[0] == '\xFE' && ret[1] == '\xFF') {
600 sfree(ret);
601 ret = NULL;
f0e51ce1 602 }
ce1b04aa 603
604 if (!ret) {
605 ret = utoa_dup_len(s, CS_UTF16BE, len);
606 } else {
607 *len = strlen(ret);
f0e51ce1 608 }
ce1b04aa 609
610 return ret;
f0e51ce1 611}
612
f0e51ce1 613static int make_outline(object *parent, outline_element *items, int n,
614 int open)
615{
616 int level, totalcount = 0;
617 outline_element *itemp;
618 object *curr, *prev = NULL, *first = NULL, *last = NULL;
f0e51ce1 619
620 assert(n > 0);
621
622 level = items->level;
623
624 while (n > 0) {
7c8c4239 625 char *title;
ce1b04aa 626 int titlelen;
f0e51ce1 627
628 /*
629 * Here we expect to be sitting on an item at the given
630 * level. So we start by constructing an outline entry for
631 * that item.
632 */
633 assert(items->level == level);
634
ce1b04aa 635 title = pdf_outline_convert(items->pdata->outline_title, &titlelen);
f0e51ce1 636
637 totalcount++;
638 curr = new_object(parent->list);
639 if (!first) first = curr;
640 last = curr;
7c8c4239 641 objtext(curr, "<<\n/Title ");
ce1b04aa 642 pdf_string_len(objtext, curr, title, titlelen);
7c8c4239 643 objtext(curr, "\n/Parent ");
f0e51ce1 644 objref(curr, parent);
645 objtext(curr, "\n/Dest [");
be76d597 646 objref(curr, (object *)items->pdata->first->page->spare);
f0e51ce1 647 objtext(curr, " /XYZ null null null]\n");
648 if (prev) {
649 objtext(curr, "/Prev ");
650 objref(curr, prev);
651 objtext(curr, "\n");
652
653 objtext(prev, "/Next ");
654 objref(prev, curr);
655 objtext(prev, "\n>>\n");
656 }
657 prev = curr;
658
659 items++, n--;
660 for (itemp = items; itemp < items+n && itemp->level > level;
661 itemp++);
662
663 if (itemp > items) {
664 char buf[80];
665 int count = make_outline(curr, items, itemp - items, FALSE);
666 if (!open)
667 count = -count;
668 else
669 totalcount += count;
670 sprintf(buf, "/Count %d\n", count);
671 objtext(curr, buf);
672 }
673
674 n -= itemp - items;
675 items = itemp;
676 }
677 objtext(prev, ">>\n");
678
679 assert(first && last);
680 objtext(parent, "/First ");
681 objref(parent, first);
682 objtext(parent, "\n/Last ");
683 objref(parent, last);
684 objtext(parent, "\n");
685
686 return totalcount;
687}
09358aa7 688
689static int pdf_versionid(FILE *fp, word *words)
690{
691 int ret;
692
693 ret = fprintf(fp, "%% ");
694
695 for (; words; words = words->next) {
696 char *text;
697 int type;
698
699 switch (words->type) {
700 case word_HyperLink:
701 case word_HyperEnd:
702 case word_UpperXref:
703 case word_LowerXref:
704 case word_XrefEnd:
705 case word_IndexRef:
706 continue;
707 }
708
709 type = removeattr(words->type);
710
711 switch (type) {
712 case word_Normal:
e4ea58f8 713 text = utoa_dup(words->text, CS_ASCII);
09358aa7 714 break;
715 case word_WhiteSpace:
716 text = dupstr(" ");
717 break;
718 case word_Quote:
719 text = dupstr("'");
720 break;
721 }
722
723 fputs(text, fp);
724 ret += strlen(text);
725 sfree(text);
726 }
727
728 ret += fprintf(fp, "\n");
729
730 return ret;
731}
7c8c4239 732
ce1b04aa 733static void pdf_string_len(void (*add)(object *, char const *),
734 object *o, char const *str, int len)
7c8c4239 735{
736 char const *p;
737
738 add(o, "(");
ce1b04aa 739 for (p = str; len > 0; p++, len--) {
740 char c[10];
741 if (*p < ' ' || *p > '~') {
742 sprintf(c, "\\%03o", 0xFF & (int)*p);
743 } else {
744 int n = 0;
745 if (*p == '\\' || *p == '(' || *p == ')')
746 c[n++] = '\\';
747 c[n++] = *p;
748 c[n] = '\0';
749 }
7c8c4239 750 add(o, c);
751 }
752 add(o, ")");
753}
ce1b04aa 754
755static void pdf_string(void (*add)(object *, char const *),
756 object *o, char const *str)
757{
758 pdf_string_len(add, o, str, strlen(str));
759}