You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache FOP 2.7:Spring Boot+Maven项目如何读取resources目录图片?

Apache FOP 2.7 加载Spring Boot资源目录图片的解决方案

方法1:直接读取classpath资源

图片位于src/main/resources/static/test.jpg,打包后属于classpath资源,可直接通过classpath协议引用,无需走HTTP:
在XSL中修改图片引用:

<fo:external-graphic src="url('classpath:/static/test.jpg')" content-height="24mm" content-width="190mm"/>

同时需要在初始化FopFactory时配置资源解析器,让FOP能识别classpath协议:

import org.apache.fop.apps.FopFactory;
import org.springframework.core.io.ClassPathResource;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.InputStream;

// 初始化FopFactory并配置URI解析器
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
fopFactory.setURIResolver((href, base) -> {
    if (href.startsWith("classpath:/")) {
        ClassPathResource resource = new ClassPathResource(href.substring(10));
        InputStream is = resource.getInputStream();
        return new InputSource(is);
    }
    // 处理其他类型URL
    return new InputSource(href);
});

方法2:动态生成应用基础URL替换占位符

在Spring Boot中通过ServerProperties获取当前端口,动态替换XSL中的占位符:

  1. 修改XSL中的图片引用为占位符:
<fo:external-graphic src="url('${appBaseUrl}/test.jpg')" content-height="24mm" content-width="190mm"/>
  1. 在Java代码中生成基础URL并替换:
import org.springframework.boot.web.server.ServerProperties;
import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.StringReader;
import org.xml.sax.InputSource;

@Resource
private ServerProperties serverProperties;

// 构建应用基础URL
String appBaseUrl = "http://localhost:" + serverProperties.getPort();
// 读取XSL文件内容并替换占位符
String xslContent = Files.readString(Paths.get("src/main/resources/your-template.xsl"));
xslContent = xslContent.replace("${appBaseUrl}", appBaseUrl);
// 生成用于转换的InputSource
InputSource xslInput = new InputSource(new StringReader(xslContent));

如果是部署在反向代理或多实例环境,建议从HttpServletRequest中获取真实请求URL来构建appBaseUrl,避免硬编码localhost。

方法3:配置FOP基础URI(适配2.7版本)

Apache FOP 2.7仍支持设置基础URI,通过FopFactory.setBaseURI()实现:

import org.apache.fop.apps.FopFactory;
import java.io.File;

// 获取当前应用基础URI(可从请求或配置中获取)
String baseUri = "http://localhost:" + serverPort;
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
fopFactory.setBaseURI(baseUri);

之后XSL中使用相对路径即可:

<fo:external-graphic src="url('test.jpg')" content-height="24mm" content-width="190mm"/>

FOP会自动将相对路径拼接在基础URI后。

内容的提问来源于stack exchange,提问作者Lako12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:03:25