Monday, November 02, 2009
PHP class adds SVG images to PDF files
I have modified the svg2pdf PHP class from Sylvain Briand at godisaduck.com for incorporating SVG graphics into a PDF document. The original class is an extension of the awesome FPDF class for creating PDF documents on the fly using PHP. Because FPDF does not support SVG graphics, there is a need for this extension. Briand's class works great, but did not meet all of my needs. My modification adds the following capabilities:
1. Write text on an SVG graphic
2. Transform scale support
3. Overflow hidden support (incomplete)
4. Place multiple SVG graphics on a single page
5. Produce a multi-page PDF document
Within the SVG standard, this would correspond to using a text element, as below:
<text x="210" y="15" font-family=”times” font-weight=”bold” font-style=”italic” font-size="10" fill="red">Hello World</text>
The PDF standard defines 3 standard fonts that all readers should support (Helvetica, Times, and Courier). You can use these fonts, with their bold and italic variants, without issue. The parent FPDF class supports external font definition files, so if you want to use any other font you must import it before calling ImageSVG() [not tested, see FPDF docs for more information on importing fonts].
There is no support for manipulating orientation, baseline alignment, directionality, etc.
TRANSFORM SCALE SUPPORT
Within the SVG standard, this would correspond to using a transform attribute as below:
The original class only supported applying styles with the g element. The modified class adds support for scale transformations.
Other transformations (rotate, skew, etc) are not supported.
OVERFLOW HIDDEN SUPPORT
It is possible, using the drawing tool that generates my SVG graphics, for graphical elements to extend beyond the borders of the image. Therefore, I needed a way to crop these elements down to the height and width defined for the image. Within the SVG standard, this would correspond to applying the overflow attribute of the svg element as below:
Sorry, but I was only able to implement cropping for path objects. Rendered objects (circles, rectangles, etc) may still extend beyond the borders defined for the image.
MULTIPLE IMAGES ON A PAGE AND MULTIPAGE PDF DOCUMENTS
It is now possible to call ImageSVG() multiple times for a single PDF document, and to add SVG graphics to multiple pages of a multi-page PDF file.
You can download the modified svg2pdf class here. I hope you find it helpful.