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
115 * pages objects, and the pagelabels dictionary.
117 objtext(cat
, "<<\n/Type /Catalog");
119 objtext(cat
, "\n/Outlines ");
120 objref(cat
, outlines
);
122 objtext(cat
, "\n/Pages ");
124 /* Halibut just numbers pages 1, 2, 3, ... */
125 objtext(cat
, "\n/PageLabels<</Nums[0<</S/D>>]>>");
127 objtext(cat
, "\n/PageMode /UseOutlines");
128 objtext(cat
, "\n>>\n");
131 * Set up the resources dictionary, which mostly means
132 * providing all the font objects and names to call them by.
135 objtext(resources
, "<<\n/Font <<\n");
136 for (fe
= doc
->fonts
->head
; fe
; fe
= fe
->next
) {
141 sprintf(fname
, "f%d", font_index
++);
142 fe
->name
= dupstr(fname
);
144 font
= new_object(&olist
);
146 objtext(resources
, "/");
147 objtext(resources
, fe
->name
);
148 objtext(resources
, " ");
149 objref(resources
, font
);
150 objtext(resources
, "\n");
152 objtext(font
, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
153 objtext(font
, fe
->name
);
154 objtext(font
, "\n/BaseFont /");
155 objtext(font
, fe
->font
->info
->name
);
156 objtext(font
, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
158 for (i
= 0; i
< 256; i
++) {
163 sprintf(buf
, "\n%d", i
);
166 objtext(font
, i
% 8 ?
"/" : "\n/");
167 objtext(font
, fe
->vector
[i
]);
171 objtext(font
, "\n]\n>>\n");
173 #define FF_FIXEDPITCH 0x00000001
174 #define FF_SERIF 0x00000002
175 #define FF_SYMBOLIC 0x00000004
176 #define FF_SCRIPT 0x00000008
177 #define FF_NONSYMBOLIC 0x00000020
178 #define FF_ITALIC 0x00000040
179 #define FF_ALLCAP 0x00010000
180 #define FF_SMALLCAP 0x00020000
181 #define FF_FORCEBOLD 0x00040000
183 if (!is_std_font(fe
->font
->info
->name
)){
184 object
*widths
= new_object(&olist
);
185 object
*fontdesc
= new_object(&olist
);
186 int firstchar
= -1, lastchar
= -1;
188 font_info
const *fi
= fe
->font
->info
;
190 for (i
= 0; i
< 256; i
++)
191 if (fe
->indices
[i
] >= 0) {
192 if (firstchar
< 0) firstchar
= i
;
195 sprintf(buf
, "/FirstChar %d\n/LastChar %d\n/Widths ",
196 firstchar
, lastchar
);
198 objref(font
, widths
);
200 objtext(widths
, "[\n");
201 for (i
= firstchar
; i
<= lastchar
; i
++) {
203 if (fe
->indices
[i
] < 0)
206 width
= fi
->widths
[fe
->indices
[i
]];
207 sprintf(buf
, "%g\n", 1000.0 * width
/ FUNITS_PER_PT
);
208 objtext(widths
, buf
);
210 objtext(widths
, "]\n");
211 objtext(font
, "/FontDescriptor ");
212 objref(font
, fontdesc
);
213 objtext(fontdesc
, "<<\n/Type /FontDescriptor\n/Name /");
214 objtext(fontdesc
, fi
->name
);
216 if (fi
->italicangle
) flags
|= FF_ITALIC
;
217 flags
|= FF_NONSYMBOLIC
;
218 sprintf(buf
, "\n/Flags %d\n", flags
);
219 objtext(fontdesc
, buf
);
220 sprintf(buf
, "/FontBBox [%g %g %g %g]\n", fi
->fontbbox
[0],
221 fi
->fontbbox
[1], fi
->fontbbox
[2], fi
->fontbbox
[3]);
222 objtext(fontdesc
, buf
);
223 sprintf(buf
, "/ItalicAngle %g\n", fi
->italicangle
);
224 objtext(fontdesc
, buf
);
225 sprintf(buf
, "/Ascent %g\n", fi
->ascent
);
226 objtext(fontdesc
, buf
);
227 sprintf(buf
, "/Descent %g\n", fi
->descent
);
228 objtext(fontdesc
, buf
);
229 sprintf(buf
, "/CapHeight %g\n", fi
->capheight
);
230 objtext(fontdesc
, buf
);
231 sprintf(buf
, "/XHeight %g\n", fi
->xheight
);
232 objtext(fontdesc
, buf
);
233 sprintf(buf
, "/StemH %g\n", fi
->stemh
);
234 objtext(fontdesc
, buf
);
235 sprintf(buf
, "/StemV %g\n", fi
->stemv
);
236 objtext(fontdesc
, buf
);
238 object
*fontfile
= new_object(&olist
);
243 len
= fread(buf
, 1, sizeof(buf
)-1, fi
->fp
);
245 objstream(fontfile
, buf
);
246 } while (len
== sizeof(buf
)-1);
247 objtext(fontdesc
, "/FontFile ");
248 objref(fontdesc
, fontfile
);
250 objtext(fontdesc
, "\n>>\n");
253 objtext(font
, "\n>>\n");
255 objtext(resources
, ">>\n>>\n");
259 mediabox
= new_object(&olist
);
260 sprintf(buf
, "[0 0 %g %g]\n",
261 doc
->paper_width
/ FUNITS_PER_PT
,
262 doc
->paper_height
/ FUNITS_PER_PT
);
263 objtext(mediabox
, buf
);
267 * Define the page objects for each page, and get each one
268 * ready to have a `Parent' specification added to it.
270 for (page
= doc
->pages
; page
; page
= page
->next
) {
273 opage
= new_object(&olist
);
275 objtext(opage
, "<<\n/Type /Page\n");
279 * Recursively build the page tree.
281 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
, mediabox
);
284 * Create and render the individual pages.
287 for (page
= doc
->pages
; page
; page
= page
->next
) {
288 object
*opage
, *cstr
;
290 text_fragment
*frag
, *frag_end
;
294 opage
= (object
*)page
->spare
;
296 * At this point the page dictionary is already
297 * half-written, with /Type and /Parent already present. We
298 * continue from there.
302 * The PDF spec says /Resources is required, but also says
303 * that it's inheritable and may be omitted if it's present
304 * in a Pages node. In our case it is: it's present in the
305 * topmost /Pages node because we carefully put it there.
306 * So we don't need a /Resources entry here. The same applies
311 * Now we're ready to define a content stream containing
312 * the actual text on the page.
314 cstr
= new_object(&olist
);
315 objtext(opage
, "/Contents ");
317 objtext(opage
, "\n");
320 * Render any rectangles on the page.
322 for (r
= page
->first_rect
; r
; r
= r
->next
) {
324 sprintf(buf
, "%g %g %g %g re f\n",
325 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
326 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
327 objstream(cstr
, buf
);
330 objstream(cstr
, "BT\n");
333 * PDF tracks two separate current positions: the position
334 * given in the `line matrix' and the position given in the
335 * `text matrix'. We must therefore track both as well.
336 * They start off at -1 (unset).
341 frag
= page
->first_text
;
344 * For compactness, I'm going to group text fragments
345 * into subsequences that use the same font+size. So
346 * first find the end of this subsequence.
348 for (frag_end
= frag
;
350 frag_end
->fe
== frag
->fe
&&
351 frag_end
->fontsize
== frag
->fontsize
);
352 frag_end
= frag_end
->next
);
355 * Now select the text fragment, and prepare to display
358 objstream(cstr
, "/");
359 objstream(cstr
, frag
->fe
->name
);
360 sprintf(buf
, " %d Tf ", frag
->fontsize
);
361 objstream(cstr
, buf
);
363 while (frag
&& frag
!= frag_end
) {
365 * Place the text position for the first piece of
369 sprintf(buf
, "1 0 0 1 %g %g Tm ",
370 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
372 sprintf(buf
, "%g %g Td ",
373 (frag
->x
- lx
)/FUNITS_PER_PT
,
374 (frag
->y
- ly
)/FUNITS_PER_PT
);
376 objstream(cstr
, buf
);
381 * See if we're going to use Tj (show a single
382 * string) or TJ (show an array of strings with
383 * x-spacings between them). We determine this by
384 * seeing if there's more than one text fragment in
385 * sequence with the same y-coordinate.
387 if (frag
->next
&& frag
->next
!= frag_end
&&
388 frag
->next
->y
== y
) {
392 objstream(cstr
, "[");
393 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
396 (x
- frag
->x
) * 1000.0 /
397 (FUNITS_PER_PT
* frag
->fontsize
));
398 objstream(cstr
, buf
);
400 pdf_string(objstream
, cstr
, frag
->text
);
401 x
= frag
->x
+ frag
->width
;
404 objstream(cstr
, "]TJ\n");
410 pdf_string(objstream
, cstr
, frag
->text
);
411 objstream(cstr
, "Tj\n");
416 objstream(cstr
, "ET");
419 * Also, we want an annotation dictionary containing the
420 * cross-references from this page.
422 if (page
->first_xref
) {
424 objtext(opage
, "/Annots [\n");
426 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
429 objtext(opage
, "<</Subtype/Link\n/Rect[");
430 sprintf(buf
, "%g %g %g %g",
431 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
432 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
434 objtext(opage
, "]/Border[0 0 0]\n");
436 if (xr
->dest
.type
== PAGE
) {
437 objtext(opage
, "/Dest[");
438 objref(opage
, (object
*)xr
->dest
.page
->spare
);
439 objtext(opage
, "/XYZ null null null]");
441 objtext(opage
, "/A<</S/URI/URI");
442 pdf_string(objtext
, opage
, xr
->dest
.url
);
443 objtext(opage
, ">>");
446 objtext(opage
, ">>\n");
449 objtext(opage
, "]\n");
452 objtext(opage
, ">>\n");
456 * Set up the outlines dictionary.
462 objtext(outlines
, "<<\n/Type /Outlines\n");
463 topcount
= make_outline(outlines
, doc
->outline_elements
,
464 doc
->n_outline_elements
, TRUE
);
465 sprintf(buf
, "/Count %d\n>>\n", topcount
);
466 objtext(outlines
, buf
);
470 * Assemble the final linear form of every object.
472 for (o
= olist
.head
; o
; o
= o
->next
) {
473 rdstringc rs
= {0, 0, NULL
};
476 sprintf(text
, "%d 0 obj\n", o
->number
);
479 if (!o
->main
.text
&& o
->stream
.text
) {
480 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
481 rdaddsc(&o
->main
, text
);
484 assert(o
->main
.text
);
485 rdaddsc(&rs
, o
->main
.text
);
488 if (rs
.text
[rs
.pos
-1] != '\n')
491 if (o
->stream
.text
) {
493 * FIXME: If we ever start compressing stream data then
494 * it will have zero bytes in it, so we'll have to be
495 * more careful than this.
497 rdaddsc(&rs
, "stream\n");
498 rdaddsc(&rs
, o
->stream
.text
);
499 rdaddsc(&rs
, "\nendstream\n");
500 sfree(o
->stream
.text
);
503 rdaddsc(&rs
, "endobj\n");
510 * Write out the PDF file.
513 fp
= fopen(filename
, "wb");
515 error(err_cantopenw
, filename
);
520 * Header. I'm going to put the version IDs in the header as
521 * well, simply in PDF comments.
523 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
524 for (p
= sourceform
; p
; p
= p
->next
)
525 if (p
->type
== para_VersionID
)
526 fileoff
+= pdf_versionid(fp
, p
->words
);
531 for (o
= olist
.head
; o
; o
= o
->next
) {
532 o
->fileoff
= fileoff
;
533 fwrite(o
->final
, 1, o
->size
, fp
);
538 * Cross-reference table
540 fprintf(fp
, "xref\n");
541 assert(olist
.head
->number
== 1);
542 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
543 fprintf(fp
, "0000000000 65535 f \n");
544 for (o
= olist
.head
; o
; o
= o
->next
) {
546 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
547 assert(strlen(entry
) == 20);
554 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n",
555 olist
.tail
->number
+ 1, cat
->number
, info
->number
);
556 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
563 static object
*new_object(objlist
*list
)
565 object
*obj
= snew(object
);
569 obj
->main
.text
= NULL
;
570 obj
->main
.pos
= obj
->main
.size
= 0;
571 obj
->stream
.text
= NULL
;
572 obj
->stream
.pos
= obj
->stream
.size
= 0;
574 obj
->number
= list
->number
++;
578 list
->tail
->next
= obj
;
589 static void objtext(object
*o
, char const *text
)
591 rdaddsc(&o
->main
, text
);
594 static void objstream(object
*o
, char const *text
)
596 rdaddsc(&o
->stream
, text
);
599 static void objref(object
*o
, object
*dest
)
602 sprintf(buf
, "%d 0 R", dest
->number
);
603 rdaddsc(&o
->main
, buf
);
606 static char const * const stdfonts
[] = {
607 "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",
608 "Helvetica", "Helvetica-Bold", "Helvetica-Oblique","Helvetica-BoldOblique",
609 "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique",
610 "Symbol", "ZapfDingbats"
613 static int is_std_font(char const *name
) {
615 for (i
= 0; i
< lenof(stdfonts
); i
++)
616 if (strcmp(name
, stdfonts
[i
]) == 0)
621 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
622 page_data
*last
, object
*resources
,
629 objtext(node
, "<<\n/Type /Pages\n");
631 objtext(node
, "/Parent ");
632 objref(node
, parent
);
637 * Count the pages in this stretch, to see if there are few
638 * enough to reference directly.
641 for (page
= first
; page
; page
= page
->next
) {
647 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
650 if (count
> TREE_BRANCH
) {
652 page_data
*thisfirst
, *thislast
;
656 for (i
= 0; i
< TREE_BRANCH
; i
++) {
657 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
664 if (thisfirst
== thislast
) {
665 objref(node
, (object
*)thisfirst
->spare
);
666 objtext((object
*)thisfirst
->spare
, "/Parent ");
667 objref((object
*)thisfirst
->spare
, node
);
668 objtext((object
*)thisfirst
->spare
, "\n");
670 object
*newnode
= new_object(node
->list
);
671 make_pages_node(newnode
, node
, thisfirst
, thislast
,
673 objref(node
, newnode
);
678 assert(thislast
== last
|| page
== NULL
);
681 for (page
= first
; page
; page
= page
->next
) {
682 objref(node
, (object
*)page
->spare
);
684 objtext((object
*)page
->spare
, "/Parent ");
685 objref((object
*)page
->spare
, node
);
686 objtext((object
*)page
->spare
, "\n");
692 objtext(node
, "]\n");
695 objtext(node
, "/Resources ");
696 objref(node
, resources
);
700 objtext(node
, "/MediaBox ");
701 objref(node
, mediabox
);
705 objtext(node
, ">>\n");
709 * In text on the page, PDF uses the PostScript font model, which
710 * means that glyphs are identified by PS strings and hence font
711 * encoding can be managed independently of the supplied encoding
712 * of the font. However, in the document outline, the PDF spec
713 * encodes in either PDFDocEncoding (a custom superset of
714 * ISO-8859-1) or UTF-16BE.
716 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
719 ret
= utoa_careful_dup(s
, CS_PDF
);
722 * Very silly special case: if the returned string begins with
723 * FE FF, then the PDF reader will mistake it for a UTF-16BE
724 * string. So in this case we give up on PDFDocEncoding and
725 * encode it in UTF-16 straight away.
727 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
733 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
741 static int make_outline(object
*parent
, outline_element
*items
, int n
,
744 int level
, totalcount
= 0;
745 outline_element
*itemp
;
746 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
750 level
= items
->level
;
757 * Here we expect to be sitting on an item at the given
758 * level. So we start by constructing an outline entry for
761 assert(items
->level
== level
);
763 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
766 curr
= new_object(parent
->list
);
767 if (!first
) first
= curr
;
769 objtext(curr
, "<<\n/Title ");
770 pdf_string_len(objtext
, curr
, title
, titlelen
);
772 objtext(curr
, "\n/Parent ");
773 objref(curr
, parent
);
774 objtext(curr
, "\n/Dest [");
775 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
776 objtext(curr
, " /XYZ null null null]\n");
778 objtext(curr
, "/Prev ");
782 objtext(prev
, "/Next ");
784 objtext(prev
, "\n>>\n");
789 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
794 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
799 sprintf(buf
, "/Count %d\n", count
);
806 objtext(prev
, ">>\n");
808 assert(first
&& last
);
809 objtext(parent
, "/First ");
810 objref(parent
, first
);
811 objtext(parent
, "\n/Last ");
812 objref(parent
, last
);
813 objtext(parent
, "\n");
818 static int pdf_versionid(FILE *fp
, word
*words
)
822 ret
= fprintf(fp
, "%% ");
824 for (; words
; words
= words
->next
) {
828 switch (words
->type
) {
838 type
= removeattr(words
->type
);
842 text
= utoa_dup(words
->text
, CS_ASCII
);
844 case word_WhiteSpace
:
857 ret
+= fprintf(fp
, "\n");
862 static void pdf_string_len(void (*add
)(object
*, char const *),
863 object
*o
, char const *str
, int len
)
868 for (p
= str
; len
> 0; p
++, len
--) {
870 if (*p
< ' ' || *p
> '~') {
871 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
874 if (*p
== '\\' || *p
== '(' || *p
== ')')
884 static void pdf_string(void (*add
)(object
*, char const *),
885 object
*o
, char const *str
)
887 pdf_string_len(add
, o
, str
, strlen(str
));