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