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 void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
44 page_data
*last
, object
*resources
,
46 static int make_outline(object
*parent
, outline_element
*start
, int n
,
48 static int pdf_versionid(FILE *fp
, word
*words
);
50 void pdf_backend(paragraph
*sourceform
, keywordlist
*keywords
,
51 indexdata
*idx
, void *vdoc
) {
52 document
*doc
= (document
*)vdoc
;
61 object
*o
, *info
, *cat
, *outlines
, *pages
, *resources
, *mediabox
;
67 filename
= dupstr("output.pdf");
68 for (p
= sourceform
; p
; p
= p
->next
) {
69 if (p
->type
== para_Config
) {
70 if (!ustricmp(p
->keyword
, L
"pdf-filename")) {
72 filename
= dupstr(adv(p
->origkeyword
));
77 olist
.head
= olist
.tail
= NULL
;
83 info
= new_object(&olist
);
84 objtext(info
, "<<\n");
85 if (doc
->n_outline_elements
> 0) {
90 pdf_outline_convert(doc
->outline_elements
->pdata
->outline_title
,
92 objtext(info
, "/Title ");
93 pdf_string_len(objtext
, info
, title
, titlelen
);
97 objtext(info
, "/Producer ");
98 sprintf(buf
, "Halibut, %s", version
);
99 pdf_string(objtext
, info
, buf
);
100 objtext(info
, "\n>>\n");
103 cat
= new_object(&olist
);
104 if (doc
->n_outline_elements
> 0)
105 outlines
= new_object(&olist
);
108 pages
= new_object(&olist
);
109 resources
= new_object(&olist
);
112 * The catalogue just contains references to the outlines and
115 objtext(cat
, "<<\n/Type /Catalog");
117 objtext(cat
, "\n/Outlines ");
118 objref(cat
, outlines
);
120 objtext(cat
, "\n/Pages ");
123 objtext(cat
, "\n/PageMode /UseOutlines");
124 objtext(cat
, "\n>>\n");
127 * Set up the resources dictionary, which mostly means
128 * providing all the font objects and names to call them by.
131 objtext(resources
, "<<\n/Font <<\n");
132 for (fe
= doc
->fonts
->head
; fe
; fe
= fe
->next
) {
137 sprintf(fname
, "f%d", font_index
++);
138 fe
->name
= dupstr(fname
);
140 font
= new_object(&olist
);
142 objtext(resources
, "/");
143 objtext(resources
, fe
->name
);
144 objtext(resources
, " ");
145 objref(resources
, font
);
146 objtext(resources
, "\n");
148 objtext(font
, "<<\n/Type /Font\n/Subtype /Type1\n/Name /");
149 objtext(font
, fe
->name
);
150 objtext(font
, "\n/BaseFont /");
151 objtext(font
, fe
->font
->name
);
152 objtext(font
, "\n/Encoding <<\n/Type /Encoding\n/Differences [");
154 for (i
= 0; i
< 256; i
++) {
158 sprintf(buf
, "\n%d /", i
);
160 objtext(font
, fe
->vector
[i
] ? fe
->vector
[i
] : ".notdef");
163 objtext(font
, "\n]\n>>\n");
166 object
*widths
= new_object(&olist
);
167 objtext(font
, "/FirstChar 0\n/LastChar 255\n/Widths ");
168 objref(font
, widths
);
170 objtext(widths
, "[\n");
171 for (i
= 0; i
< 256; i
++) {
174 if (fe
->indices
[i
] < 0)
177 width
= fe
->font
->widths
[fe
->indices
[i
]];
178 sprintf(buf
, "%g\n", 1000.0 * width
/ FUNITS_PER_PT
);
179 objtext(widths
, buf
);
181 objtext(widths
, "]\n");
184 objtext(font
, ">>\n");
186 objtext(resources
, ">>\n>>\n");
190 mediabox
= new_object(&olist
);
191 sprintf(buf
, "[0 0 %g %g]\n",
192 doc
->paper_width
/ FUNITS_PER_PT
,
193 doc
->paper_height
/ FUNITS_PER_PT
);
194 objtext(mediabox
, buf
);
198 * Define the page objects for each page, and get each one
199 * ready to have a `Parent' specification added to it.
201 for (page
= doc
->pages
; page
; page
= page
->next
) {
204 opage
= new_object(&olist
);
206 objtext(opage
, "<<\n/Type /Page\n");
210 * Recursively build the page tree.
212 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
, mediabox
);
215 * Create and render the individual pages.
218 for (page
= doc
->pages
; page
; page
= page
->next
) {
219 object
*opage
, *cstr
;
221 text_fragment
*frag
, *frag_end
;
225 opage
= (object
*)page
->spare
;
227 * At this point the page dictionary is already
228 * half-written, with /Type and /Parent already present. We
229 * continue from there.
233 * The PDF spec says /Resources is required, but also says
234 * that it's inheritable and may be omitted if it's present
235 * in a Pages node. In our case it is: it's present in the
236 * topmost /Pages node because we carefully put it there.
237 * So we don't need a /Resources entry here. The same applies
242 * Now we're ready to define a content stream containing
243 * the actual text on the page.
245 cstr
= new_object(&olist
);
246 objtext(opage
, "/Contents ");
248 objtext(opage
, "\n");
251 * Render any rectangles on the page.
253 for (r
= page
->first_rect
; r
; r
= r
->next
) {
255 sprintf(buf
, "%g %g %g %g re f\n",
256 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
257 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
258 objstream(cstr
, buf
);
261 objstream(cstr
, "BT\n");
264 * PDF tracks two separate current positions: the position
265 * given in the `line matrix' and the position given in the
266 * `text matrix'. We must therefore track both as well.
267 * They start off at -1 (unset).
272 frag
= page
->first_text
;
275 * For compactness, I'm going to group text fragments
276 * into subsequences that use the same font+size. So
277 * first find the end of this subsequence.
279 for (frag_end
= frag
;
281 frag_end
->fe
== frag
->fe
&&
282 frag_end
->fontsize
== frag
->fontsize
);
283 frag_end
= frag_end
->next
);
286 * Now select the text fragment, and prepare to display
289 objstream(cstr
, "/");
290 objstream(cstr
, frag
->fe
->name
);
291 sprintf(buf
, " %d Tf ", frag
->fontsize
);
292 objstream(cstr
, buf
);
294 while (frag
&& frag
!= frag_end
) {
296 * Place the text position for the first piece of
300 sprintf(buf
, "1 0 0 1 %g %g Tm ",
301 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
303 sprintf(buf
, "%g %g Td ",
304 (frag
->x
- lx
)/FUNITS_PER_PT
,
305 (frag
->y
- ly
)/FUNITS_PER_PT
);
307 objstream(cstr
, buf
);
312 * See if we're going to use Tj (show a single
313 * string) or TJ (show an array of strings with
314 * x-spacings between them). We determine this by
315 * seeing if there's more than one text fragment in
316 * sequence with the same y-coordinate.
318 if (frag
->next
&& frag
->next
!= frag_end
&&
319 frag
->next
->y
== y
) {
323 objstream(cstr
, "[");
324 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
327 (x
- frag
->x
) * 1000.0 /
328 (FUNITS_PER_PT
* frag
->fontsize
));
329 objstream(cstr
, buf
);
331 pdf_string(objstream
, cstr
, frag
->text
);
332 x
= frag
->x
+ frag
->width
;
335 objstream(cstr
, "]TJ\n");
341 pdf_string(objstream
, cstr
, frag
->text
);
342 objstream(cstr
, "Tj\n");
347 objstream(cstr
, "ET");
350 * Also, we want an annotation dictionary containing the
351 * cross-references from this page.
353 if (page
->first_xref
) {
355 objtext(opage
, "/Annots [\n");
357 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
361 annot
= new_object(&olist
);
362 objref(opage
, annot
);
363 objtext(opage
, "\n");
365 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
366 sprintf(buf
, "%g %g %g %g",
367 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
368 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
370 objtext(annot
, "]\n/Border [0 0 0]\n");
372 if (xr
->dest
.type
== PAGE
) {
373 objtext(annot
, "/Dest [");
374 objref(annot
, (object
*)xr
->dest
.page
->spare
);
375 objtext(annot
, " /XYZ null null null]\n");
377 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
378 pdf_string(objtext
, annot
, xr
->dest
.url
);
379 objtext(annot
, "\n>>\n");
382 objtext(annot
, ">>\n");
385 objtext(opage
, "]\n");
388 objtext(opage
, ">>\n");
392 * Set up the outlines dictionary.
398 objtext(outlines
, "<<\n/Type /Outlines\n");
399 topcount
= make_outline(outlines
, doc
->outline_elements
,
400 doc
->n_outline_elements
, TRUE
);
401 sprintf(buf
, "/Count %d\n>>\n", topcount
);
402 objtext(outlines
, buf
);
406 * Assemble the final linear form of every object.
408 for (o
= olist
.head
; o
; o
= o
->next
) {
409 rdstringc rs
= {0, 0, NULL
};
412 sprintf(text
, "%d 0 obj\n", o
->number
);
415 if (!o
->main
.text
&& o
->stream
.text
) {
416 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
417 rdaddsc(&o
->main
, text
);
420 assert(o
->main
.text
);
421 rdaddsc(&rs
, o
->main
.text
);
424 if (rs
.text
[rs
.pos
-1] != '\n')
427 if (o
->stream
.text
) {
429 * FIXME: If we ever start compressing stream data then
430 * it will have zero bytes in it, so we'll have to be
431 * more careful than this.
433 rdaddsc(&rs
, "stream\n");
434 rdaddsc(&rs
, o
->stream
.text
);
435 rdaddsc(&rs
, "\nendstream\n");
436 sfree(o
->stream
.text
);
439 rdaddsc(&rs
, "endobj\n");
446 * Write out the PDF file.
449 fp
= fopen(filename
, "wb");
451 error(err_cantopenw
, filename
);
456 * Header. I'm going to put the version IDs in the header as
457 * well, simply in PDF comments.
459 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
460 for (p
= sourceform
; p
; p
= p
->next
)
461 if (p
->type
== para_VersionID
)
462 fileoff
+= pdf_versionid(fp
, p
->words
);
467 for (o
= olist
.head
; o
; o
= o
->next
) {
468 o
->fileoff
= fileoff
;
469 fwrite(o
->final
, 1, o
->size
, fp
);
474 * Cross-reference table
476 fprintf(fp
, "xref\n");
477 assert(olist
.head
->number
== 1);
478 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
479 fprintf(fp
, "0000000000 65535 f \n");
480 for (o
= olist
.head
; o
; o
= o
->next
) {
482 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
483 assert(strlen(entry
) == 20);
490 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n",
491 olist
.tail
->number
+ 1, cat
->number
, info
->number
);
492 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
499 static object
*new_object(objlist
*list
)
501 object
*obj
= snew(object
);
505 obj
->main
.text
= NULL
;
506 obj
->main
.pos
= obj
->main
.size
= 0;
507 obj
->stream
.text
= NULL
;
508 obj
->stream
.pos
= obj
->stream
.size
= 0;
510 obj
->number
= list
->number
++;
514 list
->tail
->next
= obj
;
525 static void objtext(object
*o
, char const *text
)
527 rdaddsc(&o
->main
, text
);
530 static void objstream(object
*o
, char const *text
)
532 rdaddsc(&o
->stream
, text
);
535 static void objref(object
*o
, object
*dest
)
538 sprintf(buf
, "%d 0 R", dest
->number
);
539 rdaddsc(&o
->main
, buf
);
542 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
543 page_data
*last
, object
*resources
,
550 objtext(node
, "<<\n/Type /Pages\n");
552 objtext(node
, "/Parent ");
553 objref(node
, parent
);
558 * Count the pages in this stretch, to see if there are few
559 * enough to reference directly.
562 for (page
= first
; page
; page
= page
->next
) {
568 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
571 if (count
> TREE_BRANCH
) {
573 page_data
*thisfirst
, *thislast
;
577 for (i
= 0; i
< TREE_BRANCH
; i
++) {
578 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
585 if (thisfirst
== thislast
) {
586 objref(node
, (object
*)thisfirst
->spare
);
587 objtext((object
*)thisfirst
->spare
, "/Parent ");
588 objref((object
*)thisfirst
->spare
, node
);
589 objtext((object
*)thisfirst
->spare
, "\n");
591 object
*newnode
= new_object(node
->list
);
592 make_pages_node(newnode
, node
, thisfirst
, thislast
,
594 objref(node
, newnode
);
599 assert(thislast
== last
|| page
== NULL
);
602 for (page
= first
; page
; page
= page
->next
) {
603 objref(node
, (object
*)page
->spare
);
605 objtext((object
*)page
->spare
, "/Parent ");
606 objref((object
*)page
->spare
, node
);
607 objtext((object
*)page
->spare
, "\n");
613 objtext(node
, "]\n");
616 objtext(node
, "/Resources ");
617 objref(node
, resources
);
621 objtext(node
, "/MediaBox ");
622 objref(node
, mediabox
);
626 objtext(node
, ">>\n");
630 * In text on the page, PDF uses the PostScript font model, which
631 * means that glyphs are identified by PS strings and hence font
632 * encoding can be managed independently of the supplied encoding
633 * of the font. However, in the document outline, the PDF spec
634 * encodes in either PDFDocEncoding (a custom superset of
635 * ISO-8859-1) or UTF-16BE.
637 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
640 ret
= utoa_careful_dup(s
, CS_PDF
);
643 * Very silly special case: if the returned string begins with
644 * FE FF, then the PDF reader will mistake it for a UTF-16BE
645 * string. So in this case we give up on PDFDocEncoding and
646 * encode it in UTF-16 straight away.
648 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
654 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
662 static int make_outline(object
*parent
, outline_element
*items
, int n
,
665 int level
, totalcount
= 0;
666 outline_element
*itemp
;
667 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
671 level
= items
->level
;
678 * Here we expect to be sitting on an item at the given
679 * level. So we start by constructing an outline entry for
682 assert(items
->level
== level
);
684 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
687 curr
= new_object(parent
->list
);
688 if (!first
) first
= curr
;
690 objtext(curr
, "<<\n/Title ");
691 pdf_string_len(objtext
, curr
, title
, titlelen
);
693 objtext(curr
, "\n/Parent ");
694 objref(curr
, parent
);
695 objtext(curr
, "\n/Dest [");
696 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
697 objtext(curr
, " /XYZ null null null]\n");
699 objtext(curr
, "/Prev ");
703 objtext(prev
, "/Next ");
705 objtext(prev
, "\n>>\n");
710 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
715 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
720 sprintf(buf
, "/Count %d\n", count
);
727 objtext(prev
, ">>\n");
729 assert(first
&& last
);
730 objtext(parent
, "/First ");
731 objref(parent
, first
);
732 objtext(parent
, "\n/Last ");
733 objref(parent
, last
);
734 objtext(parent
, "\n");
739 static int pdf_versionid(FILE *fp
, word
*words
)
743 ret
= fprintf(fp
, "%% ");
745 for (; words
; words
= words
->next
) {
749 switch (words
->type
) {
759 type
= removeattr(words
->type
);
763 text
= utoa_dup(words
->text
, CS_ASCII
);
765 case word_WhiteSpace
:
778 ret
+= fprintf(fp
, "\n");
783 static void pdf_string_len(void (*add
)(object
*, char const *),
784 object
*o
, char const *str
, int len
)
789 for (p
= str
; len
> 0; p
++, len
--) {
791 if (*p
< ' ' || *p
> '~') {
792 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
795 if (*p
== '\\' || *p
== '(' || *p
== ')')
805 static void pdf_string(void (*add
)(object
*, char const *),
806 object
*o
, char const *str
)
808 pdf_string_len(add
, o
, str
, strlen(str
));