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