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