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
++) {
161 sprintf(buf
, "\n%d", i
);
164 objtext(font
, i
% 8 ?
"/" : "\n/");
165 objtext(font
, fe
->vector
[i
]);
169 objtext(font
, "\n]\n>>\n");
171 #define FF_FIXEDPITCH 0x00000001
172 #define FF_SERIF 0x00000002
173 #define FF_SYMBOLIC 0x00000004
174 #define FF_SCRIPT 0x00000008
175 #define FF_NONSYMBOLIC 0x00000020
176 #define FF_ITALIC 0x00000040
177 #define FF_ALLCAP 0x00010000
178 #define FF_SMALLCAP 0x00020000
179 #define FF_FORCEBOLD 0x00040000
181 if (!is_std_font(fe
->font
->info
->name
)){
182 object
*widths
= new_object(&olist
);
183 object
*fontdesc
= new_object(&olist
);
184 int firstchar
= -1, lastchar
= -1;
186 font_info
const *fi
= fe
->font
->info
;
188 for (i
= 0; i
< 256; i
++)
189 if (fe
->indices
[i
] >= 0) {
190 if (firstchar
< 0) firstchar
= i
;
193 sprintf(buf
, "/FirstChar %d\n/LastChar %d\n/Widths ",
194 firstchar
, lastchar
);
196 objref(font
, widths
);
198 objtext(widths
, "[\n");
199 for (i
= firstchar
; i
<= lastchar
; i
++) {
201 if (fe
->indices
[i
] < 0)
204 width
= fi
->widths
[fe
->indices
[i
]];
205 sprintf(buf
, "%g\n", 1000.0 * width
/ FUNITS_PER_PT
);
206 objtext(widths
, buf
);
208 objtext(widths
, "]\n");
209 objtext(font
, "/FontDescriptor ");
210 objref(font
, fontdesc
);
211 objtext(fontdesc
, "<<\n/Type /FontDescriptor\n/Name /");
212 objtext(fontdesc
, fi
->name
);
214 if (fi
->italicangle
) flags
|= FF_ITALIC
;
215 flags
|= FF_NONSYMBOLIC
;
216 sprintf(buf
, "\n/Flags %d\n", flags
);
217 objtext(fontdesc
, buf
);
218 sprintf(buf
, "/FontBBox [%g %g %g %g]\n", fi
->fontbbox
[0],
219 fi
->fontbbox
[1], fi
->fontbbox
[2], fi
->fontbbox
[3]);
220 objtext(fontdesc
, buf
);
221 sprintf(buf
, "/ItalicAngle %g\n", fi
->italicangle
);
222 objtext(fontdesc
, buf
);
223 sprintf(buf
, "/Ascent %g\n", fi
->ascent
);
224 objtext(fontdesc
, buf
);
225 sprintf(buf
, "/Descent %g\n", fi
->descent
);
226 objtext(fontdesc
, buf
);
227 sprintf(buf
, "/CapHeight %g\n", fi
->capheight
);
228 objtext(fontdesc
, buf
);
229 sprintf(buf
, "/XHeight %g\n", fi
->xheight
);
230 objtext(fontdesc
, buf
);
231 sprintf(buf
, "/StemH %g\n", fi
->stemh
);
232 objtext(fontdesc
, buf
);
233 sprintf(buf
, "/StemV %g\n", fi
->stemv
);
234 objtext(fontdesc
, buf
);
236 object
*fontfile
= new_object(&olist
);
241 len
= fread(buf
, 1, sizeof(buf
)-1, fi
->fp
);
243 objstream(fontfile
, buf
);
244 } while (len
== sizeof(buf
)-1);
245 objtext(fontdesc
, "/FontFile ");
246 objref(fontdesc
, fontfile
);
248 objtext(fontdesc
, "\n>>\n");
251 objtext(font
, "\n>>\n");
253 objtext(resources
, ">>\n>>\n");
257 mediabox
= new_object(&olist
);
258 sprintf(buf
, "[0 0 %g %g]\n",
259 doc
->paper_width
/ FUNITS_PER_PT
,
260 doc
->paper_height
/ FUNITS_PER_PT
);
261 objtext(mediabox
, buf
);
265 * Define the page objects for each page, and get each one
266 * ready to have a `Parent' specification added to it.
268 for (page
= doc
->pages
; page
; page
= page
->next
) {
271 opage
= new_object(&olist
);
273 objtext(opage
, "<<\n/Type /Page\n");
277 * Recursively build the page tree.
279 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
, mediabox
);
282 * Create and render the individual pages.
285 for (page
= doc
->pages
; page
; page
= page
->next
) {
286 object
*opage
, *cstr
;
288 text_fragment
*frag
, *frag_end
;
292 opage
= (object
*)page
->spare
;
294 * At this point the page dictionary is already
295 * half-written, with /Type and /Parent already present. We
296 * continue from there.
300 * The PDF spec says /Resources is required, but also says
301 * that it's inheritable and may be omitted if it's present
302 * in a Pages node. In our case it is: it's present in the
303 * topmost /Pages node because we carefully put it there.
304 * So we don't need a /Resources entry here. The same applies
309 * Now we're ready to define a content stream containing
310 * the actual text on the page.
312 cstr
= new_object(&olist
);
313 objtext(opage
, "/Contents ");
315 objtext(opage
, "\n");
318 * Render any rectangles on the page.
320 for (r
= page
->first_rect
; r
; r
= r
->next
) {
322 sprintf(buf
, "%g %g %g %g re f\n",
323 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
324 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
325 objstream(cstr
, buf
);
328 objstream(cstr
, "BT\n");
331 * PDF tracks two separate current positions: the position
332 * given in the `line matrix' and the position given in the
333 * `text matrix'. We must therefore track both as well.
334 * They start off at -1 (unset).
339 frag
= page
->first_text
;
342 * For compactness, I'm going to group text fragments
343 * into subsequences that use the same font+size. So
344 * first find the end of this subsequence.
346 for (frag_end
= frag
;
348 frag_end
->fe
== frag
->fe
&&
349 frag_end
->fontsize
== frag
->fontsize
);
350 frag_end
= frag_end
->next
);
353 * Now select the text fragment, and prepare to display
356 objstream(cstr
, "/");
357 objstream(cstr
, frag
->fe
->name
);
358 sprintf(buf
, " %d Tf ", frag
->fontsize
);
359 objstream(cstr
, buf
);
361 while (frag
&& frag
!= frag_end
) {
363 * Place the text position for the first piece of
367 sprintf(buf
, "1 0 0 1 %g %g Tm ",
368 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
370 sprintf(buf
, "%g %g Td ",
371 (frag
->x
- lx
)/FUNITS_PER_PT
,
372 (frag
->y
- ly
)/FUNITS_PER_PT
);
374 objstream(cstr
, buf
);
379 * See if we're going to use Tj (show a single
380 * string) or TJ (show an array of strings with
381 * x-spacings between them). We determine this by
382 * seeing if there's more than one text fragment in
383 * sequence with the same y-coordinate.
385 if (frag
->next
&& frag
->next
!= frag_end
&&
386 frag
->next
->y
== y
) {
390 objstream(cstr
, "[");
391 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
394 (x
- frag
->x
) * 1000.0 /
395 (FUNITS_PER_PT
* frag
->fontsize
));
396 objstream(cstr
, buf
);
398 pdf_string(objstream
, cstr
, frag
->text
);
399 x
= frag
->x
+ frag
->width
;
402 objstream(cstr
, "]TJ\n");
408 pdf_string(objstream
, cstr
, frag
->text
);
409 objstream(cstr
, "Tj\n");
414 objstream(cstr
, "ET");
417 * Also, we want an annotation dictionary containing the
418 * cross-references from this page.
420 if (page
->first_xref
) {
422 objtext(opage
, "/Annots [\n");
424 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
428 annot
= new_object(&olist
);
429 objref(opage
, annot
);
430 objtext(opage
, "\n");
432 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
433 sprintf(buf
, "%g %g %g %g",
434 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
435 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
437 objtext(annot
, "]\n/Border [0 0 0]\n");
439 if (xr
->dest
.type
== PAGE
) {
440 objtext(annot
, "/Dest [");
441 objref(annot
, (object
*)xr
->dest
.page
->spare
);
442 objtext(annot
, " /XYZ null null null]\n");
444 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
445 pdf_string(objtext
, annot
, xr
->dest
.url
);
446 objtext(annot
, "\n>>\n");
449 objtext(annot
, ">>\n");
452 objtext(opage
, "]\n");
455 objtext(opage
, ">>\n");
459 * Set up the outlines dictionary.
465 objtext(outlines
, "<<\n/Type /Outlines\n");
466 topcount
= make_outline(outlines
, doc
->outline_elements
,
467 doc
->n_outline_elements
, TRUE
);
468 sprintf(buf
, "/Count %d\n>>\n", topcount
);
469 objtext(outlines
, buf
);
473 * Assemble the final linear form of every object.
475 for (o
= olist
.head
; o
; o
= o
->next
) {
476 rdstringc rs
= {0, 0, NULL
};
479 sprintf(text
, "%d 0 obj\n", o
->number
);
482 if (!o
->main
.text
&& o
->stream
.text
) {
483 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
484 rdaddsc(&o
->main
, text
);
487 assert(o
->main
.text
);
488 rdaddsc(&rs
, o
->main
.text
);
491 if (rs
.text
[rs
.pos
-1] != '\n')
494 if (o
->stream
.text
) {
496 * FIXME: If we ever start compressing stream data then
497 * it will have zero bytes in it, so we'll have to be
498 * more careful than this.
500 rdaddsc(&rs
, "stream\n");
501 rdaddsc(&rs
, o
->stream
.text
);
502 rdaddsc(&rs
, "\nendstream\n");
503 sfree(o
->stream
.text
);
506 rdaddsc(&rs
, "endobj\n");
513 * Write out the PDF file.
516 fp
= fopen(filename
, "wb");
518 error(err_cantopenw
, filename
);
523 * Header. I'm going to put the version IDs in the header as
524 * well, simply in PDF comments.
526 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
527 for (p
= sourceform
; p
; p
= p
->next
)
528 if (p
->type
== para_VersionID
)
529 fileoff
+= pdf_versionid(fp
, p
->words
);
534 for (o
= olist
.head
; o
; o
= o
->next
) {
535 o
->fileoff
= fileoff
;
536 fwrite(o
->final
, 1, o
->size
, fp
);
541 * Cross-reference table
543 fprintf(fp
, "xref\n");
544 assert(olist
.head
->number
== 1);
545 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
546 fprintf(fp
, "0000000000 65535 f \n");
547 for (o
= olist
.head
; o
; o
= o
->next
) {
549 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
550 assert(strlen(entry
) == 20);
557 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n",
558 olist
.tail
->number
+ 1, cat
->number
, info
->number
);
559 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
566 static object
*new_object(objlist
*list
)
568 object
*obj
= snew(object
);
572 obj
->main
.text
= NULL
;
573 obj
->main
.pos
= obj
->main
.size
= 0;
574 obj
->stream
.text
= NULL
;
575 obj
->stream
.pos
= obj
->stream
.size
= 0;
577 obj
->number
= list
->number
++;
581 list
->tail
->next
= obj
;
592 static void objtext(object
*o
, char const *text
)
594 rdaddsc(&o
->main
, text
);
597 static void objstream(object
*o
, char const *text
)
599 rdaddsc(&o
->stream
, text
);
602 static void objref(object
*o
, object
*dest
)
605 sprintf(buf
, "%d 0 R", dest
->number
);
606 rdaddsc(&o
->main
, buf
);
609 static char const * const stdfonts
[] = {
610 "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",
611 "Helvetica", "Helvetica-Bold", "Helvetica-Oblique","Helvetica-BoldOblique",
612 "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique",
613 "Symbol", "ZapfDingbats"
616 static int is_std_font(char const *name
) {
618 for (i
= 0; i
< lenof(stdfonts
); i
++)
619 if (strcmp(name
, stdfonts
[i
]) == 0)
624 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
625 page_data
*last
, object
*resources
,
632 objtext(node
, "<<\n/Type /Pages\n");
634 objtext(node
, "/Parent ");
635 objref(node
, parent
);
640 * Count the pages in this stretch, to see if there are few
641 * enough to reference directly.
644 for (page
= first
; page
; page
= page
->next
) {
650 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
653 if (count
> TREE_BRANCH
) {
655 page_data
*thisfirst
, *thislast
;
659 for (i
= 0; i
< TREE_BRANCH
; i
++) {
660 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
667 if (thisfirst
== thislast
) {
668 objref(node
, (object
*)thisfirst
->spare
);
669 objtext((object
*)thisfirst
->spare
, "/Parent ");
670 objref((object
*)thisfirst
->spare
, node
);
671 objtext((object
*)thisfirst
->spare
, "\n");
673 object
*newnode
= new_object(node
->list
);
674 make_pages_node(newnode
, node
, thisfirst
, thislast
,
676 objref(node
, newnode
);
681 assert(thislast
== last
|| page
== NULL
);
684 for (page
= first
; page
; page
= page
->next
) {
685 objref(node
, (object
*)page
->spare
);
687 objtext((object
*)page
->spare
, "/Parent ");
688 objref((object
*)page
->spare
, node
);
689 objtext((object
*)page
->spare
, "\n");
695 objtext(node
, "]\n");
698 objtext(node
, "/Resources ");
699 objref(node
, resources
);
703 objtext(node
, "/MediaBox ");
704 objref(node
, mediabox
);
708 objtext(node
, ">>\n");
712 * In text on the page, PDF uses the PostScript font model, which
713 * means that glyphs are identified by PS strings and hence font
714 * encoding can be managed independently of the supplied encoding
715 * of the font. However, in the document outline, the PDF spec
716 * encodes in either PDFDocEncoding (a custom superset of
717 * ISO-8859-1) or UTF-16BE.
719 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
722 ret
= utoa_careful_dup(s
, CS_PDF
);
725 * Very silly special case: if the returned string begins with
726 * FE FF, then the PDF reader will mistake it for a UTF-16BE
727 * string. So in this case we give up on PDFDocEncoding and
728 * encode it in UTF-16 straight away.
730 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
736 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
744 static int make_outline(object
*parent
, outline_element
*items
, int n
,
747 int level
, totalcount
= 0;
748 outline_element
*itemp
;
749 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
753 level
= items
->level
;
760 * Here we expect to be sitting on an item at the given
761 * level. So we start by constructing an outline entry for
764 assert(items
->level
== level
);
766 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
769 curr
= new_object(parent
->list
);
770 if (!first
) first
= curr
;
772 objtext(curr
, "<<\n/Title ");
773 pdf_string_len(objtext
, curr
, title
, titlelen
);
775 objtext(curr
, "\n/Parent ");
776 objref(curr
, parent
);
777 objtext(curr
, "\n/Dest [");
778 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
779 objtext(curr
, " /XYZ null null null]\n");
781 objtext(curr
, "/Prev ");
785 objtext(prev
, "/Next ");
787 objtext(prev
, "\n>>\n");
792 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
797 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
802 sprintf(buf
, "/Count %d\n", count
);
809 objtext(prev
, ">>\n");
811 assert(first
&& last
);
812 objtext(parent
, "/First ");
813 objref(parent
, first
);
814 objtext(parent
, "\n/Last ");
815 objref(parent
, last
);
816 objtext(parent
, "\n");
821 static int pdf_versionid(FILE *fp
, word
*words
)
825 ret
= fprintf(fp
, "%% ");
827 for (; words
; words
= words
->next
) {
831 switch (words
->type
) {
841 type
= removeattr(words
->type
);
845 text
= utoa_dup(words
->text
, CS_ASCII
);
847 case word_WhiteSpace
:
860 ret
+= fprintf(fp
, "\n");
865 static void pdf_string_len(void (*add
)(object
*, char const *),
866 object
*o
, char const *str
, int len
)
871 for (p
= str
; len
> 0; p
++, len
--) {
873 if (*p
< ' ' || *p
> '~') {
874 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
877 if (*p
== '\\' || *p
== '(' || *p
== ')')
887 static void pdf_string(void (*add
)(object
*, char const *),
888 object
*o
, char const *str
)
890 pdf_string_len(add
, o
, str
, strlen(str
));