2 * PDF backend for Halibut
9 #define TREE_BRANCH 2 /* max branching factor in page tree */
11 paragraph
*pdf_config_filename(char *filename
)
13 return cmdline_cfg_simple("pdf-filename", filename
, NULL
);
16 typedef struct object_Tag object
;
17 typedef struct objlist_Tag objlist
;
23 rdstringc main
, stream
;
33 static object
*new_object(objlist
*list
);
34 static void objtext(object
*o
, char const *text
);
35 static void objstream(object
*o
, char const *text
);
36 static void pdf_string(void (*add
)(object
*, char const *),
37 object
*, char const *);
38 static void pdf_string_len(void (*add
)(object
*, char const *),
39 object
*, char const *, int);
40 static void objref(object
*o
, object
*dest
);
41 static char *pdf_outline_convert(wchar_t *s
, int *len
);
43 static int is_std_font(char const *name
);
45 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
46 page_data
*last
, object
*resources
,
48 static int make_outline(object
*parent
, outline_element
*start
, int n
,
50 static int pdf_versionid(FILE *fp
, word
*words
);
52 void pdf_backend(paragraph
*sourceform
, keywordlist
*keywords
,
53 indexdata
*idx
, void *vdoc
) {
54 document
*doc
= (document
*)vdoc
;
63 object
*o
, *info
, *cat
, *outlines
, *pages
, *resources
, *mediabox
;
69 filename
= dupstr("output.pdf");
70 for (p
= sourceform
; p
; p
= p
->next
) {
71 if (p
->type
== para_Config
) {
72 if (!ustricmp(p
->keyword
, L
"pdf-filename")) {
74 filename
= dupstr(adv(p
->origkeyword
));
79 olist
.head
= olist
.tail
= NULL
;
85 info
= new_object(&olist
);
86 objtext(info
, "<<\n");
87 if (doc
->n_outline_elements
> 0) {
92 pdf_outline_convert(doc
->outline_elements
->pdata
->outline_title
,
94 objtext(info
, "/Title ");
95 pdf_string_len(objtext
, info
, title
, titlelen
);
99 objtext(info
, "/Producer ");
100 sprintf(buf
, "Halibut, %s", version
);
101 pdf_string(objtext
, info
, buf
);
102 objtext(info
, "\n>>\n");
105 cat
= new_object(&olist
);
106 if (doc
->n_outline_elements
> 0)
107 outlines
= new_object(&olist
);
110 pages
= new_object(&olist
);
111 resources
= new_object(&olist
);
114 * The catalogue just contains references to the outlines and
117 objtext(cat
, "<<\n/Type /Catalog");
119 objtext(cat
, "\n/Outlines ");
120 objref(cat
, outlines
);
122 objtext(cat
, "\n/Pages ");
125 objtext(cat
, "\n/PageMode /UseOutlines");
126 objtext(cat
, "\n>>\n");
129 * Set up the resources dictionary, which mostly means
130 * providing all the font objects and names to call them by.
133 objtext(resources
, "<<\n/Font <<\n");
134 for (fe
= doc
->fonts
->head
; fe
; fe
= fe
->next
) {
139 sprintf(fname
, "f%d", font_index
++);
140 fe
->name
= dupstr(fname
);
142 font
= new_object(&olist
);
144 objtext(resources
, "/");
145 objtext(resources
, fe
->name
);
146 objtext(resources
, " ");
147 objref(resources
, font
);
148 objtext(resources
, "\n");
150 objtext(font
, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
151 objtext(font
, fe
->name
);
152 objtext(font
, "\n/BaseFont /");
153 objtext(font
, fe
->font
->info
->name
);
154 objtext(font
, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
156 for (i
= 0; i
< 256; i
++) {
160 sprintf(buf
, "\n%d /", i
);
162 objtext(font
, fe
->vector
[i
] ? fe
->vector
[i
] : ".notdef");
165 objtext(font
, "\n]\n>>\n");
167 #define FF_FIXEDPITCH 0x00000001
168 #define FF_SERIF 0x00000002
169 #define FF_SYMBOLIC 0x00000004
170 #define FF_SCRIPT 0x00000008
171 #define FF_NONSYMBOLIC 0x00000020
172 #define FF_ITALIC 0x00000040
173 #define FF_ALLCAP 0x00010000
174 #define FF_SMALLCAP 0x00020000
175 #define FF_FORCEBOLD 0x00040000
177 if (!is_std_font(fe
->font
->info
->name
)){
178 object
*widths
= new_object(&olist
);
179 object
*fontdesc
= new_object(&olist
);
180 int firstchar
= -1, lastchar
= -1;
182 font_info
const *fi
= fe
->font
->info
;
184 for (i
= 0; i
< 256; i
++)
185 if (fe
->indices
[i
] >= 0) {
186 if (firstchar
< 0) firstchar
= i
;
189 sprintf(buf
, "/FirstChar %d\n/LastChar %d\n/Widths ",
190 firstchar
, lastchar
);
192 objref(font
, widths
);
194 objtext(widths
, "[\n");
195 for (i
= firstchar
; i
<= lastchar
; i
++) {
197 if (fe
->indices
[i
] < 0)
200 width
= fi
->widths
[fe
->indices
[i
]];
201 sprintf(buf
, "%g\n", 1000.0 * width
/ FUNITS_PER_PT
);
202 objtext(widths
, buf
);
204 objtext(widths
, "]\n");
205 objtext(font
, "/FontDescriptor ");
206 objref(font
, fontdesc
);
207 objtext(fontdesc
, "<<\n/Type /FontDescriptor\n/Name /");
208 objtext(fontdesc
, fi
->name
);
210 if (fi
->italicangle
) flags
|= FF_ITALIC
;
211 flags
|= FF_NONSYMBOLIC
;
212 sprintf(buf
, "\n/Flags %d\n", flags
);
213 objtext(fontdesc
, buf
);
214 sprintf(buf
, "/FontBBox [%g %g %g %g]\n", fi
->fontbbox
[0],
215 fi
->fontbbox
[1], fi
->fontbbox
[2], fi
->fontbbox
[3]);
216 objtext(fontdesc
, buf
);
217 sprintf(buf
, "/ItalicAngle %g\n", fi
->italicangle
);
218 objtext(fontdesc
, buf
);
219 sprintf(buf
, "/Ascent %g\n", fi
->ascent
);
220 objtext(fontdesc
, buf
);
221 sprintf(buf
, "/Descent %g\n", fi
->descent
);
222 objtext(fontdesc
, buf
);
223 sprintf(buf
, "/CapHeight %g\n", fi
->capheight
);
224 objtext(fontdesc
, buf
);
225 sprintf(buf
, "/XHeight %g\n", fi
->xheight
);
226 objtext(fontdesc
, buf
);
227 sprintf(buf
, "/StemH %g\n", fi
->stemh
);
228 objtext(fontdesc
, buf
);
229 sprintf(buf
, "/StemV %g\n", fi
->stemv
);
230 objtext(fontdesc
, buf
);
232 object
*fontfile
= new_object(&olist
);
237 len
= fread(buf
, 1, sizeof(buf
)-1, fi
->fp
);
239 objstream(fontfile
, buf
);
240 } while (len
== sizeof(buf
)-1);
241 objtext(fontdesc
, "/FontFile ");
242 objref(fontdesc
, fontfile
);
244 objtext(fontdesc
, "\n>>\n");
247 objtext(font
, "\n>>\n");
249 objtext(resources
, ">>\n>>\n");
253 mediabox
= new_object(&olist
);
254 sprintf(buf
, "[0 0 %g %g]\n",
255 doc
->paper_width
/ FUNITS_PER_PT
,
256 doc
->paper_height
/ FUNITS_PER_PT
);
257 objtext(mediabox
, buf
);
261 * Define the page objects for each page, and get each one
262 * ready to have a `Parent' specification added to it.
264 for (page
= doc
->pages
; page
; page
= page
->next
) {
267 opage
= new_object(&olist
);
269 objtext(opage
, "<<\n/Type /Page\n");
273 * Recursively build the page tree.
275 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
, mediabox
);
278 * Create and render the individual pages.
281 for (page
= doc
->pages
; page
; page
= page
->next
) {
282 object
*opage
, *cstr
;
284 text_fragment
*frag
, *frag_end
;
288 opage
= (object
*)page
->spare
;
290 * At this point the page dictionary is already
291 * half-written, with /Type and /Parent already present. We
292 * continue from there.
296 * The PDF spec says /Resources is required, but also says
297 * that it's inheritable and may be omitted if it's present
298 * in a Pages node. In our case it is: it's present in the
299 * topmost /Pages node because we carefully put it there.
300 * So we don't need a /Resources entry here. The same applies
305 * Now we're ready to define a content stream containing
306 * the actual text on the page.
308 cstr
= new_object(&olist
);
309 objtext(opage
, "/Contents ");
311 objtext(opage
, "\n");
314 * Render any rectangles on the page.
316 for (r
= page
->first_rect
; r
; r
= r
->next
) {
318 sprintf(buf
, "%g %g %g %g re f\n",
319 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
320 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
321 objstream(cstr
, buf
);
324 objstream(cstr
, "BT\n");
327 * PDF tracks two separate current positions: the position
328 * given in the `line matrix' and the position given in the
329 * `text matrix'. We must therefore track both as well.
330 * They start off at -1 (unset).
335 frag
= page
->first_text
;
338 * For compactness, I'm going to group text fragments
339 * into subsequences that use the same font+size. So
340 * first find the end of this subsequence.
342 for (frag_end
= frag
;
344 frag_end
->fe
== frag
->fe
&&
345 frag_end
->fontsize
== frag
->fontsize
);
346 frag_end
= frag_end
->next
);
349 * Now select the text fragment, and prepare to display
352 objstream(cstr
, "/");
353 objstream(cstr
, frag
->fe
->name
);
354 sprintf(buf
, " %d Tf ", frag
->fontsize
);
355 objstream(cstr
, buf
);
357 while (frag
&& frag
!= frag_end
) {
359 * Place the text position for the first piece of
363 sprintf(buf
, "1 0 0 1 %g %g Tm ",
364 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
366 sprintf(buf
, "%g %g Td ",
367 (frag
->x
- lx
)/FUNITS_PER_PT
,
368 (frag
->y
- ly
)/FUNITS_PER_PT
);
370 objstream(cstr
, buf
);
375 * See if we're going to use Tj (show a single
376 * string) or TJ (show an array of strings with
377 * x-spacings between them). We determine this by
378 * seeing if there's more than one text fragment in
379 * sequence with the same y-coordinate.
381 if (frag
->next
&& frag
->next
!= frag_end
&&
382 frag
->next
->y
== y
) {
386 objstream(cstr
, "[");
387 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
390 (x
- frag
->x
) * 1000.0 /
391 (FUNITS_PER_PT
* frag
->fontsize
));
392 objstream(cstr
, buf
);
394 pdf_string(objstream
, cstr
, frag
->text
);
395 x
= frag
->x
+ frag
->width
;
398 objstream(cstr
, "]TJ\n");
404 pdf_string(objstream
, cstr
, frag
->text
);
405 objstream(cstr
, "Tj\n");
410 objstream(cstr
, "ET");
413 * Also, we want an annotation dictionary containing the
414 * cross-references from this page.
416 if (page
->first_xref
) {
418 objtext(opage
, "/Annots [\n");
420 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
424 annot
= new_object(&olist
);
425 objref(opage
, annot
);
426 objtext(opage
, "\n");
428 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
429 sprintf(buf
, "%g %g %g %g",
430 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
431 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
433 objtext(annot
, "]\n/Border [0 0 0]\n");
435 if (xr
->dest
.type
== PAGE
) {
436 objtext(annot
, "/Dest [");
437 objref(annot
, (object
*)xr
->dest
.page
->spare
);
438 objtext(annot
, " /XYZ null null null]\n");
440 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
441 pdf_string(objtext
, annot
, xr
->dest
.url
);
442 objtext(annot
, "\n>>\n");
445 objtext(annot
, ">>\n");
448 objtext(opage
, "]\n");
451 objtext(opage
, ">>\n");
455 * Set up the outlines dictionary.
461 objtext(outlines
, "<<\n/Type /Outlines\n");
462 topcount
= make_outline(outlines
, doc
->outline_elements
,
463 doc
->n_outline_elements
, TRUE
);
464 sprintf(buf
, "/Count %d\n>>\n", topcount
);
465 objtext(outlines
, buf
);
469 * Assemble the final linear form of every object.
471 for (o
= olist
.head
; o
; o
= o
->next
) {
472 rdstringc rs
= {0, 0, NULL
};
475 sprintf(text
, "%d 0 obj\n", o
->number
);
478 if (!o
->main
.text
&& o
->stream
.text
) {
479 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
480 rdaddsc(&o
->main
, text
);
483 assert(o
->main
.text
);
484 rdaddsc(&rs
, o
->main
.text
);
487 if (rs
.text
[rs
.pos
-1] != '\n')
490 if (o
->stream
.text
) {
492 * FIXME: If we ever start compressing stream data then
493 * it will have zero bytes in it, so we'll have to be
494 * more careful than this.
496 rdaddsc(&rs
, "stream\n");
497 rdaddsc(&rs
, o
->stream
.text
);
498 rdaddsc(&rs
, "\nendstream\n");
499 sfree(o
->stream
.text
);
502 rdaddsc(&rs
, "endobj\n");
509 * Write out the PDF file.
512 fp
= fopen(filename
, "wb");
514 error(err_cantopenw
, filename
);
519 * Header. I'm going to put the version IDs in the header as
520 * well, simply in PDF comments.
522 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
523 for (p
= sourceform
; p
; p
= p
->next
)
524 if (p
->type
== para_VersionID
)
525 fileoff
+= pdf_versionid(fp
, p
->words
);
530 for (o
= olist
.head
; o
; o
= o
->next
) {
531 o
->fileoff
= fileoff
;
532 fwrite(o
->final
, 1, o
->size
, fp
);
537 * Cross-reference table
539 fprintf(fp
, "xref\n");
540 assert(olist
.head
->number
== 1);
541 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
542 fprintf(fp
, "0000000000 65535 f \n");
543 for (o
= olist
.head
; o
; o
= o
->next
) {
545 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
546 assert(strlen(entry
) == 20);
553 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n",
554 olist
.tail
->number
+ 1, cat
->number
, info
->number
);
555 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
562 static object
*new_object(objlist
*list
)
564 object
*obj
= snew(object
);
568 obj
->main
.text
= NULL
;
569 obj
->main
.pos
= obj
->main
.size
= 0;
570 obj
->stream
.text
= NULL
;
571 obj
->stream
.pos
= obj
->stream
.size
= 0;
573 obj
->number
= list
->number
++;
577 list
->tail
->next
= obj
;
588 static void objtext(object
*o
, char const *text
)
590 rdaddsc(&o
->main
, text
);
593 static void objstream(object
*o
, char const *text
)
595 rdaddsc(&o
->stream
, text
);
598 static void objref(object
*o
, object
*dest
)
601 sprintf(buf
, "%d 0 R", dest
->number
);
602 rdaddsc(&o
->main
, buf
);
605 static char const * const stdfonts
[] = {
606 "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",
607 "Helvetica", "Helvetica-Bold", "Helvetica-Oblique","Helvetica-BoldOblique",
608 "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique",
609 "Symbol", "ZapfDingbats"
612 static int is_std_font(char const *name
) {
614 for (i
= 0; i
< lenof(stdfonts
); i
++)
615 if (strcmp(name
, stdfonts
[i
]) == 0)
620 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
621 page_data
*last
, object
*resources
,
628 objtext(node
, "<<\n/Type /Pages\n");
630 objtext(node
, "/Parent ");
631 objref(node
, parent
);
636 * Count the pages in this stretch, to see if there are few
637 * enough to reference directly.
640 for (page
= first
; page
; page
= page
->next
) {
646 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
649 if (count
> TREE_BRANCH
) {
651 page_data
*thisfirst
, *thislast
;
655 for (i
= 0; i
< TREE_BRANCH
; i
++) {
656 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
663 if (thisfirst
== thislast
) {
664 objref(node
, (object
*)thisfirst
->spare
);
665 objtext((object
*)thisfirst
->spare
, "/Parent ");
666 objref((object
*)thisfirst
->spare
, node
);
667 objtext((object
*)thisfirst
->spare
, "\n");
669 object
*newnode
= new_object(node
->list
);
670 make_pages_node(newnode
, node
, thisfirst
, thislast
,
672 objref(node
, newnode
);
677 assert(thislast
== last
|| page
== NULL
);
680 for (page
= first
; page
; page
= page
->next
) {
681 objref(node
, (object
*)page
->spare
);
683 objtext((object
*)page
->spare
, "/Parent ");
684 objref((object
*)page
->spare
, node
);
685 objtext((object
*)page
->spare
, "\n");
691 objtext(node
, "]\n");
694 objtext(node
, "/Resources ");
695 objref(node
, resources
);
699 objtext(node
, "/MediaBox ");
700 objref(node
, mediabox
);
704 objtext(node
, ">>\n");
708 * In text on the page, PDF uses the PostScript font model, which
709 * means that glyphs are identified by PS strings and hence font
710 * encoding can be managed independently of the supplied encoding
711 * of the font. However, in the document outline, the PDF spec
712 * encodes in either PDFDocEncoding (a custom superset of
713 * ISO-8859-1) or UTF-16BE.
715 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
718 ret
= utoa_careful_dup(s
, CS_PDF
);
721 * Very silly special case: if the returned string begins with
722 * FE FF, then the PDF reader will mistake it for a UTF-16BE
723 * string. So in this case we give up on PDFDocEncoding and
724 * encode it in UTF-16 straight away.
726 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
732 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
740 static int make_outline(object
*parent
, outline_element
*items
, int n
,
743 int level
, totalcount
= 0;
744 outline_element
*itemp
;
745 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
749 level
= items
->level
;
756 * Here we expect to be sitting on an item at the given
757 * level. So we start by constructing an outline entry for
760 assert(items
->level
== level
);
762 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
765 curr
= new_object(parent
->list
);
766 if (!first
) first
= curr
;
768 objtext(curr
, "<<\n/Title ");
769 pdf_string_len(objtext
, curr
, title
, titlelen
);
771 objtext(curr
, "\n/Parent ");
772 objref(curr
, parent
);
773 objtext(curr
, "\n/Dest [");
774 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
775 objtext(curr
, " /XYZ null null null]\n");
777 objtext(curr
, "/Prev ");
781 objtext(prev
, "/Next ");
783 objtext(prev
, "\n>>\n");
788 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
793 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
798 sprintf(buf
, "/Count %d\n", count
);
805 objtext(prev
, ">>\n");
807 assert(first
&& last
);
808 objtext(parent
, "/First ");
809 objref(parent
, first
);
810 objtext(parent
, "\n/Last ");
811 objref(parent
, last
);
812 objtext(parent
, "\n");
817 static int pdf_versionid(FILE *fp
, word
*words
)
821 ret
= fprintf(fp
, "%% ");
823 for (; words
; words
= words
->next
) {
827 switch (words
->type
) {
837 type
= removeattr(words
->type
);
841 text
= utoa_dup(words
->text
, CS_ASCII
);
843 case word_WhiteSpace
:
856 ret
+= fprintf(fp
, "\n");
861 static void pdf_string_len(void (*add
)(object
*, char const *),
862 object
*o
, char const *str
, int len
)
867 for (p
= str
; len
> 0; p
++, len
--) {
869 if (*p
< ' ' || *p
> '~') {
870 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
873 if (*p
== '\\' || *p
== '(' || *p
== ')')
883 static void pdf_string(void (*add
)(object
*, char const *),
884 object
*o
, char const *str
)
886 pdf_string_len(add
, o
, str
, strlen(str
));