spring Boot jar包工程下引用靜態資源
最近在寫一個sprin-boot專案。其中涉及到了PDF跟字型檔案的引用。
由於主工程打的是jar包,所以,他不像傳統的web專案那樣,可以把靜態資源放在web-info下面。而我們引用的jar包,給pdf設定水印需要傳入引用的路徑。
期初在網上查了很多資料,他們jar包下的引用用的是用流引用
如下
ClassPathResource classPathResource = new ClassPathResource("template/contractTemplate.pdf");
try {
InputStream inputStream = classPathResource.getInputStream();
byte b[]=new byte[2048];
inputStream.read(b);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
但是 PdfReader reader = new PdfReader (“路徑”)
這裡需要傳入一個路徑,所以用流就不能引用這個給PDF加水印的方法。
後來想到了:
URL url = PdfSetWaterPrint.class.getClassLoader().getResource(".");
// String path = resource.toString();
// System.out.println(path);
// path += "font/msyh.ttf";
或者:
Enumeration<URL> url = ClassLoader.getSystemResources("font/msyh.ttf");
//String url1 = url.getClass().getClassLoader().getResource("font/msyh.ttf")+"";
//ClassPathResource resource = new ClassPathResource("font/msyh.ttf");
來獲取路徑的方法,
但是一打jar包後就引入不到檔案
後來發現只要是靜態的資源打jar包就引入不到。
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
<include>**/*.jsp</include>
<include>**/*.ftl</include>
<include>**/*.html</include>
<include>**/*.txt</include>
<include>**/*.pdf</include>
<include>**/*.ttf</include>
</includes>
<excludes>
<exclude>template/*.pdf</exclude>
<exclude>font/*.ttf</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
<include>**/*.ftl</include>
<include>**/*.html</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
後來就想到把標紅的給刪除,但是刪除後就不能引用PDF了,會報空指標。後來就想到了加
<excludes>
<exclude>template/*.pdf</exclude>
<exclude>font/*.ttf</exclude>
</excludes>
打包的過程中把靜態資源給過濾掉。
ClassPathResource resource = new ClassPathResource("template/contractTemplate.pdf");
//System.out.println(resource.getFile());
//InputStream stream = resource.getInputStream();
//File targetFile = new File("hetong.pdf");
//FileUtils.copyInputStreamToFile(stream, targetFile);
//BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));