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