Image iText7将SVG添加到PdfDocument中,并在PDF中正确对齐SVG图像
我可以使用下面的代码将SVG图像添加到PDF中,但是图像的对齐是一个难题。我想保持在一个有限的区域图像(让我们说,300 x 300大小始终)。如果图像较大,则应缩小/压缩并适合此大小。我们如何才能做到这一点Image iText7将SVG添加到PdfDocument中,并在PDF中正确对齐SVG图像,image,pdf,svg,pdf-generation,itext7,Image,Pdf,Svg,Pdf Generation,Itext7,我可以使用下面的代码将SVG图像添加到PDF中,但是图像的对齐是一个难题。我想保持在一个有限的区域图像(让我们说,300 x 300大小始终)。如果图像较大,则应缩小/压缩并适合此大小。我们如何才能做到这一点 PdfDocument doc = null; try { doc = new PdfDocument(new PdfWriter(new FileOutputStream(new File("D:\\test.pdf")), new WriterPrope
PdfDocument doc = null;
try {
doc = new PdfDocument(new PdfWriter(new FileOutputStream(new File("D:\\test.pdf")),
new WriterProperties().setCompressionLevel(0)));
doc.addNewPage();
URL svgUrl = null;
String svgPath = "...svgPathHere";
try {
svgUrl = new URL(svgPath);
} catch(MalformedURLException mue) {
System.out.println("Exception caught" + mue.getMessage() );
}
if (svgUrl == null){
try {
svgUrl = new File(svgPath).toURI().toURL();
} catch(Throwable th) {
System.out.println("Exception caught" + th.getMessage());
}
}
SvgConverter.drawOnDocument(svgUrl.openStream(), doc, 1, 100, 200); // 100 and 200 are x and y coordinate of the location to draw at
doc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
除了上述问题之外,SvgConverter的drawOnDocument()方法还为我们提供了通过x和y坐标定位svg的控制。有没有更好的方法来处理职位?(如左上角、右上角)在代码中,您正在处理相当低级的API。虽然您的任务非常简单,低级别的API在这里仍然足够,但使用高级别的布局API可以更快地实现目标 首先,您可以重用代码创建
PdfDocument
,并定义SVG图像的URL:
PdfDocument doc = new PdfDocument(new PdfWriter(new FileOutputStream(new File("D:\\test.pdf")),
new WriterProperties().setCompressionLevel(0)));
String svgPath = "...svgPathHere";
然后,不必立即在页面上绘制SVG图像,您可以将其从layout
API转换为image
对象,您可以对其进行配置:缩放以适应特定尺寸,设置固定位置(左底点)等等:
Image image = SvgConverter.convertToImage(new FileInputStream(svgPath), doc);
image.setFixedPosition(100, 200);
image.scaleToFit(300, 300);
要将所有内容联系在一起,请创建高级文档
对象并将图像添加到其中。不要忘记关闭文档
实例。您不再需要关闭原始的PDF文档
:
Document layoutDoc = new Document(doc);
layoutDoc.add(image);
layoutDoc.close();