【问题标题】:Render viewBox As New SVGDocument Programmatically以编程方式将 viewBox 渲染为新的 SVGDocument
【发布时间】:2019-11-10 15:11:12
【问题描述】:

我有一个SVGDocument,我以编程方式从数据库连接中检索为byte[]<svg> 元素包含适当的 viewBox 属性,该属性涵盖了现有进程需要呈现为 PDF 的 SVGDocument 部分。

使用以下(简单)代码,我能够验证 viewBox 属性设置是否正确:

Element rootElement = svgDocument.getRootElement();
String viewBox = rootElement.getAttribute("viewBox");
log.debug("viewBox={}", viewBox);
// viewBox=-612 0 1224 792

我的目标是使用 Batik getEnclosureList() 方法检索 NodeList 并构建一个新的(裁剪的)SVGDocument,我可以将其发送到将呈现 PDF 的旧进程。

我尝试使用的代码如下:

SVGRect rectangle = svgDocument.getRootElement().createSVGRect();
rectangle.setX(minX);  // -612
rectangle.setY(minY); // 0
rectangle.setWidth(startingX); // 1224
rectangle.setHeight(startingY); // 792

NodeList croppedNodes = svgDocument.getRootElement().getEnclosureList(rectangle, null);

我的问题是,当我使用这种方法时,SVGSVGContext 为空。

我试图找到如何设置SVGSVGContext 没有成功,这就是为什么我决定在这里发布我的问题。

我不赞成将 Apache Batik 用于此解决方案,但似乎 getEnclosureList() 方法可能会返回我完成任务所需的内容。

【问题讨论】:

    标签: java svg batik


    【解决方案1】:

    通过挖掘大量源代码,我认为我已经找到了我需要做什么的答案,这在initSvgDom()方法中有详细说明:

    private void someMethod(SVGDocument svgDocument) {
       initSvgDom(svg);
    
       Element rootElement = svg.getRootElement();
    
       String viewBox = rootElement.getAttribute("viewBox");
       log.debug("viewBox={}", viewBox);
    
       String[] viewBoxArray = viewBox.split(" ");
    
       float minX = Float.valueOf(viewBoxArray[0]);
       float minY = Float.valueOf(viewBoxArray[1]);
       float startingX = Float.valueOf(viewBoxArray[2]);
       float startingY = Float.valueOf(viewBoxArray[3]);
    
       SVGRect rectangle = svgDocument.getRootElement().createSVGRect();
       rectangle.setX(minX);
       rectangle.setY(minY);
       rectangle.setWidth(startingX);
       rectangle.setHeight(startingY);
    
       NodeList nodes = svgDocument.getRootElement().getEnclosureList(rectangle, null);
    
       // nodes contains a list of elements within the specified rectangle, which matches the value of the viewBox within the svgDocument.
      ... do stuff with nodes
    }
    
    private void initSvgDom(Document document) {
       UserAgent userAgent = new UserAgentAdapter();
       DocumentLoader loader = new DocumentLoader(userAgent);
       BridgeContext bridgeContext = new BridgeContext(userAgent, loader);
       bridgeContext.setDynamicState(BridgeContext.DYNAMIC);
    
       (new GVTBuilder()).build(bridgeContext, document);
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 2011-10-09
      • 1970-01-01
      • 2010-11-19
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2011-07-09
      相关资源
      最近更新 更多