iText7 将 SVG 添加到 PdfDocument 中,并在 PDF 中正确对齐 SVG 图像



我可以使用以下代码在PDF中添加SVG图像,但是图像的对齐方式要折腾。我想将图像保存在有限的区域(假设始终为 300 x 300 尺寸)。如果图像较大,则应缩小/压缩并适合此大小。我们如何才能做到这一点。

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 cordinate 定位 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";

然后,您可以layout从 API 将其转换为 Image对象,而不是立即在页面上绘制 SVG 图像,您可以配置该对象:缩放以适应特定尺寸,设置固定位置(左下点)等:

Image image = SvgConverter.convertToImage(new FileInputStream(svgPath), doc);
image.setFixedPosition(100, 200);
image.scaleToFit(300, 300);

若要将所有内容绑定在一起,请创建高级Document对象并在此处添加图像。不要忘记关闭Document实例。您不再需要关闭原始PdfDocument

Document layoutDoc = new Document(doc);
layoutDoc.add(image);
layoutDoc.close();

最新更新