如何使用iText7将SVG添加到PDF [英] How to add an SVG to a PDF using iText7

查看:818
本文介绍了如何使用iText7将SVG添加到PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to add an SVG graphic into PDF file.

使用iText7可以吗?

Is it that possible using 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和PdfTemplate

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

如何创建Graphics2D?

How can I create Graphics2D?

推荐答案

巧合的是,我们今天发布了SVG实现.我们目前尚不支持全部功能集,我们仍将在第二季度及以后进行开发,但是您已经可以使用它了.该工件在 Maven 上.该存储库位于 Github 上.该文档位于我们的公共Wiki .

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.

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

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();

来源:我是从事SVG实施的iText开发人员

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

这篇关于如何使用iText7将SVG添加到PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆