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