index 2b3103f40a7e7ba52cfcc1101803bcb820c64417..a4eac8b67e1e39fad4b7d53a5f3f78b00851d964 100644 (file)
*
* Image printing and Ascii85 filter:
*
- * Copyright (C) 1995 Spencer Kimball and Peter Mattis
+ * Copyright (C) 2006 Johan Engelen
* Copyright (C) 1997-98 Peter Kirchgessner
+ * Copyright (C) 1995 Spencer Kimball and Peter Mattis
* George White <aa056@chebucto.ns.ca>
* Austin Donnelly <austin@gimp.org>
*
#include <libnr/n-art-bpath.h>
+#include <glib/gmem.h>
#include <gtk/gtkstock.h>
#include <gtk/gtkvbox.h>
#include <gtk/gtkframe.h>
#include "io/sys.h"
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_XFREE86_H
+#include <pango/pangoft2.h>
+#include <string>
+#include <iostream>
+#include <fstream>
+
+using namespace std;
+
namespace Inkscape {
namespace Extension {
namespace Internal {
_dpi(72),
_bitmap(false)
{
+ //map font types
+ _fontTypesMap["Type 1"] = FONT_TYPE1;
+ _fontTypesMap["TrueType"] = FONT_TRUETYPE;
+ //TODO: support other font types (cf. embed_font())
}
PrintPS::~PrintPS(void)
{
/* fixme: should really use pclose for popen'd streams */
if (_stream) fclose(_stream);
+ if(_begin_stream) fclose(_begin_stream);
+ if(_fonts) g_tree_destroy(_fonts);
/* restore default signal handling for SIGPIPE */
#if !defined(_WIN32) && !defined(__WIN32__)
#endif
unsigned int ret = FALSE;
+ gchar const *destination = mod->get_param_string("destination");
/* Create dialog */
GtkTooltips *tt = gtk_tooltips_new();
g_object_ref((GObject *) tt);
gtk_object_sink((GtkObject *) tt);
- GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
+ GtkWidget *dlg = gtk_dialog_new_with_buttons(
+ destination ? _("Print Configuration") : _("Print Destination"),
// SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
NULL,
(GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
- GTK_STOCK_PRINT,
+ destination ? GTK_STOCK_GO_FORWARD : GTK_STOCK_PRINT,
GTK_RESPONSE_OK,
NULL);
GtkWidget *l = gtk_label_new(_("Resolution:"));
gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
- /* Print destination frame */
- f = gtk_frame_new(_("Print destination"));
- gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
- vb = gtk_vbox_new(FALSE, 4);
- gtk_container_add(GTK_CONTAINER(f), vb);
- gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
-
- l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
- "leave empty to use the system default printer.\n"
- "Use '> filename' to print to file.\n"
+ GtkWidget *e = NULL;
+ /* if the destination isn't already set, we must prompt for it */
+ if (!destination) {
+ /* Print destination frame */
+ f = gtk_frame_new(_("Print destination"));
+ gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
+ vb = gtk_vbox_new(FALSE, 4);
+ gtk_container_add(GTK_CONTAINER(f), vb);
+ gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
+
+ l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
+ "leave empty to use the system default printer.\n"
+ "Use '> filename' to print to file.\n"
"Use '| prog arg...' to pipe to a program."));
- gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
+ gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
- GtkWidget *e = gtk_entry_new();
- if (1) {
- gchar const *val = mod->get_param_string("destination");
- gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
- ? val
+ e = gtk_entry_new();
+ gtk_entry_set_text(GTK_ENTRY(e), ( destination != NULL
+ ? destination
: "" ));
- }
- gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
+ gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
- // pressing enter in the destination field is the same as clicking Print:
- gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
+ // pressing enter in the destination field is the same as clicking Print:
+ gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
+ }
gtk_widget_show_all(vbox);
_bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
_dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
- /* Arrgh, have to do something */
- fn = gtk_entry_get_text(GTK_ENTRY(e));
- /* skip leading whitespace, bug #1068483 */
- while (fn && *fn==' ') { fn++; }
- /* g_print("Printing to %s\n", fn); */
+ /* if the destination was prompted for, record the new value */
+ if (e) {
+ /* Arrgh, have to do something */
+ fn = gtk_entry_get_text(GTK_ENTRY(e));
+ /* skip leading whitespace, bug #1068483 */
+ while (fn && *fn==' ') { fn++; }
+ /* g_print("Printing to %s\n", fn); */
+
+ mod->set_param_string("destination", (gchar *)fn);
+ }
mod->set_param_bool("bitmap", _bitmap);
mod->set_param_string("resolution", (gchar *)sstr);
- mod->set_param_string("destination", (gchar *)fn);
ret = TRUE;
}
{
gboolean epsexport = false;
+
_latin1_encoded_fonts.clear();
_newlatin1font_proc_defined = false;
FILE *osf = NULL;
FILE *osp = NULL;
+ FILE *osf_tmp = NULL;
gsize bytesRead = 0;
gsize bytesWritten = 0;
GError *error = NULL;
+ //check whether fonts have to be embedded in the (EPS only) output
+ bool font_embedded = mod->fontEmbedded();
gchar const *utf8_fn = mod->get_param_string("destination");
gchar *local_fn = g_filename_from_utf8( utf8_fn,
-1, &bytesRead, &bytesWritten, &error);
fn, strerror(errno));
return 0;
}
- _stream = osp;
+ _stream = _begin_stream = osp;
} else if (*fn == '>') {
fn += 1;
epsexport = g_str_has_suffix(fn,".eps");
fn, strerror(errno));
return 0;
}
- _stream = osf;
+ _begin_stream = osf;
+ /* if font embedding is requested for EPS export...
+ * TODO:could be extended to PS export if texttopath=FALSE possible
+ */
+ if(font_embedded && epsexport)
+ {
+ /**
+ * Create temporary file where to print the main "script" part of the EPS document.
+ * Use an extra stream (_begin_stream) to print the prolog and document setup sections.
+ * Thus, once all the (main) script part printed, all the fonts used are known and can be embedded
+ * just after the prolog section, in a Begin(End)Setup section (document setup),
+ * one Begin(End)Resource (DSC comment) section for each font embedded.
+ * Then, append the final script part from the temporary file (_stream in this case).
+ * Reference: Adobe Technical note 5001, "PostScript Document Struturing Conventions Specifications"
+ * page 19
+ */
+ osf_tmp = tmpfile();
+ if(!osf_tmp)
+ {
+ g_warning("Could not create a temporary file for font embedding. Font embedding canceled.");
+ mod->set_param_bool("fontEmbedded", false);
+ font_embedded = false;
+ _stream = osf;
+ } else _stream = osf_tmp;
+ } else _stream = osf;
} else {
/* put cwd stuff in here */
gchar *qn = ( *fn
return 0;
}
g_free(qn);
- _stream = osp;
+ _stream = _begin_stream = osp;
}
}
#endif
}
- int const res = fprintf(_stream, ( epsexport
+ int const res = fprintf(_begin_stream, ( epsexport
? "%%!PS-Adobe-3.0 EPSF-3.0\n"
: "%%!PS-Adobe-3.0\n" ));
/* flush this to test output stream as early as possible */
- if (fflush(_stream)) {
+ if (fflush(_begin_stream)) {
/*g_print("caught error in sp_module_print_plain_begin\n");*/
- if (ferror(_stream)) {
+ if (ferror(_begin_stream)) {
g_print("Error %d on output stream: %s\n", errno,
g_strerror(errno));
}
g_print("Printing failed\n");
/* fixme: should use pclose() for pipes */
- fclose(_stream);
- _stream = NULL;
+ fclose(_begin_stream);
+ _begin_stream = NULL;
fflush(stdout);
return 0;
}
+ //TODO: do this same test on _stream
// width and height in pt
_width = sp_document_width(doc) * PT_PER_PX;
<< d.x0 << " "
<< (_height - d.y0) << " "
<< d.x1 << "\n";
+ if (!epsexport) {
+ os << "%%DocumentMedia: plain "
+ << (int) ceil(_height) << " "
+ << (int) ceil(_width) << " "
+ << "0 () ()\n";
+ }
} else {
os << "%%Orientation: Portrait\n";
os << "%%BoundingBox: " << (int) d.x0 << " "
<< d.y0 << " "
<< d.x1 << " "
<< d.y1 << "\n";
+ if (!epsexport) {
+ os << "%%DocumentMedia: plain "
+ << (int) ceil(_width) << " "
+ << (int) ceil(_height) << " "
+ << "0 () ()\n";
+ }
}
os << "%%EndComments\n";
+ /* If font embedding requested, begin document setup section where to include font resources */
+ if(font_embedded) os << "%%BeginSetup\n";/* Resume it later with Begin(End)Resource sections for font embedding. So, for now, we are done with the prolog/setup part. */
+ gint ret = fprintf(_begin_stream, "%s", os.str().c_str());
+ if(ret < 0) return ret;
+
+ /* Main Script part (after document setup) begins */
+ /* Empty os from all previous printing */
+ std::string clrstr = "";
+ os.str(clrstr);
// This will become problematic if we print multi paged documents:
os << "%%Page: 1 1\n";
os << PT_PER_PX << " " << -PT_PER_PX << " scale\n";
// from now on we can output px, but they will be treated as pt
}
+
+ /* As a new PS document is created, _fontlist has to be reinitialized (unref fonts from possible former PS docs) */
+ _fonts = g_tree_new_full((GCompareDataFunc)strcmp, NULL, (GDestroyNotify)g_free, (GDestroyNotify)g_free);
}
+ os << "0 0 0 setrgbcolor\n"
+ << "[] 0 setdash\n"
+ << "1 setlinewidth\n"
+ << "0 setlinejoin\n"
+ << "0 setlinecap\n";
+
/* FIXME: This function is declared to return unsigned, whereas fprintf returns a signed int *
* that can be zero if the first fprintf failed (os is empty) or "negative" (i.e. very positive
* in unsigned int interpretation) if the first fprintf failed but this one succeeds, or
nr_arena_item_set_transform(mod->root, &affine);
- guchar *const px = nr_new(guchar, 4 * width * 64);
+ guchar *const px = g_new(guchar, 4 * width * 64);
for (int y = 0; y < height; y += 64) {
/* Set area of interest. */
bbox.x0, bbox.y0, bbox.x1, bbox.y1,
(guchar*)px, 4 * width, FALSE, FALSE);
memset(px, 0xff, 4 * width * 64);
- nr_arena_item_invoke_render(mod->root, &bbox, &pb, 0);
+ nr_arena_item_invoke_render(NULL, mod->root, &bbox, &pb, 0);
/* Blitter goes here */
NRMatrix imgt;
imgt.c[0] = (bbox.x1 - bbox.x0) / dots_per_pt;
print_image(_stream, px, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0, 4 * width, &imgt);
}
- nr_free(px);
+ g_free(px);
}
- int const res = fprintf(_stream, "showpage\n");
+ fprintf(_stream, "showpage\n");
+ int const res = fprintf(_stream, "%%%%EOF\n");
/* Flush stream to be sure. */
(void) fflush(_stream);
+ char c;
+ /* If font embedding... */
+ if(mod->get_param_bool("fontEmbedded"))
+ {
+ /* Close the document setup section that had been started (because all the needed resources are supposed to be included now) */
+ /*res = */fprintf(_begin_stream, "%s", "%%EndSetup\n");
+ /* If font embedding requested, the following PS script part was printed to a different file from the prolog/setup, so script part (current _stream) needs to be copied to prolog/setup file to get the complete (E)PS document */
+ if(fseek(_stream, 0, SEEK_SET) == 0)
+ {
+ while((c = fgetc(_stream))!=EOF) fputc(c, _begin_stream);
+ }
+ fclose(_stream);
+ _stream = _begin_stream;
+ }
+
/* fixme: should really use pclose for popen'd streams */
fclose(_stream);
- _stream = 0;
+ _stream = NULL;
+
_latin1_encoded_fonts.clear();
+ g_tree_destroy(_fonts);
+
return res;
}
// invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
// we first check if all components of stroke_dash.dash are 0.
bool LineSolid = true;
- if (style->stroke_dasharray_set &&
- style->stroke_dash.n_dash &&
+ if (style->stroke_dash.n_dash &&
style->stroke_dash.dash )
{
int i = 0;
while (LineSolid && (i < style->stroke_dash.n_dash)) {
- i++;
if (style->stroke_dash.dash[i] > 0.00000001)
LineSolid = false;
+ i++;
}
if (!LineSolid) {
os << "[";
@@ -782,46 +884,9 @@ PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsi
if (_bitmap) return 0;
return print_image(_stream, px, w, h, rs, transform);
-#if 0
- fprintf(_stream, "gsave\n");
- fprintf(_stream, "/rowdata %d string def\n", 3 * w);
- fprintf(_stream, "[%g %g %g %g %g %g] concat\n",
- transform->c[0],
- transform->c[1],
- transform->c[2],
- transform->c[3],
- transform->c[4],
- transform->c[5]);
- fprintf(_stream, "%d %d 8 [%d 0 0 -%d 0 %d]\n", w, h, w, h, h);
- fprintf(_stream, "{currentfile rowdata readhexstring pop}\n");
- fprintf(_stream, "false 3 colorimage\n");
-
- for (unsigned int r = 0; r < h; r++) {
- guchar *s;
- unsigned int c0, c1, c;
- s = px + r * rs;
- for (c0 = 0; c0 < w; c0 += 24) {
- c1 = MIN(w, c0 + 24);
- for (c = c0; c < c1; c++) {
- static char const xtab[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
- fputc(xtab[s[0] >> 4], _stream);
- fputc(xtab[s[0] & 0xf], _stream);
- fputc(xtab[s[1] >> 4], _stream);
- fputc(xtab[s[1] & 0xf], _stream);
- fputc(xtab[s[2] >> 4], _stream);
- fputc(xtab[s[2] & 0xf], _stream);
- s += 4;
- }
- fputs("\n", _stream);
- }
- }
-
- fprintf(_stream, "grestore\n");
-
- return 0;
-#endif
}
+/* PSFontName is now useless (cf. text() method code) */
char const *
PrintPS::PSFontName(SPStyle const *style)
{
char const *n;
char name_buf[256];
+ // PS does not like spaces in fontnames, replace them with the usual dashes.
+
if (tf) {
tf->PSName(name_buf, sizeof(name_buf));
- n = name_buf;
+ n = g_strdelimit(name_buf, " ", '-');
tf->Unref();
} else {
// this system does not have this font, so just use the name from SVG in the hope that PS interpreter will make sense of it
(style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
n = g_strdup_printf("%s%s%s%s",
- g_strdelimit(style->text->font_family.value, " ", '-'),
+ g_strdelimit(style->text->font_family.value, " ", '-'),
(b || i || o) ? "-" : "",
(b) ? "Bold" : "",
(i) ? "Italic" : ((o) ? "Oblique" : "") );
return g_strdup(n);
}
+//LSB = Least Significant Byte
+//converts 4-byte array to "LSB first" to "LSB last"
+/**
+* (Used by PrintPS::embed_t1 (from libgnomeprint/gnome-font-face.c),
+* to get the length of data segment (bytes 3-6 in IBM PC (PostScript) font file format.
+* Reference: Adobe technical note 5040, "Supporting Downloadable PostScript
+* Language Fonts", page 9)
+*/
+
+#define INT32_LSB_2_5(q) ((q)[2] + ((q)[3] << 8) + ((q)[4] << 16) + ((q)[5] << 24))
+
+/**
+* \brief For "Type 1" font only, print font data in output stream, to embed font data in PS output.
+* \param os Stream of output.
+* \param font Font whose data to embed.
+* \return FALSE if font embedding canceled (due to error or not supported font type), TRUE otherwise
+* TODO: enable font embedding for True Type
+*/
+//adapted more/less from libgnomeprint/gnome_font_face_ps_embed_t1()
+bool
+PrintPS::embed_t1 (SVGOStringStream &os, font_instance* font)
+{
+ //check font type
+ FT_Face font_face = pango_ft2_font_get_face(font->pFont);
+ const FT_String* font_type = FT_Get_X11_Font_Format(font_face);
+ g_return_val_if_fail (_fontTypesMap[font_type] == FONT_TYPE1, false);
+ //get font filename, stream to font file and size
+ FT_Stream font_stream = font_face->stream;
+ const char* font_filename = (char*) font_stream->pathname.pointer;
+ unsigned long font_stream_size = font_stream->size;
+ //first detect if font file is in IBM PC format
+ /**
+ * if first byte is 0x80, font file is pfb, do the same as a pfb to pfa converter
+ * Reference: Adobe technical note 5040, "Supporting Downloadable PostScript
+ * Language Fonts", page 9
+ * else: include all the ASCII data in the font pfa file
+ **/
+ char* buf = new char[7];
+ unsigned char* buffer = new unsigned char[7];//for the 6 header bytes (data segment length is unknown at this point) and final '\0'
+ std::string ascii_data;//for data segment "type 1" in IBM PC Format
+ //read the 6 header bytes
+ //for debug: g_warning("Reading from font file %s...", font_filename);
+ font_stream->close(font_stream);
+ ifstream font_file (font_filename, ios::in|ios::binary);
+ if (!font_file.is_open()) {
+ g_warning ("file %s: line %d: Cannot open font file %s", __FILE__, __LINE__, font_filename);
+ return false;
+ }
+ font_file.read(buf, 6);
+ buffer = (unsigned char*) buf;
+
+ //If font file is pfb, do the same as pfb to pfa converter
+ //check byte 1
+ if (buffer[0] == 0x80) {
+ const char hextab[17] = "0123456789abcdef";
+ unsigned long offset = 0;
+
+ while (offset < font_stream_size) {
+ gint length, i;
+ if (buffer[0] != 0x80) {
+ g_warning ("file %s: line %d: Corrupt %s", __FILE__, __LINE__, font_filename);
+ //TODO: print some default font data anyway like libgnomeprint/gnome_font_face_ps_embed_empty
+ return false;
+ }
+ switch (buffer[1]) {
+ case 1:
+ //get data segment length from bytes 3-6
+ //(Note: byte 1 is first byte in comments to match Adobe technical note 5040, but index 0 in code)
+ length = INT32_LSB_2_5 (buffer);
+ offset += 6;
+ //resize the buffer to fit the data segment length
+ delete [] buf;
+ buf = new char[length + 1];
+ buffer = new unsigned char[length + 1];
+ //read and print all the data segment length
+ font_file.read(buf, length);
+ buffer = (unsigned char*) buf;
+ /**
+ * Assigning a part from the buffer of length "length" ensures
+ * that no incorrect extra character will be printed and make the PS output invalid
+ * That was the case with the code:
+ * os << buffer;
+ * (A substring method could have been used as well.)
+ */
+ ascii_data.assign(buf, 0, length);
+ os << ascii_data;
+ offset += length;
+ //read next 6 header bytes
+ font_file.read(buf, 6);
+ break;
+ case 2:
+ length = INT32_LSB_2_5 (buffer);
+ offset += 6;
+ //resize the buffer to fit the data segment length
+ delete [] buf;
+ buf = new char[length + 1];
+ buffer = new unsigned char[length + 1];
+ //read and print all the data segment length
+ font_file.read(buf, length);
+ buffer = (unsigned char*) buf;
+ for (i = 0; i < length; i++) {
+ os << hextab[buffer[i] >> 4];
+ os << hextab[buffer[i] & 15];
+ offset += 1;
+ if ((i & 31) == 31 || i == length - 1)
+ os << "\n";
+ }
+ //read next 6 header bytes
+ font_file.read(buf, 6);
+ break;
+ case 3:
+ /* Finished */
+ os << "\n";
+ offset = font_stream_size;
+ break;
+ default:
+ os << "%%%ERROR: Font file corrupted at byte " << offset << "\n";
+ //TODO: print some default font data anyway like libgnomeprint/gnome_font_face_ps_embed_empty
+ return false;
+ }
+ }
+ }
+ //else: font file is pfa, include all directly
+ else {
+ //font is not in IBM PC format, all the file content can be directly printed
+ //resize buffer
+ delete [] buf;
+ buf = new char[font_stream_size + 1];
+ delete [] buffer;
+ font_file.seekg (0, ios::beg);
+ font_file.read(buf, font_stream_size);
+ /**
+ * Assigning a part from the buffer of length "length" ensures
+ * that no incorrect extra character will be printed and make the PS output invalid
+ * That was the case with the code:
+ * os << buffer;
+ * (A substring method could have been used as well.)
+ */
+ ascii_data.assign(buf, 0, font_stream_size);
+ os << ascii_data;
+ }
+ font_file.close();
+ delete [] buf;
+ buf = NULL;
+ buffer = NULL;// Clear buffer to prevent using invalid memory reference.
+
+ char font_psname[256];
+ font->PSName(font_psname, sizeof(font_psname));
+ FT_Long font_num_glyphs = font_face->num_glyphs;
+ if (font_num_glyphs < 256) {
+ gint glyph;
+ /* 8-bit vector */
+ os << "(" << font_psname << ") cvn findfont dup length dict begin\n";
+ os << "{1 index /FID ne {def} {pop pop} ifelse} forall\n";
+ os << "/Encoding [\n";
+ for (glyph = 0; glyph < 256; glyph++) {
+ guint g;
+ gchar c[256];
+ FT_Error status;
+ g = (glyph < font_num_glyphs) ? glyph : 0;
+ status = FT_Get_Glyph_Name (font_face, g, c, 256);
+
+ if (status != FT_Err_Ok) {
+ g_warning ("file %s: line %d: Glyph %d has no name in %s", __FILE__, __LINE__, g, font_filename);
+ g_snprintf (c, 256, ".notdef");
+ }
+
+ os << "/" << c << ( ((glyph & 0xf) == 0xf)?"\n":" " );
+ }
+ os << "] def currentdict end\n";
+ //TODO: manage several font instances for same ps name like in libgnomeprint/gnome_print_ps2_set_font_real()
+ //gf_pso_sprintf (pso, "(%s) cvn exch definefont pop\n", pso->encodedname);
+ os << "(" << font_psname << ") cvn exch definefont pop\n";
+ } else {
+ gint nfonts, i, j;
+ /* 16-bit vector */
+ nfonts = (font_num_glyphs + 255) >> 8;
+
+ os << "32 dict begin\n";
+ /* Common entries */
+ os << "/FontType 0 def\n";
+ os << "/FontMatrix [1 0 0 1 0 0] def\n";
+ os << "/FontName (" << font_psname << "-Glyph-Composite) cvn def\n";
+ os << "/LanguageLevel 2 def\n";
+
+ /* Type 0 entries */
+ os << "/FMapType 2 def\n";
+
+ /* Bitch 'o' bitches */
+ os << "/FDepVector [\n";
+
+ for (i = 0; i < nfonts; i++) {
+ os << "(" << font_psname << ") cvn findfont dup length dict begin\n";
+ os << "{1 index /FID ne {def} {pop pop} ifelse} forall\n";
+ os << "/Encoding [\n";
+ for (j = 0; j < 256; j++) {
+ gint glyph;
+ gchar c[256];
+ FT_Error status;
+ glyph = 256 * i + j;
+ if (glyph >= font_num_glyphs)
+ glyph = 0;
+ status = FT_Get_Glyph_Name (font_face, glyph, c, 256);
+ if (status != FT_Err_Ok) {
+ g_warning ("file %s: line %d: Glyph %d has no name in %s", __FILE__, __LINE__, glyph, font_filename);
+ g_snprintf (c, 256, ".notdef");
+ }
+ os << "/" << c << ( ((j & 0xf) == 0xf)?"\n":" " );
+ }
+ os << "] def\n";
+ os << "currentdict end (" << font_psname << "-Glyph-Page-";
+ os << std::dec << i;
+ os << ") cvn exch definefont\n";
+ }
+ os << "] def\n";
+ os << "/Encoding [\n";
+ for (i = 0; i < 256; i++) {
+ gint fn;
+ fn = (i < nfonts) ? i : 0;
+ os << std::dec << fn;
+ os << ( ((i & 0xf) == 0xf) ? "\n" : " " );
+ }
+ os << "] def\n";
+ os << "currentdict end\n";
+ //TODO: manage several font instances for same ps name like in libgnomeprint/gnome_print_ps2_set_font_real()
+ //gf_pso_sprintf (pso, "(%s) cvn exch definefont pop\n", pso->encodedname);
+ os << "(" << font_psname << ") cvn exch definefont pop\n";
+ }
+ //font embedding completed
+ return true;
+}
+
+
+
+/**
+* \brief Print font data in output stream, to embed font data in PS output.
+* \param os Stream of output.
+* \param font Font whose data to embed.
+* \return FALSE if font embedding canceled (due to error or not supported font type), TRUE otherwise
+*/
+//adapted from libgnomeprint/gnome_font_face_ps_embed()
+bool PrintPS::embed_font(SVGOStringStream &os, font_instance* font)
+{
+ //Hinted at by a comment in libgnomeprint/fcpattern_to_gp_font_entry()
+ //Determining the font type in the "Pango way"
+ FT_Face font_face = pango_ft2_font_get_face(font->pFont);
+ const FT_String* font_type = FT_Get_X11_Font_Format(font_face);
+
+ /**
+ * Possible values of "font_type": Type 1, TrueType, etc.
+ * Embedding available only for Type 1 fonts so far.
+ */
+ //TODO: provide support for other font types (TrueType is a priority)
+ switch(_fontTypesMap[font_type])
+ {
+ case FONT_TYPE1:
+ return embed_t1 (os, font);
+ //TODO: implement TT font embedding
+ /*case FONT_TRUETYPE:
+ embed_tt (os, font);
+ break;*/
+ default:
+ g_warning("Unknown (not supported) font type for embedding: %s", font_type);
+ //TODO: embed something like in libgnomeprint/gnome_font_face_ps_embed_empty();
+ return false;
+ }
+}
+
+
+/**
+* \brief Converts UTF-8 string to sequence of glyph numbers for PostScript string (cf. "show" commands.).
+* \param os Stream of output.
+* \param font Font used for unicode->glyph mapping.
+* \param unistring UTF-8 encoded string to convert.
+*/
+void PrintPS::print_glyphlist(SVGOStringStream &os, font_instance* font, Glib::ustring unistring)
+{
+ //iterate through unicode chars in unistring
+ Glib::ustring::iterator unistring_iter;
+ gunichar unichar;
+ gint glyph_index, glyph_page;
+
+ FT_Face font_face = pango_ft2_font_get_face(font->pFont);
+ FT_Long font_num_glyphs = font_face->num_glyphs;
+ //whether font has more than one glyph pages (16-bit encoding)
+ bool two_bytes_encoded = (font_num_glyphs > 255);
+
+ for (unistring_iter = unistring.begin(); unistring_iter!=unistring.end(); unistring_iter++)
+ {
+ //get unicode char
+ unichar = *unistring_iter;
+ //get matching glyph index in current font for unicode char
+ //default glyph index is 0 for undefined font character (glyph unavailable)
+ //TODO: if glyph unavailable for current font, use a default font among the most Unicode-compliant - e.g. Bitstream Cyberbit - I guess
+ glyph_index = font->MapUnicodeChar(unichar);
+ //if more than one glyph pages for current font (16-bit encoding),
+ if(two_bytes_encoded)
+ {
+ //add glyph page before glyph index.
+ glyph_page = (glyph_index >> 8) & 0xff;
+ os << "\\";
+ //convert in octal code before printing
+ os << std::oct << glyph_page;
+ }
+ //(If one page - 8-bit encoding -, nothing to add.)
+ //TODO: explain the following line inspired from libgnomeprint/gnome_print_ps2_glyphlist()
+ glyph_index = glyph_index & 0xff;
+ //TODO: mark glyph as used for current font, if Inkscape has to embed minimal font data in PS
+ os << "\\";
+ //convert in octal code before printing
+ os << std::oct << glyph_index;
+ }
+}
unsigned int
PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
@@ -859,42 +1239,129 @@ PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
if (_bitmap) return 0;
+ //check whether fonts have to be embedded in the PS output
+ //if not, use the former way of Inkscape to print text
+ gboolean font_embedded = mod->fontEmbedded();
+
Inkscape::SVGOStringStream os;
+ //find font
+ /**
+ * A font_instance object is necessary for the next steps,
+ * that's why using PSFontName() method just to get the PS fontname
+ * is not enough and not appropriate
+ */
+ font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
+ const gchar *fn = NULL;
+ char name_buf[256];
+ //check whether font was found
+ /**
+ * This check is not strictly reliable
+ * since Inkscape returns a default font if font not found.
+ * This is just to be consistent with the method PSFontName().
+ */
+ if (tf) {
+ //get font PS name
+ tf->PSName(name_buf, sizeof(name_buf));
+ fn = name_buf;
+ } else {
+ // this system does not have this font, so cancel font embedding...
+ font_embedded = FALSE;
+ //this case seems to never happen since Inkscape uses a default font instead (like BitstreamVeraSans on Windows)
+ g_warning("Font %s not found.", fn);
+ //...and just use the name from SVG in the hope that PS interpreter will make sense of it
+ bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
+ bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
+ bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
+ (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
+
+ fn = g_strdup_printf("%s%s%s%s",
+ g_strdelimit(style->text->font_family.value, " ", '-'),
+ (b || i || o) ? "-" : "",
+ (b) ? "Bold" : "",
+ (i) ? "Italic" : ((o) ? "Oblique" : "") );
+ }
+
+ /**
+ * If font embedding is requested, tempt to embed the font the first time it is used, once and for all.
+ * There is no selection of the glyph descriptions to embed, based on the characters used effectively in the document.
+ * (TODO?)
+ * Else, back to the former way of printing.
+ */
+ gpointer is_embedded;
+ //if not first time the font is used and if font embedding requested, check whether the font has been embedded (successfully the first time).
+ if(g_tree_lookup_extended(_fonts, fn, NULL, &is_embedded)) font_embedded = font_embedded && (strcmp((char *)is_embedded, "TRUE") == 0);
+ else
+ {
+ //first time the font is used
+ if(font_embedded)
+ {
+ //embed font in PS output
+ //adapted from libgnomeprint/gnome_print_ps2_close()
+ os << "%%BeginResource: font " << fn << "\n";
+ font_embedded = embed_font(os, tf);
+ os << "%%EndResource: font " << fn << "\n";
+ if(!font_embedded) g_warning("Font embedding canceled for font: %s", fn);
+ else fprintf(_begin_stream, "%s", os.str().c_str());
+ //empty os before resume printing to the script stream
+ std::string clrstr = "";
+ os.str(clrstr);
+
+ }
+ //add to the list
+ g_tree_insert(_fonts, g_strdup(fn), g_strdup((font_embedded)?"TRUE":"FALSE"));
+ }
+
+ Glib::ustring s;
// Escape chars
Inkscape::SVGOStringStream escaped_text;
- escaped_text << std::oct;
- for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
- gunichar const c = g_utf8_get_char(p_text);
- if (c == '\\' || c == ')' || c == '(')
- escaped_text << '\\' << static_cast<char>(c);
- else if (c >= 0x80)
- escaped_text << '\\' << c;
- else
- escaped_text << static_cast<char>(c);
+ //if font embedding, all characters will be converted to glyph indices (cf. PrintPS::print_glyphlist()),
+ //so no need to escape characters
+ //else back to the old way, i.e. escape chars: '\',')','(' and UTF-8 ones
+ if(font_embedded) s = text;
+ else {
+ escaped_text << std::oct;
+ for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
+ gunichar const c = g_utf8_get_char(p_text);
+ if (c == '\\' || c == ')' || c == '(')
+ escaped_text << '\\' << static_cast<char>(c);
+ else if (c >= 0x80)
+ escaped_text << '\\' << c;
+ else
+ escaped_text << static_cast<char>(c);
+ }
}
os << "gsave\n";
// set font
- char const *fn = PSFontName(style);
- if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
- if (!_newlatin1font_proc_defined) {
- // input: newfontname, existingfontname
- // output: new font object, also defined to newfontname
- os << "/newlatin1font " // name of the proc
- "{findfont dup length dict copy " // load the font and create a copy of it
- "dup /Encoding ISOLatin1Encoding put " // change the encoding in the copy
- "definefont} def\n"; // create the new font and leave it on the stack, define the proc
- _newlatin1font_proc_defined = true;
- }
- os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
- _latin1_encoded_fonts.insert(fn);
- } else
- os << "/" << fn << "-ISOLatin1 findfont\n";
+ if(font_embedded) os << "/" << fn << " findfont\n";
+ else {
+ if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
+ if (!_newlatin1font_proc_defined) {
+ // input: newfontname, existingfontname
+ // output: new font object, also defined to newfontname
+ os << "/newlatin1font " // name of the proc
+ "{findfont dup length dict copy " // load the font and create a copy of it
+ "dup /Encoding ISOLatin1Encoding put " // change the encoding in the copy
+ "definefont} def\n"; // create the new font and leave it on the stack, define the proc
+ _newlatin1font_proc_defined = true;
+ }
+ if(strchr(fn, ' ') == NULL)
+ os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
+ else
+ os << "(/" << fn << "-ISOLatin1) (/" << fn << ") newlatin1font\n";
+ _latin1_encoded_fonts.insert(fn);
+ } else
+ if(strchr(fn, ' ') == NULL)
+ os << "/" << fn << "-ISOLatin1 findfont\n";
+ else
+ os << "(/" << fn << "-ISOLatin1) findfont\n";
+ }
os << style->font_size.computed << " scalefont\n";
os << "setfont\n";
- g_free((void *) fn);
+ //The commented line beneath causes Inkscape to crash under Linux but not under Windows
+ //g_free((void*) fn);
if ( style->fill.type == SP_PAINT_TYPE_COLOR
|| ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
os << "newpath\n";
os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
- os << "(" << escaped_text.str() << ") show\n";
+ os << "(";
+ if(font_embedded) print_glyphlist(os, tf, s);
+ else os << escaped_text.str();
+ os << ") show\n";
}
if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
// paint stroke
os << "newpath\n";
os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
- os << "(" << escaped_text.str() << ") false charpath stroke\n";
+ os << "(";
+ if(font_embedded) print_glyphlist(os, tf, s);
+ else os << escaped_text.str();
+ os << ") false charpath stroke\n";
}
+ if(tf) tf->Unref();
+
os << "grestore\n";
fprintf(_stream, "%s", os.str().c_str());
@@ -1140,85 +1615,87 @@ PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int hei
Inkscape::SVGOStringStream os;
os << "gsave\n";
+
os << "[" << transform->c[0] << " "
<< transform->c[1] << " "
<< transform->c[2] << " "
<< transform->c[3] << " "
<< transform->c[4] << " "
<< transform->c[5] << "] concat\n";
- os << width << " " << height << " 8 ["
- << width << " 0 0 -" << height << " 0 " << height << "]\n";
-
/* Write read image procedure */
- os << "% Strings to hold RGB-samples per scanline\n";
- os << "/rstr " << width << " string def\n";
- os << "/gstr " << width << " string def\n";
- os << "/bstr " << width << " string def\n";
- os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter rstr readstring pop}\n";
- os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter gstr readstring pop}\n";
- os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter bstr readstring pop}\n";
- os << "true 3\n";
+ os << "<<\n";
+ os << " /ImageType 3\n";
+ os << " /InterleaveType 1\n";
+
+ os << " /MaskDict\n";
+ os << " <<\n";
+ os << " /ImageType 1\n";
+ os << " /Width " << width << "\n";
+ os << " /Height " << height << "\n";
+ os << " /ImageMatrix "
+ << "[" << width << " "
+ << 0 << " "
+ << 0 << " "
+ << -((long) height) << " "
+ << 0 << " "
+ << height << "]\n";
+ os << " /BitsPerComponent 8\n";
+ os << " /Decode [1 0]\n";
+ os << " >>\n";
+
+ os << " /DataDict\n";
+ os << " <<\n";
+ os << " /ImageType 1\n";
+ os << " /Width " << width << "\n";
+ os << " /Height " << height << "\n";
+ os << " /ImageMatrix "
+ << "[" << width << " "
+ << 0 << " "
+ << 0 << " "
+ << -((long )height) << " "
+ << 0 << " "
+ << height << "]\n";
+ os << " /DataSource currentfile /ASCII85Decode filter\n";
+ os << " /BitsPerComponent 8\n";
+ os << " /Decode [0 1 0 1 0 1]\n";
+ os << " >>\n";
+
+ os << ">>\n";
/* Allocate buffer for packbits data. Worst case: Less than 1% increase */
- guchar *const packb = (guchar *)g_malloc((width * 105)/100+2);
- guchar *const plane = (guchar *)g_malloc(width);
-
- /* ps_begin_data(ofp); */
- os << "colorimage\n";
+ guchar *const packb = (guchar *)g_malloc((4*width * 105)/100+2);
+ guchar *const plane = (guchar *)g_malloc(4*width);
-/*#define GET_RGB_TILE(begin) \
- * {int scan_lines; \
- * scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
- * gimp_pixel_rgn_get_rect(&pixel_rgn, begin, 0, i, width, scan_lines); \
- * src = begin; }
- */
+ os << "image\n";
+ ascii85_init();
+
for (unsigned i = 0; i < height; i++) {
- /* if ((i % tile_height) == 0) GET_RGB_TILE(data); */ /* Get more data */
guchar const *const src = px + i * rs;
- /* Iterate over RGB */
- for (int rgb = 0; rgb < 3; rgb++) {
- guchar const *src_ptr = src + rgb;
- guchar *plane_ptr = plane;
- for (unsigned j = 0; j < width; j++) {
- *(plane_ptr++) = *src_ptr;
- src_ptr += 4;
- }
-
- int nout;
- compress_packbits(width, plane, &nout, packb);
-
- ascii85_init();
- ascii85_nout(nout, packb, os);
- ascii85_out(128, os); /* Write EOD of RunLengthDecode filter */
- ascii85_done(os);
+ guchar const *src_ptr = src;
+ guchar *plane_ptr = plane;
+ for (unsigned j = 0; j < width; j++) {
+ *(plane_ptr++) = *(src_ptr+3);
+ *(plane_ptr++) = *(src_ptr+0);
+ *(plane_ptr++) = *(src_ptr+1);
+ *(plane_ptr++) = *(src_ptr+2);
+ src_ptr += 4;
}
+
+ ascii85_nout(4*width, plane, os);
}
- /* ps_end_data(ofp); */
-
-#if 0
- fprintf(ofp, "showpage\n");
- g_free(data);
-#endif
+ ascii85_done(os);
g_free(packb);
g_free(plane);
-#if 0
- if (ferror(ofp)) {
- g_message(_("write error occurred"));
- return (FALSE);
- }
-#endif
-
os << "grestore\n";
fprintf(ofp, "%s", os.str().c_str());
return 0;
-//#undef GET_RGB_TILE
}
bool
return ext->get_param_bool("textToPath");
}
+/**
+* \brief Get "fontEmbedded" param
+* \retval TRUE Fonts have to be embedded in the output so that the user might not need to install fonts to have the interpreter read the document correctly
+* \retval FALSE No font embedding
+*
+* Only available for Adobe Type 1 fonts in EPS output till now
+*/
+bool
+PrintPS::fontEmbedded(Inkscape::Extension::Print * ext)
+{
+ return ext->get_param_bool("fontEmbedded");
+}
+
+#include "clear-n_.h"
+
void
PrintPS::init(void)
{
/* SVG in */
(void) Inkscape::Extension::build_from_mem(
"<inkscape-extension>\n"
- "<name>Postscript Print</name>\n"
+ "<name>" N_("Postscript Print") "</name>\n"
"<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
"<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
"<param name=\"resolution\" type=\"string\">72</param>\n"
- "<param name=\"destination\" type=\"string\"></param>\n"
+ "<param name=\"destination\" type=\"string\">| lp</param>\n"
"<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
"<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
+ "<param name=\"fontEmbedded\" type=\"boolean\">FALSE</param>\n"
"<print/>\n"
"</inkscape-extension>", new PrintPS());
}