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
/ FUNITS_PER_PT
);
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
/ FUNITS_PER_PT
,
207 doc
->paper_height
/ FUNITS_PER_PT
);
211 * Now we're ready to define a content stream containing
212 * the actual text on the page.
214 cstr
= new_object(&olist
);
215 objtext(opage
, "/Contents ");
217 objtext(opage
, "\n");
220 * Render any rectangles on the page.
222 for (r
= page
->first_rect
; r
; r
= r
->next
) {
224 sprintf(buf
, "%g %g %g %g re f\n",
225 r
->x
/ FUNITS_PER_PT
, r
->y
/ FUNITS_PER_PT
,
226 r
->w
/ FUNITS_PER_PT
, r
->h
/ FUNITS_PER_PT
);
227 objstream(cstr
, buf
);
230 objstream(cstr
, "BT\n");
233 * PDF tracks two separate current positions: the position
234 * given in the `line matrix' and the position given in the
235 * `text matrix'. We must therefore track both as well.
236 * They start off at -1 (unset).
241 frag
= page
->first_text
;
244 * For compactness, I'm going to group text fragments
245 * into subsequences that use the same font+size. So
246 * first find the end of this subsequence.
248 for (frag_end
= frag
;
250 frag_end
->fe
== frag
->fe
&&
251 frag_end
->fontsize
== frag
->fontsize
);
252 frag_end
= frag_end
->next
);
255 * Now select the text fragment, and prepare to display
258 objstream(cstr
, "/");
259 objstream(cstr
, frag
->fe
->name
);
260 sprintf(buf
, " %d Tf ", frag
->fontsize
);
261 objstream(cstr
, buf
);
263 while (frag
&& frag
!= frag_end
) {
265 * Place the text position for the first piece of
269 sprintf(buf
, "1 0 0 1 %g %g Tm ",
270 frag
->x
/FUNITS_PER_PT
, frag
->y
/FUNITS_PER_PT
);
272 sprintf(buf
, "%g %g Td ",
273 (frag
->x
- lx
)/FUNITS_PER_PT
,
274 (frag
->y
- ly
)/FUNITS_PER_PT
);
276 objstream(cstr
, buf
);
281 * See if we're going to use Tj (show a single
282 * string) or TJ (show an array of strings with
283 * x-spacings between them). We determine this by
284 * seeing if there's more than one text fragment in
285 * sequence with the same y-coordinate.
287 if (frag
->next
&& frag
->next
!= frag_end
&&
288 frag
->next
->y
== y
) {
292 objstream(cstr
, "[");
293 while (frag
&& frag
!= frag_end
&& frag
->y
== y
) {
296 (x
- frag
->x
) * 1000.0 /
297 (FUNITS_PER_PT
* frag
->fontsize
));
298 objstream(cstr
, buf
);
300 pdf_string(objstream
, cstr
, frag
->text
);
301 x
= frag
->x
+ frag
->width
;
304 objstream(cstr
, "]TJ\n");
310 pdf_string(objstream
, cstr
, frag
->text
);
311 objstream(cstr
, "Tj\n");
316 objstream(cstr
, "ET");
319 * Also, we want an annotation dictionary containing the
320 * cross-references from this page.
322 if (page
->first_xref
) {
324 objtext(opage
, "/Annots [\n");
326 for (xr
= page
->first_xref
; xr
; xr
= xr
->next
) {
330 annot
= new_object(&olist
);
331 objref(opage
, annot
);
332 objtext(opage
, "\n");
334 objtext(annot
, "<<\n/Type /Annot\n/Subtype /Link\n/Rect [");
335 sprintf(buf
, "%g %g %g %g",
336 xr
->lx
/ FUNITS_PER_PT
, xr
->by
/ FUNITS_PER_PT
,
337 xr
->rx
/ FUNITS_PER_PT
, xr
->ty
/ FUNITS_PER_PT
);
339 objtext(annot
, "]\n/Border [0 0 0]\n");
341 if (xr
->dest
.type
== PAGE
) {
342 objtext(annot
, "/Dest [");
343 objref(annot
, (object
*)xr
->dest
.page
->spare
);
344 objtext(annot
, " /XYZ null null null]\n");
346 objtext(annot
, "/A <<\n/Type /Action\n/S /URI\n/URI ");
347 pdf_string(objtext
, annot
, xr
->dest
.url
);
348 objtext(annot
, "\n>>\n");
351 objtext(annot
, ">>\n");
354 objtext(opage
, "]\n");
357 objtext(opage
, ">>\n");
361 * Set up the outlines dictionary.
367 objtext(outlines
, "<<\n/Type /Outlines\n");
368 topcount
= make_outline(outlines
, doc
->outline_elements
,
369 doc
->n_outline_elements
, TRUE
);
370 sprintf(buf
, "/Count %d\n>>\n", topcount
);
371 objtext(outlines
, buf
);
375 * Assemble the final linear form of every object.
377 for (o
= olist
.head
; o
; o
= o
->next
) {
378 rdstringc rs
= {0, 0, NULL
};
381 sprintf(text
, "%d 0 obj\n", o
->number
);
384 if (!o
->main
.text
&& o
->stream
.text
) {
385 sprintf(text
, "<<\n/Length %d\n>>\n", o
->stream
.pos
);
386 rdaddsc(&o
->main
, text
);
389 assert(o
->main
.text
);
390 rdaddsc(&rs
, o
->main
.text
);
393 if (rs
.text
[rs
.pos
-1] != '\n')
396 if (o
->stream
.text
) {
398 * FIXME: If we ever start compressing stream data then
399 * it will have zero bytes in it, so we'll have to be
400 * more careful than this.
402 rdaddsc(&rs
, "stream\n");
403 rdaddsc(&rs
, o
->stream
.text
);
404 rdaddsc(&rs
, "\nendstream\n");
405 sfree(o
->stream
.text
);
408 rdaddsc(&rs
, "endobj\n");
415 * Write out the PDF file.
418 fp
= fopen(filename
, "wb");
420 error(err_cantopenw
, filename
);
425 * Header. I'm going to put the version IDs in the header as
426 * well, simply in PDF comments.
428 fileoff
= fprintf(fp
, "%%PDF-1.3\n");
429 for (p
= sourceform
; p
; p
= p
->next
)
430 if (p
->type
== para_VersionID
)
431 fileoff
+= pdf_versionid(fp
, p
->words
);
436 for (o
= olist
.head
; o
; o
= o
->next
) {
437 o
->fileoff
= fileoff
;
438 fwrite(o
->final
, 1, o
->size
, fp
);
443 * Cross-reference table
445 fprintf(fp
, "xref\n");
446 assert(olist
.head
->number
== 1);
447 fprintf(fp
, "0 %d\n", olist
.tail
->number
+ 1);
448 fprintf(fp
, "0000000000 65535 f \n");
449 for (o
= olist
.head
; o
; o
= o
->next
) {
451 sprintf(entry
, "%010d 00000 n \n", o
->fileoff
);
452 assert(strlen(entry
) == 20);
459 fprintf(fp
, "trailer\n<<\n/Size %d\n/Root %d 0 R\n>>\n",
460 olist
.tail
->number
+ 1, cat
->number
);
461 fprintf(fp
, "startxref\n%d\n%%%%EOF\n", fileoff
);
468 static object
*new_object(objlist
*list
)
470 object
*obj
= snew(object
);
474 obj
->main
.text
= NULL
;
475 obj
->main
.pos
= obj
->main
.size
= 0;
476 obj
->stream
.text
= NULL
;
477 obj
->stream
.pos
= obj
->stream
.size
= 0;
479 obj
->number
= list
->number
++;
483 list
->tail
->next
= obj
;
494 static void objtext(object
*o
, char const *text
)
496 rdaddsc(&o
->main
, text
);
499 static void objstream(object
*o
, char const *text
)
501 rdaddsc(&o
->stream
, text
);
504 static void objref(object
*o
, object
*dest
)
507 sprintf(buf
, "%d 0 R", dest
->number
);
508 rdaddsc(&o
->main
, buf
);
511 static void make_pages_node(object
*node
, object
*parent
, page_data
*first
,
512 page_data
*last
, object
*resources
)
518 objtext(node
, "<<\n/Type /Pages\n");
520 objtext(node
, "/Parent ");
521 objref(node
, parent
);
526 * Count the pages in this stretch, to see if there are few
527 * enough to reference directly.
530 for (page
= first
; page
; page
= page
->next
) {
536 sprintf(buf
, "/Count %d\n/Kids [\n", count
);
539 if (count
> TREE_BRANCH
) {
541 page_data
*thisfirst
, *thislast
;
545 for (i
= 0; i
< TREE_BRANCH
; i
++) {
546 int number
= (i
+1) * count
/ TREE_BRANCH
- i
* count
/ TREE_BRANCH
;
553 if (thisfirst
== thislast
) {
554 objref(node
, (object
*)thisfirst
->spare
);
555 objtext((object
*)thisfirst
->spare
, "/Parent ");
556 objref((object
*)thisfirst
->spare
, node
);
557 objtext((object
*)thisfirst
->spare
, "\n");
559 object
*newnode
= new_object(node
->list
);
560 make_pages_node(newnode
, node
, thisfirst
, thislast
, NULL
);
561 objref(node
, newnode
);
566 assert(thislast
== last
|| page
== NULL
);
569 for (page
= first
; page
; page
= page
->next
) {
570 objref(node
, (object
*)page
->spare
);
572 objtext((object
*)page
->spare
, "/Parent ");
573 objref((object
*)page
->spare
, node
);
574 objtext((object
*)page
->spare
, "\n");
580 objtext(node
, "]\n");
583 objtext(node
, "/Resources ");
584 objref(node
, resources
);
588 objtext(node
, ">>\n");
592 * In text on the page, PDF uses the PostScript font model, which
593 * means that glyphs are identified by PS strings and hence font
594 * encoding can be managed independently of the supplied encoding
595 * of the font. However, in the document outline, the PDF spec
596 * encodes in either PDFDocEncoding (a custom superset of
597 * ISO-8859-1) or UTF-16BE.
599 static char *pdf_outline_convert(wchar_t *s
, int *len
) {
602 ret
= utoa_careful_dup(s
, CS_PDF
);
605 * Very silly special case: if the returned string begins with
606 * FE FF, then the PDF reader will mistake it for a UTF-16BE
607 * string. So in this case we give up on PDFDocEncoding and
608 * encode it in UTF-16 straight away.
610 if (ret
&& ret
[0] == '\xFE' && ret
[1] == '\xFF') {
616 ret
= utoa_dup_len(s
, CS_UTF16BE
, len
);
624 static int make_outline(object
*parent
, outline_element
*items
, int n
,
627 int level
, totalcount
= 0;
628 outline_element
*itemp
;
629 object
*curr
, *prev
= NULL
, *first
= NULL
, *last
= NULL
;
633 level
= items
->level
;
640 * Here we expect to be sitting on an item at the given
641 * level. So we start by constructing an outline entry for
644 assert(items
->level
== level
);
646 title
= pdf_outline_convert(items
->pdata
->outline_title
, &titlelen
);
649 curr
= new_object(parent
->list
);
650 if (!first
) first
= curr
;
652 objtext(curr
, "<<\n/Title ");
653 pdf_string_len(objtext
, curr
, title
, titlelen
);
654 objtext(curr
, "\n/Parent ");
655 objref(curr
, parent
);
656 objtext(curr
, "\n/Dest [");
657 objref(curr
, (object
*)items
->pdata
->first
->page
->spare
);
658 objtext(curr
, " /XYZ null null null]\n");
660 objtext(curr
, "/Prev ");
664 objtext(prev
, "/Next ");
666 objtext(prev
, "\n>>\n");
671 for (itemp
= items
; itemp
< items
+n
&& itemp
->level
> level
;
676 int count
= make_outline(curr
, items
, itemp
- items
, FALSE
);
681 sprintf(buf
, "/Count %d\n", count
);
688 objtext(prev
, ">>\n");
690 assert(first
&& last
);
691 objtext(parent
, "/First ");
692 objref(parent
, first
);
693 objtext(parent
, "\n/Last ");
694 objref(parent
, last
);
695 objtext(parent
, "\n");
700 static int pdf_versionid(FILE *fp
, word
*words
)
704 ret
= fprintf(fp
, "%% ");
706 for (; words
; words
= words
->next
) {
710 switch (words
->type
) {
720 type
= removeattr(words
->type
);
724 text
= utoa_dup(words
->text
, CS_ASCII
);
726 case word_WhiteSpace
:
739 ret
+= fprintf(fp
, "\n");
744 static void pdf_string_len(void (*add
)(object
*, char const *),
745 object
*o
, char const *str
, int len
)
750 for (p
= str
; len
> 0; p
++, len
--) {
752 if (*p
< ' ' || *p
> '~') {
753 sprintf(c
, "\\%03o", 0xFF & (int)*p
);
756 if (*p
== '\\' || *p
== '(' || *p
== ')')
766 static void pdf_string(void (*add
)(object
*, char const *),
767 object
*o
, char const *str
)
769 pdf_string_len(add
, o
, str
, strlen(str
));