Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an SVG to a PDF using iText7

Tags:

java

svg

itext7

I need to add an SVG graphic into PDF file.

Is it that possible using iText7?

Using iText5:

BufferedReader in = new BufferedReader(new InputStreamReader(svgUrl.openStream()));
String xmlParser = XMLResourceDescriptor.getXMLParserClassName();

SVGDocument svgDoc = new SAXSVGDocumentFactory(xmlParser).createSVGDocument(null, in);
in.close();


// Try to read embedded height and width
float svgWidth = Float.parseFloat(svgDoc.getDocumentElement().getAttribute("width").replaceAll("[^0-9.,]",""));
float svgHeight = Float.parseFloat(svgDoc.getDocumentElement().getAttribute("height").replaceAll("[^0-9.,]",""));

PdfTemplate svgTempl = PdfTemplate.createTemplate(writer, svgWidth, svgHeight);
Graphics2D g2d = svgTempl.createGraphics(svgWidth,svgHeight);          

GraphicsNode chartGfx = (new GVTBuilder()).build(new BridgeContext(new UserAgentAdapter()), svgDoc);
chartGfx.paint(g2d);
g2d.dispose();

Image img = new ImgTemplate(svgTempl);

I found out that in the following page: PdfPTable and PdfTemplate

there is a way to create something similar as Template:

PdfFormXObject svgTempl = new PdfFormXObject(new Rectangle(svgWidth, svgHeight));

How can I create Graphics2D?

like image 472
Ap Tsi Avatar asked Apr 27 '18 09:04

Ap Tsi


1 Answers

Coincidentally, we're releasing our SVG implementation today. We don't support the full feature set just yet, we're still working on that in Q2 and beyond, but you can use it already. The artifact is on Maven. The repository is on Github. And the documentation is on our public wiki.

Code samples will be put on the web site, but it's a very simple API, similar to how pdfHtml works. There's an SvgConverter utility class that offers multiple ways to convert to PDF or PDF XObjects.

PdfDocument doc = new PdfDocument(
  new PdfWriter(pdfOutputStream, 
    new WriterProperties().setCompressionLevel(0)));
doc.addNewPage();
SvgConverter.drawOnDocument(svg, doc, 1);
doc.close();

Source: I'm an iText developer working on the SVG implementation

like image 54
Michaël Demey Avatar answered Oct 07 '22 02:10

Michaël Demey