X-Git-Url: https://git.distorted.org.uk/~mdw/sgt/halibut/blobdiff_plain/4334192268c4b1c0c27a91d043792a21bd8d1292..3e32e06c2e95cae66f921be9da2a0993f4fde752:/bk_pdf.c diff --git a/bk_pdf.c b/bk_pdf.c index 44f7486..0a36ad9 100644 --- a/bk_pdf.c +++ b/bk_pdf.c @@ -10,30 +10,7 @@ paragraph *pdf_config_filename(char *filename) { - paragraph *p; - wchar_t *ufilename, *up; - int len; - - p = mknew(paragraph); - memset(p, 0, sizeof(*p)); - p->type = para_Config; - p->next = NULL; - p->fpos.filename = ""; - p->fpos.line = p->fpos.col = -1; - - ufilename = ufroma_dup(filename); - len = ustrlen(ufilename) + 2 + lenof(L"pdf-filename"); - p->keyword = mknewa(wchar_t, len); - up = p->keyword; - ustrcpy(up, L"pdf-filename"); - up = uadv(up); - ustrcpy(up, ufilename); - up = uadv(up); - *up = L'\0'; - assert(up - p->keyword < len); - sfree(ufilename); - - return p; + return cmdline_cfg_simple("pdf-filename", filename, NULL); } typedef struct object_Tag object; @@ -56,10 +33,21 @@ struct objlist_Tag { static object *new_object(objlist *list); static void objtext(object *o, char const *text); static void objstream(object *o, char const *text); +static void pdf_string(void (*add)(object *, char const *), + object *, char const *); +static void pdf_string_len(void (*add)(object *, char const *), + object *, char const *, int); static void objref(object *o, object *dest); +static char *pdf_outline_convert(wchar_t *s, int *len); + +static int is_std_font(char const *name); static void make_pages_node(object *node, object *parent, page_data *first, - page_data *last, object *resources); + page_data *last, object *resources, + object *mediabox); +static int make_outline(object *parent, outline_element *start, int n, + int open); +static int pdf_versionid(FILE *fp, word *words); void pdf_backend(paragraph *sourceform, keywordlist *keywords, indexdata *idx, void *vdoc) { @@ -72,7 +60,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, char *filename; paragraph *p; objlist olist; - object *o, *cat, *outlines, *pages, *resources; + object *o, *info, *cat, *outlines, *pages, *resources, *mediabox; int fileoff; IGNORE(keywords); @@ -80,11 +68,10 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, filename = dupstr("output.pdf"); for (p = sourceform; p; p = p->next) { - p->private_data = NULL; - if (p->type == para_Config && p->parent) { + if (p->type == para_Config) { if (!ustricmp(p->keyword, L"pdf-filename")) { sfree(filename); - filename = utoa_dup(uadv(p->keyword)); + filename = dupstr(adv(p->origkeyword)); } } } @@ -92,25 +79,50 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, olist.head = olist.tail = NULL; olist.number = 1; + { + char buf[256]; + + info = new_object(&olist); + objtext(info, "<<\n"); + if (doc->n_outline_elements > 0) { + char *title; + int titlelen; + + title = + pdf_outline_convert(doc->outline_elements->pdata->outline_title, + &titlelen); + objtext(info, "/Title "); + pdf_string_len(objtext, info, title, titlelen); + sfree(title); + objtext(info, "\n"); + } + objtext(info, "/Producer "); + sprintf(buf, "Halibut, %s", version); + pdf_string(objtext, info, buf); + objtext(info, "\n>>\n"); + } + cat = new_object(&olist); - outlines = new_object(&olist); + if (doc->n_outline_elements > 0) + outlines = new_object(&olist); + else + outlines = NULL; pages = new_object(&olist); resources = new_object(&olist); /* - * We currently don't support outlines, so here's a null - * outlines dictionary. - */ - objtext(outlines, "<<\n/Type Outlines\n/Count 0\n>>\n"); - - /* * The catalogue just contains references to the outlines and * pages objects. */ - objtext(cat, "<<\n/Type /Catalog\n/Outlines "); - objref(cat, outlines); + objtext(cat, "<<\n/Type /Catalog"); + if (outlines) { + objtext(cat, "\n/Outlines "); + objref(cat, outlines); + } objtext(cat, "\n/Pages "); objref(cat, pages); + if (outlines) + objtext(cat, "\n/PageMode /UseOutlines"); objtext(cat, "\n>>\n"); /* @@ -138,7 +150,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, objtext(font, "<<\n/Type /Font\n/Subtype /Type1\n/Name /"); objtext(font, fe->name); objtext(font, "\n/BaseFont /"); - objtext(font, fe->font->name); + objtext(font, fe->font->info->name); objtext(font, "\n/Encoding <<\n/Type /Encoding\n/Differences ["); for (i = 0; i < 256; i++) { @@ -152,29 +164,99 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, objtext(font, "\n]\n>>\n"); - { +#define FF_FIXEDPITCH 0x00000001 +#define FF_SERIF 0x00000002 +#define FF_SYMBOLIC 0x00000004 +#define FF_SCRIPT 0x00000008 +#define FF_NONSYMBOLIC 0x00000020 +#define FF_ITALIC 0x00000040 +#define FF_ALLCAP 0x00010000 +#define FF_SMALLCAP 0x00020000 +#define FF_FORCEBOLD 0x00040000 + + if (!is_std_font(fe->font->info->name)){ object *widths = new_object(&olist); - objtext(font, "/FirstChar 0\n/LastChar 255\n/Widths "); + object *fontdesc = new_object(&olist); + int firstchar = -1, lastchar = -1; + char buf[80]; + font_info const *fi = fe->font->info; + int flags; + for (i = 0; i < 256; i++) + if (fe->indices[i] >= 0) { + if (firstchar < 0) firstchar = i; + lastchar = i; + } + sprintf(buf, "/FirstChar %d\n/LastChar %d\n/Widths ", + firstchar, lastchar); + objtext(font, buf); objref(font, widths); objtext(font, "\n"); objtext(widths, "[\n"); - for (i = 0; i < 256; i++) { - char buf[80]; + for (i = firstchar; i <= lastchar; i++) { double width; if (fe->indices[i] < 0) width = 0.0; else - width = fe->font->widths[fe->indices[i]]; - sprintf(buf, "%g\n", 1000.0 * width / 4096.0); + width = fi->widths[fe->indices[i]]; + sprintf(buf, "%g\n", 1000.0 * width / FUNITS_PER_PT); objtext(widths, buf); } objtext(widths, "]\n"); + objtext(font, "/FontDescriptor "); + objref(font, fontdesc); + objtext(fontdesc, "<<\n/Type /FontDescriptor\n/Name /"); + objtext(fontdesc, fi->name); + flags = 0; + if (fi->italicangle) flags |= FF_ITALIC; + flags |= FF_NONSYMBOLIC; + sprintf(buf, "\n/Flags %d\n", flags); + objtext(fontdesc, buf); + sprintf(buf, "/FontBBox [%g %g %g %g]\n", fi->fontbbox[0], + fi->fontbbox[1], fi->fontbbox[2], fi->fontbbox[3]); + objtext(fontdesc, buf); + sprintf(buf, "/ItalicAngle %g\n", fi->italicangle); + objtext(fontdesc, buf); + sprintf(buf, "/Ascent %g\n", fi->ascent); + objtext(fontdesc, buf); + sprintf(buf, "/Descent %g\n", fi->descent); + objtext(fontdesc, buf); + sprintf(buf, "/CapHeight %g\n", fi->capheight); + objtext(fontdesc, buf); + sprintf(buf, "/XHeight %g\n", fi->xheight); + objtext(fontdesc, buf); + sprintf(buf, "/StemH %g\n", fi->stemh); + objtext(fontdesc, buf); + sprintf(buf, "/StemV %g\n", fi->stemv); + objtext(fontdesc, buf); + if (fi->fp) { + object *fontfile = new_object(&olist); + char buf[513]; + size_t len; + rewind(fi->fp); + do { + len = fread(buf, 1, sizeof(buf)-1, fi->fp); + buf[len] = 0; + objstream(fontfile, buf); + } while (len == sizeof(buf)-1); + objtext(fontdesc, "/FontFile "); + objref(fontdesc, fontfile); + } + objtext(fontdesc, "\n>>\n"); } - objtext(font, ">>\n"); + objtext(font, "\n>>\n"); } objtext(resources, ">>\n>>\n"); + { + char buf[255]; + mediabox = new_object(&olist); + sprintf(buf, "[0 0 %g %g]\n", + doc->paper_width / FUNITS_PER_PT, + doc->paper_height / FUNITS_PER_PT); + objtext(mediabox, buf); + } + /* * Define the page objects for each page, and get each one * ready to have a `Parent' specification added to it. @@ -190,7 +272,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, /* * Recursively build the page tree. */ - make_pages_node(pages, NULL, doc->pages, NULL, resources); + make_pages_node(pages, NULL, doc->pages, NULL, resources, mediabox); /* * Create and render the individual pages. @@ -198,8 +280,10 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, pageno = 0; for (page = doc->pages; page; page = page->next) { object *opage, *cstr; - text_fragment *frag; + rect *r; + text_fragment *frag, *frag_end; char buf[256]; + int x, y, lx, ly; opage = (object *)page->spare; /* @@ -213,11 +297,9 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, * that it's inheritable and may be omitted if it's present * in a Pages node. In our case it is: it's present in the * topmost /Pages node because we carefully put it there. - * So we don't need a /Resources entry here. + * So we don't need a /Resources entry here. The same applies + * to /MediaBox. */ - sprintf(buf, "/MediaBox [0 0 %g %g]\n", - doc->paper_width / 4096.0, doc->paper_height / 4096.0); - objtext(opage, buf); /* * Now we're ready to define a content stream containing @@ -228,32 +310,162 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, objref(opage, cstr); objtext(opage, "\n"); + /* + * Render any rectangles on the page. + */ + for (r = page->first_rect; r; r = r->next) { + char buf[512]; + sprintf(buf, "%g %g %g %g re f\n", + r->x / FUNITS_PER_PT, r->y / FUNITS_PER_PT, + r->w / FUNITS_PER_PT, r->h / FUNITS_PER_PT); + objstream(cstr, buf); + } + objstream(cstr, "BT\n"); - for (frag = page->first_text; frag; frag = frag->next) { - char *c; + /* + * PDF tracks two separate current positions: the position + * given in the `line matrix' and the position given in the + * `text matrix'. We must therefore track both as well. + * They start off at -1 (unset). + */ + lx = ly = -1; + x = y = -1; + + frag = page->first_text; + while (frag) { + /* + * For compactness, I'm going to group text fragments + * into subsequences that use the same font+size. So + * first find the end of this subsequence. + */ + for (frag_end = frag; + (frag_end && + frag_end->fe == frag->fe && + frag_end->fontsize == frag->fontsize); + frag_end = frag_end->next); + + /* + * Now select the text fragment, and prepare to display + * the text. + */ objstream(cstr, "/"); objstream(cstr, frag->fe->name); - sprintf(buf, " %d Tf 1 0 0 1 %g %g Tm (", frag->fontsize, - frag->x/4096.0, frag->y/4096.0); + sprintf(buf, " %d Tf ", frag->fontsize); objstream(cstr, buf); - for (c = frag->text; *c; c++) { - if (*c == '(' || *c == ')' || *c == '\\') - objstream(cstr, "\\"); - buf[0] = *c; - buf[1] = '\0'; + while (frag && frag != frag_end) { + /* + * Place the text position for the first piece of + * text. + */ + if (lx < 0) { + sprintf(buf, "1 0 0 1 %g %g Tm ", + frag->x/FUNITS_PER_PT, frag->y/FUNITS_PER_PT); + } else { + sprintf(buf, "%g %g Td ", + (frag->x - lx)/FUNITS_PER_PT, + (frag->y - ly)/FUNITS_PER_PT); + } objstream(cstr, buf); + lx = x = frag->x; + ly = y = frag->y; + + /* + * See if we're going to use Tj (show a single + * string) or TJ (show an array of strings with + * x-spacings between them). We determine this by + * seeing if there's more than one text fragment in + * sequence with the same y-coordinate. + */ + if (frag->next && frag->next != frag_end && + frag->next->y == y) { + /* + * The TJ strategy. + */ + objstream(cstr, "["); + while (frag && frag != frag_end && frag->y == y) { + if (frag->x != x) { + sprintf(buf, "%g", + (x - frag->x) * 1000.0 / + (FUNITS_PER_PT * frag->fontsize)); + objstream(cstr, buf); + } + pdf_string(objstream, cstr, frag->text); + x = frag->x + frag->width; + frag = frag->next; + } + objstream(cstr, "]TJ\n"); + } else + { + /* + * The Tj strategy. + */ + pdf_string(objstream, cstr, frag->text); + objstream(cstr, "Tj\n"); + frag = frag->next; + } } - - objstream(cstr, ") Tj\n"); } objstream(cstr, "ET"); + /* + * Also, we want an annotation dictionary containing the + * cross-references from this page. + */ + if (page->first_xref) { + xref *xr; + objtext(opage, "/Annots [\n"); + + for (xr = page->first_xref; xr; xr = xr->next) { + object *annot; + char buf[256]; + + annot = new_object(&olist); + objref(opage, annot); + objtext(opage, "\n"); + + objtext(annot, "<<\n/Type /Annot\n/Subtype /Link\n/Rect ["); + sprintf(buf, "%g %g %g %g", + xr->lx / FUNITS_PER_PT, xr->by / FUNITS_PER_PT, + xr->rx / FUNITS_PER_PT, xr->ty / FUNITS_PER_PT); + objtext(annot, buf); + objtext(annot, "]\n/Border [0 0 0]\n"); + + if (xr->dest.type == PAGE) { + objtext(annot, "/Dest ["); + objref(annot, (object *)xr->dest.page->spare); + objtext(annot, " /XYZ null null null]\n"); + } else { + objtext(annot, "/A <<\n/Type /Action\n/S /URI\n/URI "); + pdf_string(objtext, annot, xr->dest.url); + objtext(annot, "\n>>\n"); + } + + objtext(annot, ">>\n"); + } + + objtext(opage, "]\n"); + } + objtext(opage, ">>\n"); } /* + * Set up the outlines dictionary. + */ + if (outlines) { + int topcount; + char buf[80]; + + objtext(outlines, "<<\n/Type /Outlines\n"); + topcount = make_outline(outlines, doc->outline_elements, + doc->n_outline_elements, TRUE); + sprintf(buf, "/Count %d\n>>\n", topcount); + objtext(outlines, buf); + } + + /* * Assemble the final linear form of every object. */ for (o = olist.head; o; o = o->next) { @@ -304,9 +516,13 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, } /* - * Header + * Header. I'm going to put the version IDs in the header as + * well, simply in PDF comments. */ fileoff = fprintf(fp, "%%PDF-1.3\n"); + for (p = sourceform; p; p = p->next) + if (p->type == para_VersionID) + fileoff += pdf_versionid(fp, p->words); /* * Body @@ -334,8 +550,8 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, /* * Trailer */ - fprintf(fp, "trailer\n<<\n/Size %d\n/Root %d 0 R\n>>\n", - olist.tail->number + 1, cat->number); + fprintf(fp, "trailer\n<<\n/Size %d\n/Root %d 0 R\n/Info %d 0 R\n>>\n", + olist.tail->number + 1, cat->number, info->number); fprintf(fp, "startxref\n%d\n%%%%EOF\n", fileoff); fclose(fp); @@ -345,7 +561,7 @@ void pdf_backend(paragraph *sourceform, keywordlist *keywords, static object *new_object(objlist *list) { - object *obj = mknew(object); + object *obj = snew(object); obj->list = list; @@ -386,8 +602,24 @@ static void objref(object *o, object *dest) rdaddsc(&o->main, buf); } +static char const * const stdfonts[] = { + "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic", + "Helvetica", "Helvetica-Bold", "Helvetica-Oblique","Helvetica-BoldOblique", + "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", + "Symbol", "ZapfDingbats" +}; + +static int is_std_font(char const *name) { + unsigned i; + for (i = 0; i < lenof(stdfonts); i++) + if (strcmp(name, stdfonts[i]) == 0) + return TRUE; + return FALSE; +} + static void make_pages_node(object *node, object *parent, page_data *first, - page_data *last, object *resources) + page_data *last, object *resources, + object *mediabox) { int count; page_data *page; @@ -435,7 +667,8 @@ static void make_pages_node(object *node, object *parent, page_data *first, objtext((object *)thisfirst->spare, "\n"); } else { object *newnode = new_object(node->list); - make_pages_node(newnode, node, thisfirst, thislast, NULL); + make_pages_node(newnode, node, thisfirst, thislast, + NULL, NULL); objref(node, newnode); } objtext(node, "\n"); @@ -462,6 +695,193 @@ static void make_pages_node(object *node, object *parent, page_data *first, objref(node, resources); objtext(node, "\n"); } + if (mediabox) { + objtext(node, "/MediaBox "); + objref(node, mediabox); + objtext(node, "\n"); + } objtext(node, ">>\n"); } + +/* + * In text on the page, PDF uses the PostScript font model, which + * means that glyphs are identified by PS strings and hence font + * encoding can be managed independently of the supplied encoding + * of the font. However, in the document outline, the PDF spec + * encodes in either PDFDocEncoding (a custom superset of + * ISO-8859-1) or UTF-16BE. + */ +static char *pdf_outline_convert(wchar_t *s, int *len) { + char *ret; + + ret = utoa_careful_dup(s, CS_PDF); + + /* + * Very silly special case: if the returned string begins with + * FE FF, then the PDF reader will mistake it for a UTF-16BE + * string. So in this case we give up on PDFDocEncoding and + * encode it in UTF-16 straight away. + */ + if (ret && ret[0] == '\xFE' && ret[1] == '\xFF') { + sfree(ret); + ret = NULL; + } + + if (!ret) { + ret = utoa_dup_len(s, CS_UTF16BE, len); + } else { + *len = strlen(ret); + } + + return ret; +} + +static int make_outline(object *parent, outline_element *items, int n, + int open) +{ + int level, totalcount = 0; + outline_element *itemp; + object *curr, *prev = NULL, *first = NULL, *last = NULL; + + assert(n > 0); + + level = items->level; + + while (n > 0) { + char *title; + int titlelen; + + /* + * Here we expect to be sitting on an item at the given + * level. So we start by constructing an outline entry for + * that item. + */ + assert(items->level == level); + + title = pdf_outline_convert(items->pdata->outline_title, &titlelen); + + totalcount++; + curr = new_object(parent->list); + if (!first) first = curr; + last = curr; + objtext(curr, "<<\n/Title "); + pdf_string_len(objtext, curr, title, titlelen); + sfree(title); + objtext(curr, "\n/Parent "); + objref(curr, parent); + objtext(curr, "\n/Dest ["); + objref(curr, (object *)items->pdata->first->page->spare); + objtext(curr, " /XYZ null null null]\n"); + if (prev) { + objtext(curr, "/Prev "); + objref(curr, prev); + objtext(curr, "\n"); + + objtext(prev, "/Next "); + objref(prev, curr); + objtext(prev, "\n>>\n"); + } + prev = curr; + + items++, n--; + for (itemp = items; itemp < items+n && itemp->level > level; + itemp++); + + if (itemp > items) { + char buf[80]; + int count = make_outline(curr, items, itemp - items, FALSE); + if (!open) + count = -count; + else + totalcount += count; + sprintf(buf, "/Count %d\n", count); + objtext(curr, buf); + } + + n -= itemp - items; + items = itemp; + } + objtext(prev, ">>\n"); + + assert(first && last); + objtext(parent, "/First "); + objref(parent, first); + objtext(parent, "\n/Last "); + objref(parent, last); + objtext(parent, "\n"); + + return totalcount; +} + +static int pdf_versionid(FILE *fp, word *words) +{ + int ret; + + ret = fprintf(fp, "%% "); + + for (; words; words = words->next) { + char *text; + int type; + + switch (words->type) { + case word_HyperLink: + case word_HyperEnd: + case word_UpperXref: + case word_LowerXref: + case word_XrefEnd: + case word_IndexRef: + continue; + } + + type = removeattr(words->type); + + switch (type) { + case word_Normal: + text = utoa_dup(words->text, CS_ASCII); + break; + case word_WhiteSpace: + text = dupstr(" "); + break; + case word_Quote: + text = dupstr("'"); + break; + } + + fputs(text, fp); + ret += strlen(text); + sfree(text); + } + + ret += fprintf(fp, "\n"); + + return ret; +} + +static void pdf_string_len(void (*add)(object *, char const *), + object *o, char const *str, int len) +{ + char const *p; + + add(o, "("); + for (p = str; len > 0; p++, len--) { + char c[10]; + if (*p < ' ' || *p > '~') { + sprintf(c, "\\%03o", 0xFF & (int)*p); + } else { + int n = 0; + if (*p == '\\' || *p == '(' || *p == ')') + c[n++] = '\\'; + c[n++] = *p; + c[n] = '\0'; + } + add(o, c); + } + add(o, ")"); +} + +static void pdf_string(void (*add)(object *, char const *), + object *o, char const *str) +{ + pdf_string_len(add, o, str, strlen(str)); +}