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