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
,
45 static int make_outline(object
*parent
, outline_element
*start
, int n
,
47 static int pdf_versionid(FILE *fp
, word
*words
);
49 void pdf_backend(paragraph
*sourceform
, keywordlist
*keywords
,
50 indexdata
*idx
, void *vdoc
) {
51 document
*doc
= (document
*)vdoc
;
60 object
*o
, *cat
, *outlines
, *pages
, *resources
, *mediabox
;
66 filename
= dupstr("output.pdf");
67 for (p
= sourceform
; p
; p
= p
->next
) {
68 if (p
->type
== para_Config
) {
69 if (!ustricmp(p
->keyword
, L
"pdf-filename")) {
71 filename
= dupstr(adv(p
->origkeyword
));
76 olist
.head
= olist
.tail
= NULL
;
79 cat
= new_object(&olist
);
80 if (doc
->n_outline_elements
> 0)
81 outlines
= new_object(&olist
);
84 pages
= new_object(&olist
);
85 resources
= new_object(&olist
);
88 * The catalogue just contains references to the outlines and
91 objtext(cat
, "<<\n/Type /Catalog");
93 objtext(cat
, "\n/Outlines ");
94 objref(cat
, outlines
);
96 objtext(cat
, "\n/Pages ");
99 objtext(cat
, "\n/PageMode /UseOutlines");
100 objtext(cat
, "\n>>\n");
103 * Set up the resources dictionary, which mostly means
104 * providing all the font objects and names to call them by.
107 objtext(resources
, "<<\n/Font <<\n");
108 for (fe
= doc
->fonts
->head
; fe
; fe
= fe
->next
) {
113 sprintf(fname
, "f%d", font_index
++);
114 fe
->name
= dupstr(fname
);
116 font
= new_object(&olist
);
118 objtext(resources
, "/");
119 objtext(resources
, fe
->name
);
120 objtext(resources
, " ");
121 objref(resources
, font
);
122 objtext(resources
, "\n");
124 objtext(font
, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
125 objtext(font
, fe
->name
);
126 objtext(font
, "\n/BaseFont /");
127 objtext(font
, fe
->font
->name
);
128 objtext(font
, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
130 for (i
= 0; i
< 256; i
++) {
134 sprintf(buf
, "\n%d /", i
);
136 objtext(font
, fe
->vector
[i
] ? fe
->vector
[i
] : ".notdef");
139 objtext(font
, "\n]\n>>\n");
142 object
*widths
= new_object(&olist
);
143 objtext(font
, "/FirstChar 0\n/LastChar 255\n/Widths ");
144 objref(font
, widths
);
146 objtext(widths
, "[\n");
147 for (i
= 0; i
< 256; i
++) {
150 if (fe
->indices
[i
] < 0)
153 width
= fe
->font
->widths
[fe
->indices
[i
]];
154 sprintf(buf
, "%g\n", 1000.0 * width
/ FUNITS_PER_PT
);
155 objtext(widths
, buf
);
157 objtext(widths
, "]\n");
160 objtext(font
, ">>\n");
162 objtext(resources
, ">>\n>>\n");
166 mediabox
= new_object(&olist
);
167 sprintf(buf
, "[0 0 %g %g]\n",
168 doc
->paper_width
/ FUNITS_PER_PT
,
169 doc
->paper_height
/ FUNITS_PER_PT
);
170 objtext(mediabox
, buf
);
174 * Define the page objects for each page, and get each one
175 * ready to have a `Parent' specification added to it.
177 for (page
= doc
->pages
; page
; page
= page
->next
) {
180 opage
= new_object(&olist
);
182 objtext(opage
, "<<\n/Type /Page\n");
186 * Recursively build the page tree.
188 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
, mediabox
);
191 * Create and render the individual pages.
194 for (page
= doc
->pages
; page
; page
= page
->next
) {
195 object
*opage
, *cstr
;
197 text_fragment
*frag
, *frag_end
;
201 opage
= (object
*)page
->spare
;
203 * At this point the page dictionary is already
204 * half-written, with /Type and /Parent already present. We
205 * continue from there.
209 * The PDF spec says /Resources is required, but also says
210 * that it's inheritable and may be omitted if it's present
211 * in a Pages node. In our case it is: it's present in the
212 * topmost /Pages node because we carefully put it there.
213 * So we don't need a /Resources entry here. The same applies
218 * Now we're ready to define a content stream containing
219 * the actual text on the page.
221 cstr
= new_object(&olist
);
222 objtext(opage
, "/Contents ");
224 objtext(opage
, "\n");
227 * Render any rectangles on the page.
229 for (r
= page
->first_rect
; r
; r
= r
->next
) {
231 sprintf(buf
, "%g %g %g %g re f\n",
232 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
233 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
234 objstream(cstr
, buf
);
237 objstream(cstr
, "BT\n");
240 * PDF tracks two separate current positions: the position
241 * given in the `line matrix' and the position given in the
242 * `text matrix'. We must therefore track both as well.
243 * They start off at -1 (unset).
248 frag
= page
->first_text
;
251 * For compactness, I'm going to group text fragments
252 * into subsequences that use the same font+size. So
253 * first find the end of this subsequence.
255 for (frag_end
= frag
;
257 frag_end
->fe
== frag
->fe
&&
258 frag_end
->fontsize
== frag
->fontsize
);
259 frag_end
= frag_end
->next
);
262 * Now select the text fragment, and prepare to display
265 objstream(cstr
, "/");
266 objstream(cstr
, frag
->fe
->name
);
267 sprintf(buf
, " %d Tf ", frag
->fontsize
);
268 objstream(cstr
, buf
);
270 while (frag
&& frag
!= frag_end
) {
272 * Place the text position for the first piece of
276 sprintf(buf
, "1 0 0 1 %g %g Tm ",
277 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
279 sprintf(buf
, "%g %g Td ",
280 (frag
->x
- lx
)/FUNITS_PER_PT
,
281 (frag
->y
- ly
)/FUNITS_PER_PT
);
283 objstream(cstr
, buf
);
288 * See if we're going to use Tj (show a single
289 * string) or TJ (show an array of strings with
290 * x-spacings between them). We determine this by
291 * seeing if there's more than one text fragment in
292 * sequence with the same y-coordinate.
294 if (frag
->next
&& frag
->next
!= frag_end
&&
295 frag
->next
->y
== y
) {
299 objstream(cstr
, "[");
300 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
303 (x
- frag
->x
) * 1000.0 /
304 (FUNITS_PER_PT
* frag
->fontsize
));
305 objstream(cstr
, buf
);
307 pdf_string(objstream
, cstr
, frag
->text
);
308 x
= frag
->x
+ frag
->width
;
311 objstream(cstr
, "]TJ\n");
317 pdf_string(objstream
, cstr
, frag
->text
);
318 objstream(cstr
, "Tj\n");
323 objstream(cstr
, "ET");
326 * Also, we want an annotation dictionary containing the
327 * cross-references from this page.
329 if (page
->first_xref
) {
331 objtext(opage
, "/Annots [\n");
333 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
337 annot
= new_object(&olist
);
338 objref(opage
, annot
);
339 objtext(opage
, "\n");
341 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
342 sprintf(buf
, "%g %g %g %g",
343 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
344 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
346 objtext(annot
, "]\n/Border [0 0 0]\n");
348 if (xr
->dest
.type
== PAGE
) {
349 objtext(annot
, "/Dest [");
350 objref(annot
, (object
*)xr
->dest
.page
->spare
);
351 objtext(annot
, " /XYZ null null null]\n");
353 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
354 pdf_string(objtext
, annot
, xr
->dest
.url
);
355 objtext(annot
, "\n>>\n");
358 objtext(annot
, ">>\n");
361 objtext(opage
, "]\n");
364 objtext(opage
, ">>\n");
368 * Set up the outlines dictionary.
374 objtext(outlines
, "<<\n/Type /Outlines\n");
375 topcount
= make_outline(outlines
, doc
->outline_elements
,
376 doc
->n_outline_elements
, TRUE
);
377 sprintf(buf
, "/Count %d\n>>\n", topcount
);
378 objtext(outlines
, buf
);
382 * Assemble the final linear form of every object.
384 for (o
= olist
.head
; o
; o
= o
->next
) {
385 rdstringc rs
= {0, 0, NULL
};
388 sprintf(text
, "%d 0 obj\n", o
->number
);
391 if (!o
->main
.text
&& o
->stream
.text
) {
392 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
393 rdaddsc(&o
->main
, text
);
396 assert(o
->main
.text
);
397 rdaddsc(&rs
, o
->main
.text
);
400 if (rs
.text
[rs
.pos
-1] != '\n')
403 if (o
->stream
.text
) {
405 * FIXME: If we ever start compressing stream data then
406 * it will have zero bytes in it, so we'll have to be
407 * more careful than this.
409 rdaddsc(&rs
, "stream\n");
410 rdaddsc(&rs
, o
->stream
.text
);
411 rdaddsc(&rs
, "\nendstream\n");
412 sfree(o
->stream
.text
);
415 rdaddsc(&rs
, "endobj\n");
422 * Write out the PDF file.
425 fp
= fopen(filename
, "wb");
427 error(err_cantopenw
, filename
);
432 * Header. I'm going to put the version IDs in the header as
433 * well, simply in PDF comments.
435 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
436 for (p
= sourceform
; p
; p
= p
->next
)
437 if (p
->type
== para_VersionID
)
438 fileoff
+= pdf_versionid(fp
, p
->words
);
443 for (o
= olist
.head
; o
; o
= o
->next
) {
444 o
->fileoff
= fileoff
;
445 fwrite(o
->final
, 1, o
->size
, fp
);
450 * Cross-reference table
452 fprintf(fp
, "xref\n");
453 assert(olist
.head
->number
== 1);
454 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
455 fprintf(fp
, "0000000000 65535 f \n");
456 for (o
= olist
.head
; o
; o
= o
->next
) {
458 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
459 assert(strlen(entry
) == 20);
466 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n>>\n",
467 olist
.tail
->number
+ 1, cat
->number
);
468 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
475 static object
*new_object(objlist
*list
)
477 object
*obj
= snew(object
);
481 obj
->main
.text
= NULL
;
482 obj
->main
.pos
= obj
->main
.size
= 0;
483 obj
->stream
.text
= NULL
;
484 obj
->stream
.pos
= obj
->stream
.size
= 0;
486 obj
->number
= list
->number
++;
490 list
->tail
->next
= obj
;
501 static void objtext(object
*o
, char const *text
)
503 rdaddsc(&o
->main
, text
);
506 static void objstream(object
*o
, char const *text
)
508 rdaddsc(&o
->stream
, text
);
511 static void objref(object
*o
, object
*dest
)
514 sprintf(buf
, "%d 0 R", dest
->number
);
515 rdaddsc(&o
->main
, buf
);
518 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
519 page_data
*last
, object
*resources
,
526 objtext(node
, "<<\n/Type /Pages\n");
528 objtext(node
, "/Parent ");
529 objref(node
, parent
);
534 * Count the pages in this stretch, to see if there are few
535 * enough to reference directly.
538 for (page
= first
; page
; page
= page
->next
) {
544 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
547 if (count
> TREE_BRANCH
) {
549 page_data
*thisfirst
, *thislast
;
553 for (i
= 0; i
< TREE_BRANCH
; i
++) {
554 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
561 if (thisfirst
== thislast
) {
562 objref(node
, (object
*)thisfirst
->spare
);
563 objtext((object
*)thisfirst
->spare
, "/Parent ");
564 objref((object
*)thisfirst
->spare
, node
);
565 objtext((object
*)thisfirst
->spare
, "\n");
567 object
*newnode
= new_object(node
->list
);
568 make_pages_node(newnode
, node
, thisfirst
, thislast
,
570 objref(node
, newnode
);
575 assert(thislast
== last
|| page
== NULL
);
578 for (page
= first
; page
; page
= page
->next
) {
579 objref(node
, (object
*)page
->spare
);
581 objtext((object
*)page
->spare
, "/Parent ");
582 objref((object
*)page
->spare
, node
);
583 objtext((object
*)page
->spare
, "\n");
589 objtext(node
, "]\n");
592 objtext(node
, "/Resources ");
593 objref(node
, resources
);
597 objtext(node
, "/MediaBox ");
598 objref(node
, mediabox
);
602 objtext(node
, ">>\n");
606 * In text on the page, PDF uses the PostScript font model, which
607 * means that glyphs are identified by PS strings and hence font
608 * encoding can be managed independently of the supplied encoding
609 * of the font. However, in the document outline, the PDF spec
610 * encodes in either PDFDocEncoding (a custom superset of
611 * ISO-8859-1) or UTF-16BE.
613 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
616 ret
= utoa_careful_dup(s
, CS_PDF
);
619 * Very silly special case: if the returned string begins with
620 * FE FF, then the PDF reader will mistake it for a UTF-16BE
621 * string. So in this case we give up on PDFDocEncoding and
622 * encode it in UTF-16 straight away.
624 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
630 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
638 static int make_outline(object
*parent
, outline_element
*items
, int n
,
641 int level
, totalcount
= 0;
642 outline_element
*itemp
;
643 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
647 level
= items
->level
;
654 * Here we expect to be sitting on an item at the given
655 * level. So we start by constructing an outline entry for
658 assert(items
->level
== level
);
660 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
663 curr
= new_object(parent
->list
);
664 if (!first
) first
= curr
;
666 objtext(curr
, "<<\n/Title ");
667 pdf_string_len(objtext
, curr
, title
, titlelen
);
668 objtext(curr
, "\n/Parent ");
669 objref(curr
, parent
);
670 objtext(curr
, "\n/Dest [");
671 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
672 objtext(curr
, " /XYZ null null null]\n");
674 objtext(curr
, "/Prev ");
678 objtext(prev
, "/Next ");
680 objtext(prev
, "\n>>\n");
685 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
690 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
695 sprintf(buf
, "/Count %d\n", count
);
702 objtext(prev
, ">>\n");
704 assert(first
&& last
);
705 objtext(parent
, "/First ");
706 objref(parent
, first
);
707 objtext(parent
, "\n/Last ");
708 objref(parent
, last
);
709 objtext(parent
, "\n");
714 static int pdf_versionid(FILE *fp
, word
*words
)
718 ret
= fprintf(fp
, "%% ");
720 for (; words
; words
= words
->next
) {
724 switch (words
->type
) {
734 type
= removeattr(words
->type
);
738 text
= utoa_dup(words
->text
, CS_ASCII
);
740 case word_WhiteSpace
:
753 ret
+= fprintf(fp
, "\n");
758 static void pdf_string_len(void (*add
)(object
*, char const *),
759 object
*o
, char const *str
, int len
)
764 for (p
= str
; len
> 0; p
++, len
--) {
766 if (*p
< ' ' || *p
> '~') {
767 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
770 if (*p
== '\\' || *p
== '(' || *p
== ')')
780 static void pdf_string(void (*add
)(object
*, char const *),
781 object
*o
, char const *str
)
783 pdf_string_len(add
, o
, str
, strlen(str
));