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
);
42 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
43 page_data
*last
, object
*resources
);
44 static int make_outline(object
*parent
, outline_element
*start
, int n
,
46 static int pdf_versionid(FILE *fp
, word
*words
);
48 void pdf_backend(paragraph
*sourceform
, keywordlist
*keywords
,
49 indexdata
*idx
, void *vdoc
) {
50 document
*doc
= (document
*)vdoc
;
59 object
*o
, *cat
, *outlines
, *pages
, *resources
;
65 filename
= dupstr("output.pdf");
66 for (p
= sourceform
; p
; p
= p
->next
) {
67 if (p
->type
== para_Config
) {
68 if (!ustricmp(p
->keyword
, L
"pdf-filename")) {
70 filename
= dupstr(adv(p
->origkeyword
));
75 olist
.head
= olist
.tail
= NULL
;
78 cat
= new_object(&olist
);
79 if (doc
->n_outline_elements
> 0)
80 outlines
= new_object(&olist
);
83 pages
= new_object(&olist
);
84 resources
= new_object(&olist
);
87 * The catalogue just contains references to the outlines and
90 objtext(cat
, "<<\n/Type /Catalog");
92 objtext(cat
, "\n/Outlines ");
93 objref(cat
, outlines
);
95 objtext(cat
, "\n/Pages ");
98 objtext(cat
, "\n/PageMode /UseOutlines");
99 objtext(cat
, "\n>>\n");
102 * Set up the resources dictionary, which mostly means
103 * providing all the font objects and names to call them by.
106 objtext(resources
, "<<\n/Font <<\n");
107 for (fe
= doc
->fonts
->head
; fe
; fe
= fe
->next
) {
112 sprintf(fname
, "f%d", font_index
++);
113 fe
->name
= dupstr(fname
);
115 font
= new_object(&olist
);
117 objtext(resources
, "/");
118 objtext(resources
, fe
->name
);
119 objtext(resources
, " ");
120 objref(resources
, font
);
121 objtext(resources
, "\n");
123 objtext(font
, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
124 objtext(font
, fe
->name
);
125 objtext(font
, "\n/BaseFont /");
126 objtext(font
, fe
->font
->name
);
127 objtext(font
, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
129 for (i
= 0; i
< 256; i
++) {
133 sprintf(buf
, "\n%d /", i
);
135 objtext(font
, fe
->vector
[i
] ? fe
->vector
[i
] : ".notdef");
138 objtext(font
, "\n]\n>>\n");
141 object
*widths
= new_object(&olist
);
142 objtext(font
, "/FirstChar 0\n/LastChar 255\n/Widths ");
143 objref(font
, widths
);
145 objtext(widths
, "[\n");
146 for (i
= 0; i
< 256; i
++) {
149 if (fe
->indices
[i
] < 0)
152 width
= fe
->font
->widths
[fe
->indices
[i
]];
153 sprintf(buf
, "%g\n", 1000.0 * width
/ 4096.0);
154 objtext(widths
, buf
);
156 objtext(widths
, "]\n");
159 objtext(font
, ">>\n");
161 objtext(resources
, ">>\n>>\n");
164 * Define the page objects for each page, and get each one
165 * ready to have a `Parent' specification added to it.
167 for (page
= doc
->pages
; page
; page
= page
->next
) {
170 opage
= new_object(&olist
);
172 objtext(opage
, "<<\n/Type /Page\n");
176 * Recursively build the page tree.
178 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
);
181 * Create and render the individual pages.
184 for (page
= doc
->pages
; page
; page
= page
->next
) {
185 object
*opage
, *cstr
;
187 text_fragment
*frag
, *frag_end
;
191 opage
= (object
*)page
->spare
;
193 * At this point the page dictionary is already
194 * half-written, with /Type and /Parent already present. We
195 * continue from there.
199 * The PDF spec says /Resources is required, but also says
200 * that it's inheritable and may be omitted if it's present
201 * in a Pages node. In our case it is: it's present in the
202 * topmost /Pages node because we carefully put it there.
203 * So we don't need a /Resources entry here.
205 sprintf(buf
, "/MediaBox [0 0 %g %g]\n",
206 doc
->paper_width
/ 4096.0, doc
->paper_height
/ 4096.0);
210 * Now we're ready to define a content stream containing
211 * the actual text on the page.
213 cstr
= new_object(&olist
);
214 objtext(opage
, "/Contents ");
216 objtext(opage
, "\n");
219 * Render any rectangles on the page.
221 for (r
= page
->first_rect
; r
; r
= r
->next
) {
223 sprintf(buf
, "%g %g %g %g re f\n", r
->x
/ 4096.0,
224 r
->y
/ 4096.0, r
->w
/ 4096.0, r
->h
/ 4096.0);
225 objstream(cstr
, buf
);
228 objstream(cstr
, "BT\n");
231 * PDF tracks two separate current positions: the position
232 * given in the `line matrix' and the position given in the
233 * `text matrix'. We must therefore track both as well.
234 * They start off at -1 (unset).
239 frag
= page
->first_text
;
242 * For compactness, I'm going to group text fragments
243 * into subsequences that use the same font+size. So
244 * first find the end of this subsequence.
246 for (frag_end
= frag
;
248 frag_end
->fe
== frag
->fe
&&
249 frag_end
->fontsize
== frag
->fontsize
);
250 frag_end
= frag_end
->next
);
253 * Now select the text fragment, and prepare to display
256 objstream(cstr
, "/");
257 objstream(cstr
, frag
->fe
->name
);
258 sprintf(buf
, " %d Tf ", frag
->fontsize
);
259 objstream(cstr
, buf
);
261 while (frag
&& frag
!= frag_end
) {
263 * Place the text position for the first piece of
267 sprintf(buf
, "1 0 0 1 %g %g Tm ",
268 frag
->x
/4096.0, frag
->y
/4096.0);
270 sprintf(buf
, "%g %g Td ",
271 (frag
->x
- lx
)/4096.0, (frag
->y
- ly
)/4096.0);
273 objstream(cstr
, buf
);
278 * See if we're going to use Tj (show a single
279 * string) or TJ (show an array of strings with
280 * x-spacings between them). We determine this by
281 * seeing if there's more than one text fragment in
282 * sequence with the same y-coordinate.
284 if (frag
->next
&& frag
->next
!= frag_end
&&
285 frag
->next
->y
== y
) {
289 objstream(cstr
, "[");
290 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
293 (x
- frag
->x
) * 1000.0 /
294 (4096.0 * frag
->fontsize
));
295 objstream(cstr
, buf
);
297 pdf_string(objstream
, cstr
, frag
->text
);
298 x
= frag
->x
+ frag
->width
;
301 objstream(cstr
, "]TJ\n");
307 pdf_string(objstream
, cstr
, frag
->text
);
308 objstream(cstr
, "Tj\n");
313 objstream(cstr
, "ET");
316 * Also, we want an annotation dictionary containing the
317 * cross-references from this page.
319 if (page
->first_xref
) {
321 objtext(opage
, "/Annots [\n");
323 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
327 annot
= new_object(&olist
);
328 objref(opage
, annot
);
329 objtext(opage
, "\n");
331 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
332 sprintf(buf
, "%g %g %g %g",
333 xr
->lx
/ 4096.0, xr
->by
/ 4096.0,
334 xr
->rx
/ 4096.0, xr
->ty
/ 4096.0);
336 objtext(annot
, "]\n/Border [0 0 0]\n");
338 if (xr
->dest
.type
== PAGE
) {
339 objtext(annot
, "/Dest [");
340 objref(annot
, (object
*)xr
->dest
.page
->spare
);
341 objtext(annot
, " /XYZ null null null]\n");
343 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
344 pdf_string(objtext
, annot
, xr
->dest
.url
);
345 objtext(annot
, "\n>>\n");
348 objtext(annot
, ">>\n");
351 objtext(opage
, "]\n");
354 objtext(opage
, ">>\n");
358 * Set up the outlines dictionary.
364 objtext(outlines
, "<<\n/Type /Outlines\n");
365 topcount
= make_outline(outlines
, doc
->outline_elements
,
366 doc
->n_outline_elements
, TRUE
);
367 sprintf(buf
, "/Count %d\n>>\n", topcount
);
368 objtext(outlines
, buf
);
372 * Assemble the final linear form of every object.
374 for (o
= olist
.head
; o
; o
= o
->next
) {
375 rdstringc rs
= {0, 0, NULL
};
378 sprintf(text
, "%d 0 obj\n", o
->number
);
381 if (!o
->main
.text
&& o
->stream
.text
) {
382 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
383 rdaddsc(&o
->main
, text
);
386 assert(o
->main
.text
);
387 rdaddsc(&rs
, o
->main
.text
);
390 if (rs
.text
[rs
.pos
-1] != '\n')
393 if (o
->stream
.text
) {
395 * FIXME: If we ever start compressing stream data then
396 * it will have zero bytes in it, so we'll have to be
397 * more careful than this.
399 rdaddsc(&rs
, "stream\n");
400 rdaddsc(&rs
, o
->stream
.text
);
401 rdaddsc(&rs
, "\nendstream\n");
402 sfree(o
->stream
.text
);
405 rdaddsc(&rs
, "endobj\n");
412 * Write out the PDF file.
415 fp
= fopen(filename
, "wb");
417 error(err_cantopenw
, filename
);
422 * Header. I'm going to put the version IDs in the header as
423 * well, simply in PDF comments.
425 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
426 for (p
= sourceform
; p
; p
= p
->next
)
427 if (p
->type
== para_VersionID
)
428 fileoff
+= pdf_versionid(fp
, p
->words
);
433 for (o
= olist
.head
; o
; o
= o
->next
) {
434 o
->fileoff
= fileoff
;
435 fwrite(o
->final
, 1, o
->size
, fp
);
440 * Cross-reference table
442 fprintf(fp
, "xref\n");
443 assert(olist
.head
->number
== 1);
444 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
445 fprintf(fp
, "0000000000 65535 f \n");
446 for (o
= olist
.head
; o
; o
= o
->next
) {
448 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
449 assert(strlen(entry
) == 20);
456 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n>>\n",
457 olist
.tail
->number
+ 1, cat
->number
);
458 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
465 static object
*new_object(objlist
*list
)
467 object
*obj
= snew(object
);
471 obj
->main
.text
= NULL
;
472 obj
->main
.pos
= obj
->main
.size
= 0;
473 obj
->stream
.text
= NULL
;
474 obj
->stream
.pos
= obj
->stream
.size
= 0;
476 obj
->number
= list
->number
++;
480 list
->tail
->next
= obj
;
491 static void objtext(object
*o
, char const *text
)
493 rdaddsc(&o
->main
, text
);
496 static void objstream(object
*o
, char const *text
)
498 rdaddsc(&o
->stream
, text
);
501 static void objref(object
*o
, object
*dest
)
504 sprintf(buf
, "%d 0 R", dest
->number
);
505 rdaddsc(&o
->main
, buf
);
508 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
509 page_data
*last
, object
*resources
)
515 objtext(node
, "<<\n/Type /Pages\n");
517 objtext(node
, "/Parent ");
518 objref(node
, parent
);
523 * Count the pages in this stretch, to see if there are few
524 * enough to reference directly.
527 for (page
= first
; page
; page
= page
->next
) {
533 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
536 if (count
> TREE_BRANCH
) {
538 page_data
*thisfirst
, *thislast
;
542 for (i
= 0; i
< TREE_BRANCH
; i
++) {
543 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
550 if (thisfirst
== thislast
) {
551 objref(node
, (object
*)thisfirst
->spare
);
552 objtext((object
*)thisfirst
->spare
, "/Parent ");
553 objref((object
*)thisfirst
->spare
, node
);
554 objtext((object
*)thisfirst
->spare
, "\n");
556 object
*newnode
= new_object(node
->list
);
557 make_pages_node(newnode
, node
, thisfirst
, thislast
, NULL
);
558 objref(node
, newnode
);
563 assert(thislast
== last
|| page
== NULL
);
566 for (page
= first
; page
; page
= page
->next
) {
567 objref(node
, (object
*)page
->spare
);
569 objtext((object
*)page
->spare
, "/Parent ");
570 objref((object
*)page
->spare
, node
);
571 objtext((object
*)page
->spare
, "\n");
577 objtext(node
, "]\n");
580 objtext(node
, "/Resources ");
581 objref(node
, resources
);
585 objtext(node
, ">>\n");
589 * In text on the page, PDF uses the PostScript font model, which
590 * means that glyphs are identified by PS strings and hence font
591 * encoding can be managed independently of the supplied encoding
592 * of the font. However, in the document outline, the PDF spec
593 * encodes in either PDFDocEncoding (a custom superset of
594 * ISO-8859-1) or UTF-16BE.
596 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
599 ret
= utoa_careful_dup(s
, CS_PDF
);
602 * Very silly special case: if the returned string begins with
603 * FE FF, then the PDF reader will mistake it for a UTF-16BE
604 * string. So in this case we give up on PDFDocEncoding and
605 * encode it in UTF-16 straight away.
607 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
613 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
621 static int make_outline(object
*parent
, outline_element
*items
, int n
,
624 int level
, totalcount
= 0;
625 outline_element
*itemp
;
626 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
630 level
= items
->level
;
637 * Here we expect to be sitting on an item at the given
638 * level. So we start by constructing an outline entry for
641 assert(items
->level
== level
);
643 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
646 curr
= new_object(parent
->list
);
647 if (!first
) first
= curr
;
649 objtext(curr
, "<<\n/Title ");
650 pdf_string_len(objtext
, curr
, title
, titlelen
);
651 objtext(curr
, "\n/Parent ");
652 objref(curr
, parent
);
653 objtext(curr
, "\n/Dest [");
654 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
655 objtext(curr
, " /XYZ null null null]\n");
657 objtext(curr
, "/Prev ");
661 objtext(prev
, "/Next ");
663 objtext(prev
, "\n>>\n");
668 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
673 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
678 sprintf(buf
, "/Count %d\n", count
);
685 objtext(prev
, ">>\n");
687 assert(first
&& last
);
688 objtext(parent
, "/First ");
689 objref(parent
, first
);
690 objtext(parent
, "\n/Last ");
691 objref(parent
, last
);
692 objtext(parent
, "\n");
697 static int pdf_versionid(FILE *fp
, word
*words
)
701 ret
= fprintf(fp
, "%% ");
703 for (; words
; words
= words
->next
) {
707 switch (words
->type
) {
717 type
= removeattr(words
->type
);
721 text
= utoa_dup(words
->text
, CS_ASCII
);
723 case word_WhiteSpace
:
736 ret
+= fprintf(fp
, "\n");
741 static void pdf_string_len(void (*add
)(object
*, char const *),
742 object
*o
, char const *str
, int len
)
747 for (p
= str
; len
> 0; p
++, len
--) {
749 if (*p
< ' ' || *p
> '~') {
750 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
753 if (*p
== '\\' || *p
== '(' || *p
== ')')
763 static void pdf_string(void (*add
)(object
*, char const *),
764 object
*o
, char const *str
)
766 pdf_string_len(add
, o
, str
, strlen(str
));