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