【问题标题】:iText7 adding SVG into PdfDocument and aligning SVG image properly within the PDFiText7 将 SVG 添加到 PdfDocument 并在 PDF 中正确对齐 SVG 图像
【发布时间】:2019-06-13 02:44:15
【问题描述】:

我可以使用下面的代码在 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 坐标定位 svg 的控件。有没有更好的方法来处理定位? (如左上、右上)

【问题讨论】:

    标签: image pdf svg pdf-generation itext7


    【解决方案1】:

    在您的代码中,您处理的是相当低级的 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-08
      • 2019-03-09
      • 1970-01-01
      • 2018-10-08
      • 2021-04-09
      • 2015-04-14
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多