Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

java - How to add an SVG to a PDF using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...