I'm working on adding SVG image to PDF pages.
Firstly, I tried SvgConverter.createPDF to check if iText works with SVG.
Some svgs are fine. Unfortunately, the following SVG (using percentage position) is not correctly displayed / positioned in PDF.
My Conversion code
String svgImage = resourceFile("svg/circle-sRGB-rgb.svg");
String destination = targetFile("svg-itext_SVG2PDF.pdf");
try(InputStream svgStream = new FileInputStream(new File(svgImage))) {
try(OutputStream pdfStream = new FileOutputStream(new File(destination))) {
SvgConverter.createPdf(svgStream, pdfStream);
}
}
SVG file
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 80 60">
<circle cx="50%" cy="50%" r="30" fill="rgb(10, 200, 200)"/>
</svg>
SVG Preview
Generated PDF Preview
If I change the position (cx, cy) in SVG to absolute values, output seems to be good.
I also tried converting the SVG to an xObject, but it also didn't help.
private void addSvgImageToPdfPage(PdfPage page, String svgContent, float x, float y, float w, float h) {
// convert svg to xObject
PdfFormXObject xObject = SvgConverter.convertToXObject(svgContent, page.getDocument());
// create page canvas
PdfCanvas pdfCanvas = new PdfCanvas(page);
// create AT
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.concatenate(AffineTransform.getScaleInstance(w / xObject.getWidth(), h / xObject.getHeight()));
float[] matrix = new float[6];
at.getMatrix(matrix);
// add svg xObject to canvas
pdfCanvas.addXObjectWithTransformationMatrix(xObject, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
pdfCanvas.release();
}

