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
->info
->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 int firstchar
= -1, lastchar
= -1;
169 for (i
= 0; i
< 256; i
++)
170 if (fe
->indices
[i
] >= 0) {
171 if (firstchar
< 0) firstchar
= i
;
174 sprintf(buf
, "/FirstChar %d\n/LastChar %d\n/Widths ",
175 firstchar
, lastchar
);
177 objref(font
, widths
);
179 objtext(widths
, "[\n");
180 for (i
= firstchar
; i
<= lastchar
; i
++) {
183 if (fe
->indices
[i
] < 0)
186 width
= fe
->font
->info
->widths
[fe
->indices
[i
]];
187 sprintf(buf
, "%g\n", 1000.0 * width
/ FUNITS_PER_PT
);
188 objtext(widths
, buf
);
190 objtext(widths
, "]\n");
193 objtext(font
, ">>\n");
195 objtext(resources
, ">>\n>>\n");
199 mediabox
= new_object(&olist
);
200 sprintf(buf
, "[0 0 %g %g]\n",
201 doc
->paper_width
/ FUNITS_PER_PT
,
202 doc
->paper_height
/ FUNITS_PER_PT
);
203 objtext(mediabox
, buf
);
207 * Define the page objects for each page, and get each one
208 * ready to have a `Parent' specification added to it.
210 for (page
= doc
->pages
; page
; page
= page
->next
) {
213 opage
= new_object(&olist
);
215 objtext(opage
, "<<\n/Type /Page\n");
219 * Recursively build the page tree.
221 make_pages_node(pages
, NULL
, doc
->pages
, NULL
, resources
, mediabox
);
224 * Create and render the individual pages.
227 for (page
= doc
->pages
; page
; page
= page
->next
) {
228 object
*opage
, *cstr
;
230 text_fragment
*frag
, *frag_end
;
234 opage
= (object
*)page
->spare
;
236 * At this point the page dictionary is already
237 * half-written, with /Type and /Parent already present. We
238 * continue from there.
242 * The PDF spec says /Resources is required, but also says
243 * that it's inheritable and may be omitted if it's present
244 * in a Pages node. In our case it is: it's present in the
245 * topmost /Pages node because we carefully put it there.
246 * So we don't need a /Resources entry here. The same applies
251 * Now we're ready to define a content stream containing
252 * the actual text on the page.
254 cstr
= new_object(&olist
);
255 objtext(opage
, "/Contents ");
257 objtext(opage
, "\n");
260 * Render any rectangles on the page.
262 for (r
= page
->first_rect
; r
; r
= r
->next
) {
264 sprintf(buf
, "%g %g %g %g re f\n",
265 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
266 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
267 objstream(cstr
, buf
);
270 objstream(cstr
, "BT\n");
273 * PDF tracks two separate current positions: the position
274 * given in the `line matrix' and the position given in the
275 * `text matrix'. We must therefore track both as well.
276 * They start off at -1 (unset).
281 frag
= page
->first_text
;
284 * For compactness, I'm going to group text fragments
285 * into subsequences that use the same font+size. So
286 * first find the end of this subsequence.
288 for (frag_end
= frag
;
290 frag_end
->fe
== frag
->fe
&&
291 frag_end
->fontsize
== frag
->fontsize
);
292 frag_end
= frag_end
->next
);
295 * Now select the text fragment, and prepare to display
298 objstream(cstr
, "/");
299 objstream(cstr
, frag
->fe
->name
);
300 sprintf(buf
, " %d Tf ", frag
->fontsize
);
301 objstream(cstr
, buf
);
303 while (frag
&& frag
!= frag_end
) {
305 * Place the text position for the first piece of
309 sprintf(buf
, "1 0 0 1 %g %g Tm ",
310 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
312 sprintf(buf
, "%g %g Td ",
313 (frag
->x
- lx
)/FUNITS_PER_PT
,
314 (frag
->y
- ly
)/FUNITS_PER_PT
);
316 objstream(cstr
, buf
);
321 * See if we're going to use Tj (show a single
322 * string) or TJ (show an array of strings with
323 * x-spacings between them). We determine this by
324 * seeing if there's more than one text fragment in
325 * sequence with the same y-coordinate.
327 if (frag
->next
&& frag
->next
!= frag_end
&&
328 frag
->next
->y
== y
) {
332 objstream(cstr
, "[");
333 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
336 (x
- frag
->x
) * 1000.0 /
337 (FUNITS_PER_PT
* frag
->fontsize
));
338 objstream(cstr
, buf
);
340 pdf_string(objstream
, cstr
, frag
->text
);
341 x
= frag
->x
+ frag
->width
;
344 objstream(cstr
, "]TJ\n");
350 pdf_string(objstream
, cstr
, frag
->text
);
351 objstream(cstr
, "Tj\n");
356 objstream(cstr
, "ET");
359 * Also, we want an annotation dictionary containing the
360 * cross-references from this page.
362 if (page
->first_xref
) {
364 objtext(opage
, "/Annots [\n");
366 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
370 annot
= new_object(&olist
);
371 objref(opage
, annot
);
372 objtext(opage
, "\n");
374 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
375 sprintf(buf
, "%g %g %g %g",
376 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
377 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
379 objtext(annot
, "]\n/Border [0 0 0]\n");
381 if (xr
->dest
.type
== PAGE
) {
382 objtext(annot
, "/Dest [");
383 objref(annot
, (object
*)xr
->dest
.page
->spare
);
384 objtext(annot
, " /XYZ null null null]\n");
386 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
387 pdf_string(objtext
, annot
, xr
->dest
.url
);
388 objtext(annot
, "\n>>\n");
391 objtext(annot
, ">>\n");
394 objtext(opage
, "]\n");
397 objtext(opage
, ">>\n");
401 * Set up the outlines dictionary.
407 objtext(outlines
, "<<\n/Type /Outlines\n");
408 topcount
= make_outline(outlines
, doc
->outline_elements
,
409 doc
->n_outline_elements
, TRUE
);
410 sprintf(buf
, "/Count %d\n>>\n", topcount
);
411 objtext(outlines
, buf
);
415 * Assemble the final linear form of every object.
417 for (o
= olist
.head
; o
; o
= o
->next
) {
418 rdstringc rs
= {0, 0, NULL
};
421 sprintf(text
, "%d 0 obj\n", o
->number
);
424 if (!o
->main
.text
&& o
->stream
.text
) {
425 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
426 rdaddsc(&o
->main
, text
);
429 assert(o
->main
.text
);
430 rdaddsc(&rs
, o
->main
.text
);
433 if (rs
.text
[rs
.pos
-1] != '\n')
436 if (o
->stream
.text
) {
438 * FIXME: If we ever start compressing stream data then
439 * it will have zero bytes in it, so we'll have to be
440 * more careful than this.
442 rdaddsc(&rs
, "stream\n");
443 rdaddsc(&rs
, o
->stream
.text
);
444 rdaddsc(&rs
, "\nendstream\n");
445 sfree(o
->stream
.text
);
448 rdaddsc(&rs
, "endobj\n");
455 * Write out the PDF file.
458 fp
= fopen(filename
, "wb");
460 error(err_cantopenw
, filename
);
465 * Header. I'm going to put the version IDs in the header as
466 * well, simply in PDF comments.
468 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
469 for (p
= sourceform
; p
; p
= p
->next
)
470 if (p
->type
== para_VersionID
)
471 fileoff
+= pdf_versionid(fp
, p
->words
);
476 for (o
= olist
.head
; o
; o
= o
->next
) {
477 o
->fileoff
= fileoff
;
478 fwrite(o
->final
, 1, o
->size
, fp
);
483 * Cross-reference table
485 fprintf(fp
, "xref\n");
486 assert(olist
.head
->number
== 1);
487 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
488 fprintf(fp
, "0000000000 65535 f \n");
489 for (o
= olist
.head
; o
; o
= o
->next
) {
491 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
492 assert(strlen(entry
) == 20);
499 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n",
500 olist
.tail
->number
+ 1, cat
->number
, info
->number
);
501 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
508 static object
*new_object(objlist
*list
)
510 object
*obj
= snew(object
);
514 obj
->main
.text
= NULL
;
515 obj
->main
.pos
= obj
->main
.size
= 0;
516 obj
->stream
.text
= NULL
;
517 obj
->stream
.pos
= obj
->stream
.size
= 0;
519 obj
->number
= list
->number
++;
523 list
->tail
->next
= obj
;
534 static void objtext(object
*o
, char const *text
)
536 rdaddsc(&o
->main
, text
);
539 static void objstream(object
*o
, char const *text
)
541 rdaddsc(&o
->stream
, text
);
544 static void objref(object
*o
, object
*dest
)
547 sprintf(buf
, "%d 0 R", dest
->number
);
548 rdaddsc(&o
->main
, buf
);
551 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
552 page_data
*last
, object
*resources
,
559 objtext(node
, "<<\n/Type /Pages\n");
561 objtext(node
, "/Parent ");
562 objref(node
, parent
);
567 * Count the pages in this stretch, to see if there are few
568 * enough to reference directly.
571 for (page
= first
; page
; page
= page
->next
) {
577 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
580 if (count
> TREE_BRANCH
) {
582 page_data
*thisfirst
, *thislast
;
586 for (i
= 0; i
< TREE_BRANCH
; i
++) {
587 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
594 if (thisfirst
== thislast
) {
595 objref(node
, (object
*)thisfirst
->spare
);
596 objtext((object
*)thisfirst
->spare
, "/Parent ");
597 objref((object
*)thisfirst
->spare
, node
);
598 objtext((object
*)thisfirst
->spare
, "\n");
600 object
*newnode
= new_object(node
->list
);
601 make_pages_node(newnode
, node
, thisfirst
, thislast
,
603 objref(node
, newnode
);
608 assert(thislast
== last
|| page
== NULL
);
611 for (page
= first
; page
; page
= page
->next
) {
612 objref(node
, (object
*)page
->spare
);
614 objtext((object
*)page
->spare
, "/Parent ");
615 objref((object
*)page
->spare
, node
);
616 objtext((object
*)page
->spare
, "\n");
622 objtext(node
, "]\n");
625 objtext(node
, "/Resources ");
626 objref(node
, resources
);
630 objtext(node
, "/MediaBox ");
631 objref(node
, mediabox
);
635 objtext(node
, ">>\n");
639 * In text on the page, PDF uses the PostScript font model, which
640 * means that glyphs are identified by PS strings and hence font
641 * encoding can be managed independently of the supplied encoding
642 * of the font. However, in the document outline, the PDF spec
643 * encodes in either PDFDocEncoding (a custom superset of
644 * ISO-8859-1) or UTF-16BE.
646 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
649 ret
= utoa_careful_dup(s
, CS_PDF
);
652 * Very silly special case: if the returned string begins with
653 * FE FF, then the PDF reader will mistake it for a UTF-16BE
654 * string. So in this case we give up on PDFDocEncoding and
655 * encode it in UTF-16 straight away.
657 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
663 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
671 static int make_outline(object
*parent
, outline_element
*items
, int n
,
674 int level
, totalcount
= 0;
675 outline_element
*itemp
;
676 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
680 level
= items
->level
;
687 * Here we expect to be sitting on an item at the given
688 * level. So we start by constructing an outline entry for
691 assert(items
->level
== level
);
693 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
696 curr
= new_object(parent
->list
);
697 if (!first
) first
= curr
;
699 objtext(curr
, "<<\n/Title ");
700 pdf_string_len(objtext
, curr
, title
, titlelen
);
702 objtext(curr
, "\n/Parent ");
703 objref(curr
, parent
);
704 objtext(curr
, "\n/Dest [");
705 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
706 objtext(curr
, " /XYZ null null null]\n");
708 objtext(curr
, "/Prev ");
712 objtext(prev
, "/Next ");
714 objtext(prev
, "\n>>\n");
719 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
724 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
729 sprintf(buf
, "/Count %d\n", count
);
736 objtext(prev
, ">>\n");
738 assert(first
&& last
);
739 objtext(parent
, "/First ");
740 objref(parent
, first
);
741 objtext(parent
, "\n/Last ");
742 objref(parent
, last
);
743 objtext(parent
, "\n");
748 static int pdf_versionid(FILE *fp
, word
*words
)
752 ret
= fprintf(fp
, "%% ");
754 for (; words
; words
= words
->next
) {
758 switch (words
->type
) {
768 type
= removeattr(words
->type
);
772 text
= utoa_dup(words
->text
, CS_ASCII
);
774 case word_WhiteSpace
:
787 ret
+= fprintf(fp
, "\n");
792 static void pdf_string_len(void (*add
)(object
*, char const *),
793 object
*o
, char const *str
, int len
)
798 for (p
= str
; len
> 0; p
++, len
--) {
800 if (*p
< ' ' || *p
> '~') {
801 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
804 if (*p
== '\\' || *p
== '(' || *p
== ')')
814 static void pdf_string(void (*add
)(object
*, char const *),
815 object
*o
, char const *str
)
817 pdf_string_len(add
, o
, str
, strlen(str
));