2012-11-03

How to Fit ViewBox to Area of Drawing on SVG

  1. Delete attribute(width and height), from root element (the tag name is svg) of SVG document. Then save it as tmp.svg. notice: This process is needed to calculate position and area size of drawing correctly.
  2. With inkscape command, get position (X and Y) and area size (W and H) of drawing from tmp.svg. To do this, execute command "inkscape -X tmp.svg", in the same way for Y, W and H. See "inkscape --help"
  3. Change viewBox attribute to "X Y W H". The root element has this attribute.
here is an example:
#!/bin/zsh

INKSCAPE=$(whence inkscape)
if [ -z "${INKSCAPE}" ]; then
  echo "Command inkscape not found." > /dev/stderr
  exit 1
fi
CSHARP=$(whence csharp)
if [ -z "${CSHARP}" ]; then
  echo "Command csharp not found." > /dev/stderr
  exit 1
fi

ID=
INPUT=
while [ -n "$1" ]; do
  case $1 in
    -I)
      ID="$2"
      shift
    ;;
    *)
      INPUT="$1"
    ;;
  esac
  shift
done

if [ -z "${INPUT}" ]; then
  echo "No input file." > /dev/stderr
  exit 1
fi
if [ ! -f "${INPUT}" ]; then
  echo "File '${INPUT}' is not found." > /dev/stderr
  exit 1
fi

OPTS=()
if [ -n "${ID}" ]; then
  OPTS=(${OPTS} -I ${ID})
fi

TMPFILE=$(tempfile).svg
cat <<EOT | ${CSHARP} -reference:System.Xml.Linq > ${TMPFILE}
using System;
using System.Xml.Linq;

var doc = XDocument.Load(@"${INPUT}");
var width = doc.Root.Attribute(XName.Get("width"));
if (width != null) width.Remove();
var height = doc.Root.Attribute(XName.Get("height"));
if (height != null) height.Remove();

doc.Save(Console.Out);
EOT

X=$(${INKSCAPE} ${OPTS} -X ${TMPFILE})
Y=$(${INKSCAPE} ${OPTS} -Y ${TMPFILE})
W=$(${INKSCAPE} ${OPTS} -W ${TMPFILE})
H=$(${INKSCAPE} ${OPTS} -H ${TMPFILE})

cat <<EOT | ${CSHARP} -reference:System.Xml.Linq
using System;
using System.Xml.Linq;

var doc = XDocument.Load(@"${TMPFILE}");
var viewBoxValue = @"${X} ${Y} ${W} ${H}";

var viewBox = doc.Root.Attribute(XName.Get("viewBox"));
if (viewBox == null) doc.Root.Add(new XAttribute(XName.Get("viewBox"), viewBoxValue));
if (viewBox != null) viewBox.SetValue(viewBoxValue);

doc.Save(Console.Out);
EOT

0 件のコメント:

コメントを投稿