Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / extension / internal / pdfinput / svg-builder.cpp
index 7ca8eb0fef5b6a466f270a4bf6d10cacd4e50295..8b414239a708d9c8e5a8a537491aeef07518801e 100644 (file)
@@ -3,6 +3,7 @@
  * 
  * Authors:
  *   miklos erdelyi
+ *   Jon A. Cruz <jon@joncruz.org>
  *
  * Copyright (C) 2007 Authors
  *
@@ -14,6 +15,8 @@
 # include <config.h>
 #endif
 
+#include <string> 
+
 #ifdef HAVE_POPPLER
 
 #include "svg-builder.h"
@@ -33,7 +36,7 @@
 #include "unit-constants.h"
 #include "io/stringstream.h"
 #include "io/base64stream.h"
-#include "libnr/nr-matrix-ops.h"
+#include "display/nr-filter-utils.h"
 #include "libnr/nr-macros.h"
 #include "libnrtype/font-instance.h"
 
@@ -55,39 +58,82 @@ namespace Internal {
 #define TRACE(_args) IFTRACE(g_print _args)
 
 
+/**
+ * \struct SvgTransparencyGroup
+ * \brief Holds information about a PDF transparency group
+ */
+struct SvgTransparencyGroup {
+    double bbox[6];
+    Inkscape::XML::Node *container;
+
+    bool isolated;
+    bool knockout;
+    bool for_softmask;
+
+    SvgTransparencyGroup *next;
+};
+
 /**
  * \class SvgBuilder
  * 
  */
 
-SvgBuilder::SvgBuilder() {
-    _in_text_object = false;
-    _need_font_update = true;
-    _invalidated_style = true;
-    _font_style = NULL;
-    _current_font = NULL;
-    _current_state = NULL;
-}
-
-SvgBuilder::SvgBuilder(SPDocument *document, XRef *xref) {
+SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref)
+{
+    _is_top_level = true;
     _doc = document;
+    _docname = docname;
     _xref = xref;
-    _xml_doc = sp_document_repr_doc(_doc);
+    _xml_doc = _doc->getReprDoc();
     _container = _root = _doc->rroot;
-    SvgBuilder();
+    _root->setAttribute("xml:space", "preserve");
+    _init();
+
+    // Set default preference settings
+    _preferences = _xml_doc->createElement("svgbuilder:prefs");
+    _preferences->setAttribute("embedImages", "1");
+    _preferences->setAttribute("localFonts", "1");
 }
 
 SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
+    _is_top_level = false;
     _doc = parent->_doc;
+    _docname = parent->_docname;
     _xref = parent->_xref;
     _xml_doc = parent->_xml_doc;
+    _preferences = parent->_preferences;
     _container = this->_root = root;
-    SvgBuilder();
+    _init();
 }
 
 SvgBuilder::~SvgBuilder() {
 }
 
+void SvgBuilder::_init() {
+    _in_text_object = false;
+    _need_font_update = true;
+    _invalidated_style = true;
+    _font_style = NULL;
+    _current_font = NULL;
+    _current_state = NULL;
+
+    // Fill _availableFontNames (Bug LP #179589) (code cfr. FontLister)
+    FamilyToStylesMap familyStyleMap;
+    font_factory::Default()->GetUIFamiliesAndStyles(&familyStyleMap);
+    for (FamilyToStylesMap::iterator iter = familyStyleMap.begin();
+         iter != familyStyleMap.end();
+         iter++) {
+        _availableFontNames.push_back(iter->first.c_str());
+    }
+
+    _transp_group_stack = NULL;
+    SvgGraphicsState initial_state;
+    initial_state.softmask = NULL;
+    initial_state.group_depth = 0;
+    _state_stack.push_back(initial_state);
+    _node_stack.push_back(_container);
+}
+
 void SvgBuilder::setDocumentSize(double width, double height) {
     sp_repr_set_svg_double(_root, "width", width);
     sp_repr_set_svg_double(_root, "height", height);
@@ -95,32 +141,83 @@ void SvgBuilder::setDocumentSize(double width, double height) {
     this->_height = height;
 }
 
+/**
+ * \brief Sets groupmode of the current container to 'layer' and sets its label if given
+ */
+void SvgBuilder::setAsLayer(char *layer_name) {
+    _container->setAttribute("inkscape:groupmode", "layer");
+    if (layer_name) {
+        _container->setAttribute("inkscape:label", layer_name);
+    }
+}
+
+/**
+ * \brief Sets the current container's opacity
+ */
+void SvgBuilder::setGroupOpacity(double opacity) {
+    sp_repr_set_svg_double(_container, "opacity", CLAMP(opacity, 0.0, 1.0));
+}
+
 void SvgBuilder::saveState() {
-    _group_depth.push_back(0);
+    SvgGraphicsState new_state;
+    new_state.group_depth = 0;
+    new_state.softmask = _state_stack.back().softmask;
+    _state_stack.push_back(new_state);
     pushGroup();
 }
 
 void SvgBuilder::restoreState() {
-    while (_group_depth.back() > 0) {
+    while( _state_stack.back().group_depth > 0 ) {
         popGroup();
     }
-    _group_depth.pop_back();
+    _state_stack.pop_back();
 }
 
-Inkscape::XML::Node *SvgBuilder::pushGroup() {
-    Inkscape::XML::Node *node = _xml_doc->createElement("svg:g");
-    _container->appendChild(node);
+Inkscape::XML::Node *SvgBuilder::pushNode(const char *name) {
+    Inkscape::XML::Node *node = _xml_doc->createElement(name);
+    _node_stack.push_back(node);
     _container = node;
+    return node;
+}
+
+Inkscape::XML::Node *SvgBuilder::popNode() {
+    Inkscape::XML::Node *node = NULL;
+    if ( _node_stack.size() > 1 ) {
+        node = _node_stack.back();
+        _node_stack.pop_back();
+        _container = _node_stack.back();    // Re-set container
+    } else {
+        TRACE(("popNode() called when stack is empty\n"));
+        node = _root;
+    }
+    return node;
+}
+
+Inkscape::XML::Node *SvgBuilder::pushGroup() {
+    Inkscape::XML::Node *saved_container = _container;
+    Inkscape::XML::Node *node = pushNode("svg:g");
+    saved_container->appendChild(node);
     Inkscape::GC::release(node);
-    _group_depth.back()++;
+    _state_stack.back().group_depth++;
+    // Set as a layer if this is a top-level group
+    if ( _container->parent() == _root && _is_top_level ) {
+        static int layer_count = 1;
+        if ( layer_count > 1 ) {
+            gchar *layer_name = g_strdup_printf("%s%d", _docname, layer_count);
+            setAsLayer(layer_name);
+            g_free(layer_name);
+        } else {
+            setAsLayer(_docname);
+        }
+    }
 
     return _container;
 }
 
 Inkscape::XML::Node *SvgBuilder::popGroup() {
     if (_container != _root) {  // Pop if the current container isn't root
-        _container = _container->parent();
-        _group_depth[_group_depth.size()-1] = --_group_depth.back();
+        popNode();
+        _state_stack.back().group_depth--;
     }
 
     return _container;
@@ -131,35 +228,31 @@ Inkscape::XML::Node *SvgBuilder::getContainer() {
 }
 
 static gchar *svgConvertRGBToText(double r, double g, double b) {
+    using Inkscape::Filters::clamp;
     static gchar tmp[1023] = {0};
     snprintf(tmp, 1023,
              "#%02x%02x%02x",
-             CLAMP(SP_COLOR_F_TO_U(r), 0, 255),
-             CLAMP(SP_COLOR_F_TO_U(g), 0, 255),
-             CLAMP(SP_COLOR_F_TO_U(b), 0, 255));
+             clamp(SP_COLOR_F_TO_U(r)),
+             clamp(SP_COLOR_F_TO_U(g)),
+             clamp(SP_COLOR_F_TO_U(b)));
     return (gchar *)&tmp;
 }
 
 static gchar *svgConvertGfxRGB(GfxRGB *color) {
-    double r = color->r / 65535.0;
-    double g = color->g / 65535.0;
-    double b = color->b / 65535.0;
+    double r = (double)color->r / 65535.0;
+    double g = (double)color->g / 65535.0;
+    double b = (double)color->b / 65535.0;
     return svgConvertRGBToText(r, g, b);
 }
 
 static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
-                              double c2, double c3, double c4, double c5) {
-    NR::Matrix matrix(c0, c1, c2, c3, c4, c5);
+                            double c2, double c3, double c4, double c5) {
+    Geom::Matrix matrix(c0, c1, c2, c3, c4, c5);
     gchar *transform_text = sp_svg_transform_write(matrix);
     node->setAttribute("transform", transform_text);
     g_free(transform_text);
 }
 
-static void svgSetTransform(Inkscape::XML::Node *node, double *transform) {
-    svgSetTransform(node, transform[0], transform[1], transform[2], transform[3],
-                    transform[4], transform[5]);
-}
-
 /**
  * \brief Generates a SVG path string from poppler's data structure
  */
@@ -356,6 +449,63 @@ void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd)
     Inkscape::GC::release(path);
 }
 
+/**
+ * \brief Emits the current path in poppler's GfxState data structure
+ * The path is set to be filled with the given shading.
+ */
+void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *path,
+                               bool even_odd) {
+
+    Inkscape::XML::Node *path_node = _xml_doc->createElement("svg:path");
+    gchar *pathtext = svgInterpretPath(path);
+    path_node->setAttribute("d", pathtext);
+    g_free(pathtext);
+
+    // Set style
+    SPCSSAttr *css = sp_repr_css_attr_new();
+    gchar *id = _createGradient(shading, matrix, true);
+    if (id) {
+        gchar *urltext = g_strdup_printf ("url(#%s)", id);
+        sp_repr_css_set_property(css, "fill", urltext);
+        g_free(urltext);
+        g_free(id);
+    } else {
+        sp_repr_css_attr_unref(css);
+        Inkscape::GC::release(path_node);
+        return;
+    }
+    if (even_odd) {
+        sp_repr_css_set_property(css, "fill-rule", "evenodd");
+    }
+    sp_repr_css_set_property(css, "stroke", "none");
+    sp_repr_css_change(path_node, css, "style");
+    sp_repr_css_attr_unref(css);
+
+    _container->appendChild(path_node);
+    Inkscape::GC::release(path_node);
+
+    // Remove the clipping path emitted before the 'sh' operator
+    int up_walk = 0;
+    Inkscape::XML::Node *node = _container->parent();
+    while( node && node->childCount() == 1 && up_walk < 3 ) {
+        gchar const *clip_path_url = node->attribute("clip-path");
+        if (clip_path_url) {
+            // Obtain clipping path's id from the URL
+            gchar clip_path_id[32];
+            strncpy(clip_path_id, clip_path_url + 5, strlen(clip_path_url) - 6);
+            SPObject *clip_obj = _doc->getObjectById(clip_path_id);
+            if (clip_obj) {
+                clip_obj->deleteObject();
+                node->setAttribute("clip-path", NULL);
+                TRACE(("removed clipping path: %s\n", clip_path_id));
+            }
+            break;
+        }
+        node = node->parent();
+        up_walk++;
+    }
+}
+
 /**
  * \brief Clips to the current path set in GfxState
  * \param state poppler's data structure
@@ -375,6 +525,9 @@ void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
     gchar *pathtext = svgInterpretPath(state->getPath());
     path->setAttribute("d", pathtext);
     g_free(pathtext);
+    if (even_odd) {
+        path->setAttribute("clip-rule", "evenodd");
+    }
     clip_path->appendChild(path);
     Inkscape::GC::release(path);
     // Append clipPath to defs and get id
@@ -391,7 +544,7 @@ void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
  * \return true on success; false on invalid transformation
  */
 bool SvgBuilder::getTransform(double *transform) {
-    NR::Matrix svd;
+    Geom::Matrix svd;
     gchar const *tr = _container->attribute("transform");
     bool valid = sp_svg_transform_read(tr, &svd);
     if (valid) {
@@ -410,11 +563,15 @@ bool SvgBuilder::getTransform(double *transform) {
 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
                               double c4, double c5) {
 
+    // Avoid transforming a group with an already set clip-path
+    if ( _container->attribute("clip-path") != NULL ) {
+        pushGroup();
+    }
     TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
     svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
 }
 
-void SvgBuilder::setTransform(double *transform) {
+void SvgBuilder::setTransform(double const *transform) {
     setTransform(transform[0], transform[1], transform[2], transform[3],
                  transform[4], transform[5]);
 }
@@ -451,7 +608,10 @@ gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_
     gchar *id = NULL;
     if ( pattern != NULL ) {
         if ( pattern->getType() == 2 ) {  // Shading pattern
-            id = _createGradient((GfxShadingPattern*)pattern);
+            GfxShadingPattern *shading_pattern = (GfxShadingPattern*)pattern;
+            id = _createGradient(shading_pattern->getShading(),
+                                 shading_pattern->getMatrix(),
+                                 !is_stroke);
         } else if ( pattern->getType() == 1 ) {   // Tiling pattern
             id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
         }
@@ -474,7 +634,7 @@ gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
     Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
     // Set pattern transform matrix
     double *p2u = tiling_pattern->getMatrix();
-    NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
+    Geom::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
     gchar *transform_text = sp_svg_transform_write(pat_matrix);
     pattern_node->setAttribute("patternTransform", transform_text);
     g_free(transform_text);
@@ -527,10 +687,12 @@ gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
 
 /**
  * \brief Creates a linear or radial gradient from poppler's data structure
+ * \param shading poppler's data structure for the shading
+ * \param matrix gradient transformation, can be null
+ * \param for_shading true if we're creating this for a shading operator; false otherwise
  * \return id of the created object
  */
-gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) {
-    GfxShading *shading = shading_pattern->getShading();
+gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) {
     Inkscape::XML::Node *gradient;
     Function *func;
     int num_funcs;
@@ -568,20 +730,24 @@ gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) {
         return NULL;
     }
     gradient->setAttribute("gradientUnits", "userSpaceOnUse");
-    // Flip the gradient transform around the y axis
-    double *p2u = shading_pattern->getMatrix();
-    NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
-    NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
-    pat_matrix *= flip;
-    gchar *transform_text = sp_svg_transform_write(pat_matrix);
-    gradient->setAttribute("gradientTransform", transform_text);
-    g_free(transform_text);
+    // If needed, flip the gradient transform around the y axis
+    if (matrix) {
+        Geom::Matrix pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
+                              matrix[4], matrix[5]);
+        if ( !for_shading && _is_top_level ) {
+            Geom::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
+            pat_matrix *= flip;
+        }
+        gchar *transform_text = sp_svg_transform_write(pat_matrix);
+        gradient->setAttribute("gradientTransform", transform_text);
+        g_free(transform_text);
+    }
 
     if ( extend0 && extend1 ) {
         gradient->setAttribute("spreadMethod", "pad");
     }
 
-    if ( num_funcs > 1 || !_addStopsToGradient(gradient, func, 1.0) ) {
+    if ( num_funcs > 1 || !_addGradientStops(gradient, shading, func) ) {
         Inkscape::GC::release(gradient);
         return NULL;
     }
@@ -595,86 +761,91 @@ gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) {
 }
 
 #define EPSILON 0.0001
-bool SvgBuilder::_addSamplesToGradient(Inkscape::XML::Node *gradient,
-                                       SampledFunction *func, double offset0,
-                                       double offset1, double opacity) {
-
-    // Check whether this sampled function can be converted to color stops
-    int sample_size = func->getSampleSize(0);
-    if ( sample_size != 2 )
-        return false;
-    int num_comps = func->getOutputSize();
-    if ( num_comps != 3 )
-        return false;
-
-    double *samples = func->getSamples();
-    unsigned stop_count = gradient->childCount();
-    bool is_continuation = false;
-    // Check if this sampled function is the continuation of the previous one
-    if ( stop_count > 0 ) {
-        // Get previous stop
-        Inkscape::XML::Node *prev_stop = gradient->nthChild(stop_count-1);
-        // Read its properties
-        double prev_offset;
-        sp_repr_get_double(prev_stop, "offset", &prev_offset);
-        SPCSSAttr *css = sp_repr_css_attr(prev_stop, "style");
-        guint32 prev_stop_color = sp_svg_read_color(sp_repr_css_property(css, "stop-color", NULL), 0);
-        sp_repr_css_attr_unref(css);
-        // Convert colors
-        double r = SP_RGBA32_R_F (prev_stop_color);
-        double g = SP_RGBA32_G_F (prev_stop_color);
-        double b = SP_RGBA32_B_F (prev_stop_color);
-        if ( fabs(prev_offset - offset0) < EPSILON &&
-             fabs(samples[0] - r) < EPSILON &&
-             fabs(samples[1] - g) < EPSILON &&
-             fabs(samples[2] - b) < EPSILON ) {
-
-            is_continuation = true;
-        }
+/**
+ * \brief Adds a stop with the given properties to the gradient's representation
+ */
+void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset,
+                                    GfxRGB *color, double opacity) {
+    Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
+    SPCSSAttr *css = sp_repr_css_attr_new();
+    Inkscape::CSSOStringStream os_opacity;
+    gchar *color_text = NULL;
+    if ( _transp_group_stack != NULL && _transp_group_stack->for_softmask ) {
+        double gray = (double)color->r / 65535.0;
+        gray = CLAMP(gray, 0.0, 1.0);
+        os_opacity << gray;
+        color_text = (char*) "#ffffff";
+    } else {
+        os_opacity << opacity;
+        color_text = svgConvertGfxRGB(color);
     }
+    sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
+    sp_repr_css_set_property(css, "stop-color", color_text);
 
-    int i = is_continuation ? num_comps : 0;
-    while (i < sample_size*num_comps) {
-        Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
-        SPCSSAttr *css = sp_repr_css_attr_new();
-        Inkscape::CSSOStringStream os_opacity;
-        os_opacity << opacity;
-        sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
-        gchar c[64];
-        sp_svg_write_color (c, 64, SP_RGBA32_F_COMPOSE (samples[i], samples[i+1], samples[i+2], 1.0));
-        sp_repr_css_set_property(css, "stop-color", c);
-        sp_repr_css_change(stop, css, "style");
-        sp_repr_css_attr_unref(css);
-        sp_repr_set_css_double(stop, "offset", ( i < num_comps ) ? offset0 : offset1);
+    sp_repr_css_change(stop, css, "style");
+    sp_repr_css_attr_unref(css);
+    sp_repr_set_css_double(stop, "offset", offset);
+
+    gradient->appendChild(stop);
+    Inkscape::GC::release(stop);
+}
 
-        gradient->appendChild(stop);
-        Inkscape::GC::release(stop);
-        i += num_comps;
+static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) {
+    GfxColorSpace *color_space = shading->getColorSpace();
+    GfxColor temp;
+    if ( shading->getType() == 2 ) {  // Axial shading
+        ((GfxAxialShading*)shading)->getColor(offset, &temp);
+    } else if ( shading->getType() == 3 ) { // Radial shading
+        ((GfxRadialShading*)shading)->getColor(offset, &temp);
+    } else {
+        return false;
     }
-  
+    // Convert it to RGB
+    color_space->getRGB(&temp, result);
+
     return true;
 }
 
-bool SvgBuilder::_addStopsToGradient(Inkscape::XML::Node *gradient, Function *func,
-                                     double opacity) {
-    
+#define INT_EPSILON 8
+bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading,
+                                   Function *func) {
     int type = func->getType();
-    if ( type == 0 ) {  // Sampled
-        SampledFunction *sampledFunc = (SampledFunction*)func;
-        _addSamplesToGradient(gradient, sampledFunc, 0.0, 1.0, opacity);
+    if ( type == 0 || type == 2 ) {  // Sampled or exponential function
+        GfxRGB stop1, stop2;
+        if ( !svgGetShadingColorRGB(shading, 0.0, &stop1) ||
+             !svgGetShadingColorRGB(shading, 1.0, &stop2) ) {
+            return false;
+        } else {
+            _addStopToGradient(gradient, 0.0, &stop1, 1.0);
+            _addStopToGradient(gradient, 1.0, &stop2, 1.0);
+        }
     } else if ( type == 3 ) { // Stitching
         StitchingFunction *stitchingFunc = (StitchingFunction*)func;
         double *bounds = stitchingFunc->getBounds();
         int num_funcs = stitchingFunc->getNumFuncs();
-        // Add samples from all the stitched functions
+        // Add stops from all the stitched functions
         for ( int i = 0 ; i < num_funcs ; i++ ) {
-            Function *func = stitchingFunc->getFunc(i);
-            if ( func->getType() != 0 ) // Only sampled functions are supported
-                continue;
-           
-            SampledFunction *sampledFunc = (SampledFunction*)func;
-            _addSamplesToGradient(gradient, sampledFunc, bounds[i],
-                                  bounds[i+1], opacity);
+            GfxRGB color;
+            svgGetShadingColorRGB(shading, bounds[i], &color);
+            bool is_continuation = false;
+            if ( i > 0 ) {  // Compare to previous stop
+                GfxRGB prev_color;
+                svgGetShadingColorRGB(shading, bounds[i-1], &prev_color);
+                if ( abs(color.r - prev_color.r) < INT_EPSILON &&
+                     abs(color.g - prev_color.g) < INT_EPSILON &&
+                     abs(color.b - prev_color.b) < INT_EPSILON ) {
+                    is_continuation = true;
+                }
+            }
+            // Add stops
+            if ( !is_continuation ) {
+                _addStopToGradient(gradient, bounds[i], &color, 1.0);
+            }
+            if ( is_continuation || ( i == num_funcs - 1 ) ) {
+                GfxRGB next_color;
+                svgGetShadingColorRGB(shading, bounds[i+1], &next_color);
+                _addStopToGradient(gradient, bounds[i+1], &next_color, 1.0);
+            }
         }
     } else { // Unsupported function type
         return false;
@@ -694,26 +865,87 @@ void SvgBuilder::updateStyle(GfxState *state) {
     }
 }
 
+/*
+    MatchingChars
+    Count for how many characters s1 matches sp taking into account 
+    that a space in sp may be removed or replaced by some other tokens
+    specified in the code. (Bug LP #179589)
+*/
+static int MatchingChars(std::string s1, std::string sp)
+{
+    unsigned int is = 0;
+    unsigned int ip = 0;
+
+    while(is < s1.length() && ip < sp.length()) {
+        if (s1[is] == sp[ip]) {
+            is++; ip++;
+        } else if (sp[ip] == ' ') {
+            ip++;
+            if (s1[is] == '_') { // Valid matches to spaces in sp.
+                is++;
+            }
+        } else {
+            break;
+        }
+    }
+    return(ip);
+}
+
+/*
+    SvgBuilder::_BestMatchingFont
+    Scan the available fonts to find the font name that best matches PDFname.
+    (Bug LP #179589)
+*/
+std::string SvgBuilder::_BestMatchingFont(std::string PDFname)
+{
+    double bestMatch = 0;
+    std::string bestFontname = "Arial";
+    
+    for (guint i = 0; i < _availableFontNames.size(); i++) {
+        std::string fontname = _availableFontNames[i];
+        
+        // At least the first word of the font name should match.
+        guint minMatch = fontname.find(" ");
+        if (minMatch == std::string::npos) {
+           minMatch = fontname.length();
+        }
+        
+        int Match = MatchingChars(PDFname, fontname);
+        if (Match >= minMatch) {
+            double relMatch = (float)Match / (fontname.length() + PDFname.length());
+            if (relMatch > bestMatch) {
+                bestMatch = relMatch;
+                bestFontname = fontname;
+            }
+        }
+    }
+
+    if (bestMatch == 0)
+        return PDFname;
+    else
+        return bestFontname;
+}
+
 /**
  * This array holds info about translating font weight names to more or less CSS equivalents
  */
 static char *font_weight_translator[][2] = {
-    {"bold", "bold"},
-    {"light", "300"},
-    {"black", "900"},
-    {"heavy", "900"},
-    {"ultrabold", "800"},
-    {"extrabold", "800"},
-    {"demibold", "600"},
-    {"semibold", "600"},
-    {"medium", "500"},
-    {"book", "normal"},
-    {"regular", "normal"},
-    {"roman", "normal"},
-    {"normal", "normal"},
-    {"ultralight", "200"},
-    {"extralight", "200"},
-    {"thin", "100"}
+    {(char*) "bold",        (char*) "bold"},
+    {(char*) "light",       (char*) "300"},
+    {(char*) "black",       (char*) "900"},
+    {(char*) "heavy",       (char*) "900"},
+    {(char*) "ultrabold",   (char*) "800"},
+    {(char*) "extrabold",   (char*) "800"},
+    {(char*) "demibold",    (char*) "600"},
+    {(char*) "semibold",    (char*) "600"},
+    {(char*) "medium",      (char*) "500"},
+    {(char*) "book",        (char*) "normal"},
+    {(char*) "regular",     (char*) "normal"},
+    {(char*) "roman",       (char*) "normal"},
+    {(char*) "normal",      (char*) "normal"},
+    {(char*) "ultralight",  (char*) "200"},
+    {(char*) "extralight",  (char*) "200"},
+    {(char*) "thin",        (char*) "100"}
 };
 
 /**
@@ -723,8 +955,7 @@ void SvgBuilder::updateFont(GfxState *state) {
 
     TRACE(("updateFont()\n"));
     _need_font_update = false;
-    // Flush buffered text before resetting matrices and font style
-    _flushText();
+    updateTextMatrix(state);    // Ensure that we have a text matrix built
 
     if (_font_style) {
         //sp_repr_css_attr_unref(_font_style);
@@ -734,8 +965,10 @@ void SvgBuilder::updateFont(GfxState *state) {
     // Store original name
     if (font->getOrigName()) {
         _font_specification = font->getOrigName()->getCString();
-    } else {
+    } else if (font->getName()) {
         _font_specification = font->getName()->getCString();
+    } else {
+        _font_specification = (char*) "Arial";
     }
 
     // Prune the font name to get the correct font family name
@@ -750,19 +983,26 @@ void SvgBuilder::updateFont(GfxState *state) {
     } else {
         font_family = g_strdup(_font_specification);
     }
-    char *minus_sign = g_strrstr(font_family, "-");
-    if (minus_sign) {
-        font_style = minus_sign + 1;
+    char *style_delim = NULL;
+    if ( ( style_delim = g_strrstr(font_family, "-") ) ||
+         ( style_delim = g_strrstr(font_family, ",") ) ) {
+        font_style = style_delim + 1;
         font_style_lowercase = g_ascii_strdown(font_style, -1);
-        minus_sign[0] = 0;
+        style_delim[0] = 0;
     }
 
     // Font family
-    if (font->getFamily()) {
-        const gchar *family = font->getFamily()->getCString();
+    if (font->getFamily()) { // if font family is explicitly given use it.
         sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
-    } else {
-        sp_repr_css_set_property(_font_style, "font-family", font_family);
+    } else { 
+        int attr_value = 1;
+        sp_repr_get_int(_preferences, "localFonts", &attr_value);
+        if (attr_value != 0) {
+            // Find the font that best matches the stripped down (orig)name (Bug LP #179589).
+            sp_repr_css_set_property(_font_style, "font-family", _BestMatchingFont(font_family).c_str());
+        } else {
+            sp_repr_css_set_property(_font_style, "font-family", font_family);
+        }
     }
 
     // Font style
@@ -782,11 +1022,12 @@ void SvgBuilder::updateFont(GfxState *state) {
 
     // Font weight
     GfxFont::Weight font_weight = font->getWeight();
+    char *css_font_weight = NULL;
     if ( font_weight != GfxFont::WeightNotDefined ) {
         if ( font_weight == GfxFont::W400 ) {
-            sp_repr_css_set_property(_font_style, "font-weight", "normal");
+            css_font_weight = (char*) "normal";
         } else if ( font_weight == GfxFont::W700 ) {
-            sp_repr_css_set_property(_font_style, "font-weight", "bold");
+            css_font_weight = (char*) "bold";
         } else {
             gchar weight_num[4] = "100";
             weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
@@ -797,10 +1038,14 @@ void SvgBuilder::updateFont(GfxState *state) {
         int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
         for ( int i = 0 ; i < num_translations ; i++ ) {
             if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
-                sp_repr_css_set_property(_font_style, "font-weight",
-                                         font_weight_translator[i][1]);
+                css_font_weight = font_weight_translator[i][1];
             }
         }
+    } else {
+        css_font_weight = (char*) "normal";
+    }
+    if (css_font_weight) {
+        sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
     }
     g_free(font_family);
     if (font_style_lowercase) {
@@ -812,31 +1057,31 @@ void SvgBuilder::updateFont(GfxState *state) {
     gchar *stretch_value = NULL;
     switch (font_stretch) {
         case GfxFont::UltraCondensed:
-            stretch_value = "ultra-condensed";
+            stretch_value = (char*) "ultra-condensed";
             break;
         case GfxFont::ExtraCondensed:
-            stretch_value = "extra-condensed";
+            stretch_value = (char*) "extra-condensed";
             break;
         case GfxFont::Condensed:
-            stretch_value = "condensed";
+            stretch_value = (char*) "condensed";
             break;
         case GfxFont::SemiCondensed:
-            stretch_value = "semi-condensed";
+            stretch_value = (char*) "semi-condensed";
             break;
         case GfxFont::Normal:
-            stretch_value = "normal";
+            stretch_value = (char*) "normal";
             break;
         case GfxFont::SemiExpanded:
-            stretch_value = "semi-expanded";
+            stretch_value = (char*) "semi-expanded";
             break;
         case GfxFont::Expanded:
-            stretch_value = "expanded";
+            stretch_value = (char*) "expanded";
             break;
         case GfxFont::ExtraExpanded:
-            stretch_value = "extra-expanded";
+            stretch_value = (char*) "extra-expanded";
             break;
         case GfxFont::UltraExpanded:
-            stretch_value = "ultra-expanded";
+            stretch_value = (char*) "ultra-expanded";
             break;
         default:
             break;
@@ -847,10 +1092,14 @@ void SvgBuilder::updateFont(GfxState *state) {
 
     // Font size
     Inkscape::CSSOStringStream os_font_size;
-    double *text_matrix = state->getTextMat();
-    double font_size = sqrt( text_matrix[0] * text_matrix[3] - text_matrix[1] * text_matrix[2] );
-    font_size *= state->getFontSize() * state->getHorizScaling();
-    os_font_size << font_size;
+    double css_font_size = _font_scaling * state->getFontSize();
+    if ( font->getType() == fontType3 ) {
+        double *font_matrix = font->getFontMatrix();
+        if ( font_matrix[0] != 0.0 ) {
+            css_font_size *= font_matrix[3] / font_matrix[0];
+        }
+    }
+    os_font_size << css_font_size;
     sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
 
     // Writing mode
@@ -860,17 +1109,59 @@ void SvgBuilder::updateFont(GfxState *state) {
         sp_repr_css_set_property(_font_style, "writing-mode", "tb");
     }
 
+    _current_font = font;
+    _invalidated_style = true;
+}
+
+/**
+ * \brief Shifts the current text position by the given amount (specified in text space)
+ */
+void SvgBuilder::updateTextShift(GfxState *state, double shift) {
+    double shift_value = -shift * 0.001 * fabs(state->getFontSize());
+    if (state->getFont()->getWMode()) {
+        _text_position[1] += shift_value;
+    } else {
+        _text_position[0] += shift_value;
+    }
+}
+
+/**
+ * \brief Updates current text position
+ */
+void SvgBuilder::updateTextPosition(double tx, double ty) {
+    Geom::Point new_position(tx, ty);
+    _text_position = new_position;
+}
+
+/**
+ * \brief Flushes the buffered characters
+ */
+void SvgBuilder::updateTextMatrix(GfxState *state) {
+    _flushText();
+    // Update text matrix
+    double *text_matrix = state->getTextMat();
+    double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] );
+    double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] );
+    double max_scale;
+    if ( w_scale > h_scale ) {
+        max_scale = w_scale;
+    } else {
+        max_scale = h_scale;
+    }
     // Calculate new text matrix
-    double *font_matrix = font->getFontMatrix();
-    NR::Matrix nr_font_matrix(font_matrix[0], font_matrix[1], font_matrix[2],
-                              font_matrix[3], font_matrix[4], font_matrix[5]);
-    NR::Matrix new_text_matrix(text_matrix[0], text_matrix[1],
+    Geom::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
+                               text_matrix[1] * state->getHorizScaling(),
                                -text_matrix[2], -text_matrix[3],
                                0.0, 0.0);
-    new_text_matrix *= NR::scale( 1.0 / font_size, 1.0 / font_size );
-    _text_matrix = nr_font_matrix * new_text_matrix;
 
-    _current_font = font;
+    if ( fabs( max_scale - 1.0 ) > EPSILON ) {
+        // Cancel out scaling by font size in text matrix
+        for ( int i = 0 ; i < 4 ; i++ ) {
+            new_text_matrix[i] /= max_scale;
+        }
+    }
+    _text_matrix = new_text_matrix;
+    _font_scaling = max_scale;
 }
 
 /**
@@ -882,7 +1173,8 @@ void SvgBuilder::_flushText() {
         _glyphs.clear();
         return;
     }
-    const SvgGlyph& first_glyph = _glyphs[0];
+    std::vector<SvgGlyph>::iterator i = _glyphs.begin();
+    const SvgGlyph& first_glyph = (*i);
     int render_mode = first_glyph.render_mode;
     // Ignore invisible characters
     if ( render_mode == 3 ) {
@@ -891,27 +1183,24 @@ void SvgBuilder::_flushText() {
     }
 
     Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
-    text_node->setAttribute("xml:space", "preserve");
-    // Set current text position
-    sp_repr_set_svg_double(text_node, "x", first_glyph.transformed_position[0]);
-    sp_repr_set_svg_double(text_node, "y", first_glyph.transformed_position[1]);
-    // Set style
-    sp_repr_css_change(text_node, first_glyph.style, "style");
-    text_node->setAttribute("inkscape:font-specification", _font_specification);
     // Set text matrix
-    gchar *transform = sp_svg_transform_write(_text_matrix);
+    Geom::Matrix text_transform(_text_matrix);
+    text_transform[4] = first_glyph.position[0];
+    text_transform[5] = first_glyph.position[1];
+    gchar *transform = sp_svg_transform_write(text_transform);
     text_node->setAttribute("transform", transform);
     g_free(transform);
 
     bool new_tspan = true;
+    bool same_coords[2] = {true, true};
+    Geom::Point last_delta_pos;
+    unsigned int glyphs_in_a_row = 0;
     Inkscape::XML::Node *tspan_node = NULL;
     Glib::ustring x_coords;
     Glib::ustring y_coords;
     Glib::ustring text_buffer;
-    bool is_vertical = !strcmp(sp_repr_css_property(_font_style, "writing-mode", "lr"), "tb");  // FIXME
 
     // Output all buffered glyphs
-    std::vector<SvgGlyph>::iterator i = _glyphs.begin();
     while (1) {
         const SvgGlyph& glyph = (*i);
         std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
@@ -920,18 +1209,32 @@ void SvgBuilder::_flushText() {
             new_tspan = true;
         } else if ( i != _glyphs.begin() ) {
             const SvgGlyph& prev_glyph = (*prev_iterator);
-            if ( ( is_vertical && prev_glyph.transformed_position[0] != glyph.transformed_position[0] ) ||
-                 ( !is_vertical && prev_glyph.transformed_position[1] != glyph.transformed_position[1] ) ) {
+            if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 &&
+                     glyph.text_position[1] == prev_glyph.text_position[1] ) ||
+                    ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 &&
+                     glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) {
                 new_tspan = true;
             }
         }
+
         // Create tspan node if needed
         if ( new_tspan || i == _glyphs.end() ) {
             if (tspan_node) {
                 // Set the x and y coordinate arrays
-                tspan_node->setAttribute("x", x_coords.c_str());
-                tspan_node->setAttribute("y", y_coords.c_str());
+                if ( same_coords[0] ) {
+                    sp_repr_set_svg_double(tspan_node, "x", last_delta_pos[0]);
+                } else {
+                    tspan_node->setAttribute("x", x_coords.c_str());
+                }
+                if ( same_coords[1] ) {
+                    sp_repr_set_svg_double(tspan_node, "y", last_delta_pos[1]);
+                } else {
+                    tspan_node->setAttribute("y", y_coords.c_str());
+                }
                 TRACE(("tspan content: %s\n", text_buffer.c_str()));
+                if ( glyphs_in_a_row > 1 ) {
+                    tspan_node->setAttribute("sodipodi:role", "line");
+                }
                 // Add text content node to tspan
                 Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
                 tspan_node->appendChild(text_content);
@@ -942,38 +1245,59 @@ void SvgBuilder::_flushText() {
                 y_coords.clear();
                 text_buffer.clear();
                 Inkscape::GC::release(tspan_node);
+                glyphs_in_a_row = 0;
             }
             if ( i == _glyphs.end() ) {
                 sp_repr_css_attr_unref((*prev_iterator).style);
                 break;
             } else {
                 tspan_node = _xml_doc->createElement("svg:tspan");
-                tspan_node->setAttribute("sodipodi:role", "line");
+                
+                ///////
+                // Create a font specification string and save the attribute in the style
+                PangoFontDescription *descr = pango_font_description_from_string(glyph.font_specification);
+                Glib::ustring properFontSpec = font_factory::Default()->ConstructFontSpecification(descr);
+                pango_font_description_free(descr);
+                sp_repr_css_set_property(glyph.style, "-inkscape-font-specification", properFontSpec.c_str());
+
                 // Set style and unref SPCSSAttr if it won't be needed anymore
-                if ( i != _glyphs.begin() ) {
-                    sp_repr_css_change(tspan_node, glyph.style, "style");
-                    if (glyph.style_changed) {  // Free previous style
-                        sp_repr_css_attr_unref((*prev_iterator).style);
-                    }
+                sp_repr_css_change(tspan_node, glyph.style, "style");
+                if ( glyph.style_changed && i != _glyphs.begin() ) {    // Free previous style
+                    sp_repr_css_attr_unref((*prev_iterator).style);
                 }
             }
             new_tspan = false;
         }
-        if ( x_coords.length() > 0 ) {
+        if ( glyphs_in_a_row > 0 ) {
             x_coords.append(" ");
             y_coords.append(" ");
+            // Check if we have the same coordinates
+            const SvgGlyph& prev_glyph = (*prev_iterator);
+            for ( int p = 0 ; p < 2 ; p++ ) {
+                if ( glyph.text_position[p] != prev_glyph.text_position[p] ) {
+                    same_coords[p] = false;
+                }
+            }
         }
         // Append the coordinates to their respective strings
+        Geom::Point delta_pos( glyph.text_position - first_glyph.text_position );
+        delta_pos[1] += glyph.rise;
+        delta_pos[1] *= -1.0;   // flip it
+        delta_pos *= _font_scaling;
         Inkscape::CSSOStringStream os_x;
-        os_x << glyph.transformed_position[0];
+        os_x << delta_pos[0];
         x_coords.append(os_x.str());
         Inkscape::CSSOStringStream os_y;
-        os_y << glyph.transformed_position[1];
+        os_y << delta_pos[1];
         y_coords.append(os_y.str());
+        last_delta_pos = delta_pos;
 
         // Append the character to the text buffer
-        text_buffer.append((char *)&glyph.code, 1);
+       if ( !glyph.code.empty() ) {
+            text_buffer.append(1, glyph.code[0]);
+       }
 
+        glyphs_in_a_row++;
         i++;
     }
     _container->appendChild(text_node);
@@ -988,8 +1312,6 @@ void SvgBuilder::beginString(GfxState *state, GooString *s) {
     }
     IFTRACE(double *m = state->getTextMat());
     TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
-    IFTRACE(m = _current_font->getFontMatrix());
-    TRACE(("fm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
     IFTRACE(m = state->getCTM());
     TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
 }
@@ -1008,34 +1330,43 @@ void SvgBuilder::addChar(GfxState *state, double x, double y,
     bool is_space = ( uLen == 1 && u[0] == 32 );
     // Skip beginning space
     if ( is_space && _glyphs.size() < 1 ) {
+        Geom::Point delta(dx, dy);
+         _text_position += delta;
          return;
     }
     // Allow only one space in a row
-    if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
-         _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
+    if ( is_space && (_glyphs[_glyphs.size() - 1].code.size() == 1) &&
+         (_glyphs[_glyphs.size() - 1].code[0] == 32) ) {
+        Geom::Point delta(dx, dy);
+        _text_position += delta;
         return;
     }
 
     SvgGlyph new_glyph;
     new_glyph.is_space = is_space;
-    new_glyph.position = NR::Point( x - originX, y - originY );
-    new_glyph.transformed_position = new_glyph.position * _text_matrix;
+    new_glyph.position = Geom::Point( x - originX, y - originY );
+    new_glyph.text_position = _text_position;
     new_glyph.dx = dx;
     new_glyph.dy = dy;
+    Geom::Point delta(dx, dy);
+    _text_position += delta;
 
     // Convert the character to UTF-8 since that's our SVG document's encoding
-    static UnicodeMap *u_map = NULL;
-    if ( u_map == NULL ) {
-        GooString *enc = new GooString("UTF-8");
-        u_map = globalParams->getUnicodeMap(enc);
-        u_map->incRefCnt();
-        delete enc;
-    }
-    int code_size = 0;
-    for ( int i = 0 ; i < uLen ; i++ ) {
-        code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
+    {
+        gunichar2 uu[8] = {0};
+
+        for (int i = 0; i < uLen; i++) {
+            uu[i] = u[i];
+        }
+
+        gchar *tmp = g_utf16_to_utf8(uu, uLen, NULL, NULL, NULL);
+        if ( tmp && *tmp ) {
+            new_glyph.code = tmp;
+        } else {
+            new_glyph.code.clear();
+        }
+        g_free(tmp);
     }
-    new_glyph.code_size = code_size;
 
     // Copy current style if it has changed since the previous glyph
     if (_invalidated_style || _glyphs.size() == 0 ) {
@@ -1055,6 +1386,9 @@ void SvgBuilder::addChar(GfxState *state, double x, double y,
         new_glyph.style = prev_glyph.style;
         new_glyph.render_mode = prev_glyph.render_mode;
     }
+    new_glyph.font_specification = _font_specification;
+    new_glyph.rise = state->getRise();
+
     _glyphs.push_back(new_glyph);
 }
 
@@ -1115,19 +1449,21 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
         png_destroy_write_struct(&png_ptr, &info_ptr);
         return NULL;
     }
-
+    // Decide whether we should embed this image
+    int attr_value = 1;
+    sp_repr_get_int(_preferences, "embedImages", &attr_value);
+    bool embed_image = ( attr_value != 0 );
     // Set read/write functions
     Inkscape::IO::StringOutputStream base64_string;
     Inkscape::IO::Base64OutputStream base64_stream(base64_string);
-    FILE *fp;
-    gchar *file_name;
-    bool embed_image = true;
+    FILE *fp = NULL;
+    gchar *file_name = NULL;
     if (embed_image) {
         base64_stream.setColumnWidth(0);   // Disable line breaks
         png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
     } else {
         static int counter = 0;
-        file_name = g_strdup_printf("createImage%d.png", counter++);
+        file_name = g_strdup_printf("%s_img%d.png", _docname, counter++);
         fp = fopen(file_name, "wb");
         if ( fp == NULL ) {
             png_destroy_write_struct(&png_ptr, &info_ptr);
@@ -1138,7 +1474,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
     }
 
     // Set header data
-    if (!invert_alpha) {
+    if ( !invert_alpha && !alpha_only ) {
         png_set_invert_alpha(png_ptr);
     }
     png_color_8 sig_bit;
@@ -1187,20 +1523,25 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
         image_stream->reset();
 
         // Convert grayscale values
-        if (color_map) {
-            unsigned char *buffer = new unsigned char[width];
-            for ( int y = 0 ; y < height ; y++ ) {
-                unsigned char *row = image_stream->getLine();
+        unsigned char *buffer = new unsigned char[width];
+        int invert_bit = invert_alpha ? 1 : 0;
+        for ( int y = 0 ; y < height ; y++ ) {
+            unsigned char *row = image_stream->getLine();
+            if (color_map) {
                 color_map->getGrayLine(row, buffer, width);
-                png_write_row(png_ptr, (png_bytep)buffer);
-            }
-            delete buffer;
-        } else {
-            for ( int y = 0 ; y < height ; y++ ) {
-                unsigned char *row = image_stream->getLine();
-                png_write_row(png_ptr, (png_bytep)row);
+            } else {
+                unsigned char *buf_ptr = buffer;
+                for ( int x = 0 ; x < width ; x++ ) {
+                    if ( row[x] ^ invert_bit ) {
+                        *buf_ptr++ = 0;
+                    } else {
+                        *buf_ptr++ = 255;
+                    }
+                }
             }
+            png_write_row(png_ptr, (png_bytep)buffer);
         }
+        delete [] buffer;
     } else if (color_map) {
         image_stream = new ImageStream(str, width,
                                        color_map->getNumPixelComps(),
@@ -1239,7 +1580,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
                 png_write_row(png_ptr, (png_bytep)buffer);
             }
         }
-        delete buffer;
+        delete [] buffer;
 
     } else {    // A colormap must be provided, so quit
         png_destroy_write_struct(&png_ptr, &info_ptr);
@@ -1258,10 +1599,12 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
 
     // Create repr
     Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
-    sp_repr_set_svg_double(image_node, "width", width);
-    sp_repr_set_svg_double(image_node, "height", height);
+    sp_repr_set_svg_double(image_node, "width", 1);
+    sp_repr_set_svg_double(image_node, "height", 1);
     // Set transformation
-    svgSetTransform(image_node, 1.0/(double)width, 0.0, 0.0, -1.0/(double)height, 0.0, 1.0);
+    if (_is_top_level) {
+        svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
+    }
 
     // Create href
     if (embed_image) {
@@ -1278,6 +1621,42 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
     return image_node;
 }
 
+/**
+ * \brief Creates a <mask> with the specified width and height and adds to <defs>
+ *  If we're not the top-level SvgBuilder, creates a <defs> too and adds the mask to it.
+ * \return the created XML node
+ */
+Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
+    Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask");
+    mask_node->setAttribute("maskUnits", "userSpaceOnUse");
+    sp_repr_set_svg_double(mask_node, "x", 0.0);
+    sp_repr_set_svg_double(mask_node, "y", 0.0);
+    sp_repr_set_svg_double(mask_node, "width", width);
+    sp_repr_set_svg_double(mask_node, "height", height);
+    // Append mask to defs
+    if (_is_top_level) {
+        SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(mask_node);
+        Inkscape::GC::release(mask_node);
+        return SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->lastChild();
+    } else {    // Work around for renderer bug when mask isn't defined in pattern
+        static int mask_count = 0;
+        Inkscape::XML::Node *defs = _root->firstChild();
+        if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
+            // Create <defs> node
+            defs = _xml_doc->createElement("svg:defs");
+            _root->addChild(defs, NULL);
+            Inkscape::GC::release(defs);
+            defs = _root->firstChild();
+        }
+        gchar *mask_id = g_strdup_printf("_mask%d", mask_count++);
+        mask_node->setAttribute("id", mask_id);
+        g_free(mask_id);
+        defs->appendChild(mask_node);
+        Inkscape::GC::release(mask_node);
+        return defs->lastChild();
+    }
+}
+
 void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
                           GfxImageColorMap *color_map, int *mask_colors) {
 
@@ -1288,6 +1667,174 @@ void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
      }
 }
 
+void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height,
+                              bool invert) {
+
+    // Create a rectangle
+    Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect");
+    sp_repr_set_svg_double(rect, "x", 0.0);
+    sp_repr_set_svg_double(rect, "y", 0.0);
+    sp_repr_set_svg_double(rect, "width", 1.0);
+    sp_repr_set_svg_double(rect, "height", 1.0);
+    svgSetTransform(rect, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
+    // Get current fill style and set it on the rectangle
+    SPCSSAttr *css = sp_repr_css_attr_new();
+    _setFillStyle(css, state, false);
+    sp_repr_css_change(rect, css, "style");
+    sp_repr_css_attr_unref(css);
+
+    // Scaling 1x1 surfaces might not work so skip setting a mask with this size
+    if ( width > 1 || height > 1 ) {
+        Inkscape::XML::Node *mask_image_node = _createImage(str, width, height, NULL, NULL, true, invert);
+        if (mask_image_node) {
+            // Create the mask
+            Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+            // Remove unnecessary transformation from the mask image
+            mask_image_node->setAttribute("transform", NULL);
+            mask_node->appendChild(mask_image_node);
+            Inkscape::GC::release(mask_image_node);
+            gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+            rect->setAttribute("mask", mask_url);
+            g_free(mask_url);
+        }
+    }
+
+    // Add the rectangle to the container
+    _container->appendChild(rect);
+    Inkscape::GC::release(rect);
+}
+
+void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int height,
+                                GfxImageColorMap *color_map,
+                                Stream *mask_str, int mask_width, int mask_height,
+                                bool invert_mask) {
+
+    Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
+                                                        NULL, NULL, true, invert_mask);
+    Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
+    if ( mask_image_node && image_node ) {
+        // Create mask for the image
+        Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+        // Remove unnecessary transformation from the mask image
+        mask_image_node->setAttribute("transform", NULL);
+        mask_node->appendChild(mask_image_node);
+        // Scale the mask to the size of the image
+        Geom::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
+        gchar *transform_text = sp_svg_transform_write(mask_transform);
+        mask_node->setAttribute("maskTransform", transform_text);
+        g_free(transform_text);
+        // Set mask and add image
+        gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+        image_node->setAttribute("mask", mask_url);
+        g_free(mask_url);
+        _container->appendChild(image_node);
+    }
+    if (mask_image_node) {
+        Inkscape::GC::release(mask_image_node);
+    }
+    if (image_node) {
+        Inkscape::GC::release(image_node);
+    }
+}
+    
+void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int height,
+                                    GfxImageColorMap *color_map,
+                                    Stream *mask_str, int mask_width, int mask_height,
+                                    GfxImageColorMap *mask_color_map) {
+
+    Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
+                                                        mask_color_map, NULL, true);
+    Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
+    if ( mask_image_node && image_node ) {
+        // Create mask for the image
+        Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+        // Remove unnecessary transformation from the mask image
+        mask_image_node->setAttribute("transform", NULL);
+        mask_node->appendChild(mask_image_node);
+        // Set mask and add image
+        gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+        image_node->setAttribute("mask", mask_url);
+        g_free(mask_url);
+        _container->appendChild(image_node);
+    }
+    if (mask_image_node) {
+        Inkscape::GC::release(mask_image_node);
+    }
+    if (image_node) {
+        Inkscape::GC::release(image_node);
+    }
+}
+
+/**
+ * \brief Starts building a new transparency group
+ */
+void SvgBuilder::pushTransparencyGroup(GfxState *state, double *bbox,
+                                       GfxColorSpace *blending_color_space,
+                                       bool isolated, bool knockout,
+                                       bool for_softmask) {
+
+    // Push node stack
+    pushNode("svg:g");
+
+    // Setup new transparency group
+    SvgTransparencyGroup *transpGroup = new SvgTransparencyGroup;
+    memcpy(&transpGroup->bbox, bbox, sizeof(bbox));
+    transpGroup->isolated = isolated;
+    transpGroup->knockout = knockout;
+    transpGroup->for_softmask = for_softmask;
+    transpGroup->container = _container;
+
+    // Push onto the stack
+    transpGroup->next = _transp_group_stack;
+    _transp_group_stack = transpGroup;
+}
+
+void SvgBuilder::popTransparencyGroup(GfxState *state) {
+    // Restore node stack
+    popNode();
+}
+
+/**
+ * \brief Places the current transparency group into the current container
+ */
+void SvgBuilder::paintTransparencyGroup(GfxState *state, double *bbox) {
+    SvgTransparencyGroup *transpGroup = _transp_group_stack;
+    _container->appendChild(transpGroup->container);
+    Inkscape::GC::release(transpGroup->container);
+    // Pop the stack
+    _transp_group_stack = transpGroup->next;
+    delete transpGroup;
+}
+
+/**
+ * \brief Creates a mask using the current transparency group as its content
+ */
+void SvgBuilder::setSoftMask(GfxState *state, double *bbox, bool alpha,
+                             Function *transfer_func, GfxColor *backdrop_color) {
+
+    // Create mask
+    Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
+    // Add the softmask content to it
+    SvgTransparencyGroup *transpGroup = _transp_group_stack;
+    mask_node->appendChild(transpGroup->container);
+    Inkscape::GC::release(transpGroup->container);
+    // Apply the mask
+    _state_stack.back().softmask = mask_node;
+    pushGroup();
+    gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
+    _container->setAttribute("mask", mask_url);
+    g_free(mask_url);
+    // Pop the stack
+    _transp_group_stack = transpGroup->next;
+    delete transpGroup;
+}
+
+void SvgBuilder::clearSoftMask(GfxState *state) {
+    if (_state_stack.back().softmask) {
+        _state_stack.back().softmask = NULL;
+        popGroup();
+    }
+}
 
 } } } /* namespace Inkscape, Extension, Internal */