如何使用 iText7 将 SVG 添加到 PDF

How to add an SVG to a PDF using iText7

我需要将 SVG 图形添加到 PDF 文件中。

是否可以使用 iText7?

使用 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);

我在以下页面中发现: PdfPTable and PdfTemplate

有一种方法可以创建类似于模板的内容:

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

如何创建 Graphics2D?

巧合的是,我们今天发布了 SVG 实现。我们目前还不支持完整的功能集,我们将在第二季度及以后继续努力,但您已经可以使用它了。神器在 Maven. The repository is on Github. And the documentation is on our public wiki.

代码示例将放在网站上,但非常简单API,类似于 pdfHtml 的工作方式。有一个 SvgConverter 实用程序 class 提供了多种转换为 PDF 或 PDF XObjects 的方法。

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

资料来源:我是一名致力于 SVG 实现的 iText 开发人员