java servlet中的iText图像 [英] iText image in java servlet

查看:126
本文介绍了java servlet中的iText图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java servlet中的iText(pdf / rtf)进行字母生成,并且在访问图像时遇到了问题。图像位于WebContent / images文件夹中。当我在本地服务器中运行它并指向images目录的完整路径(c://eclipse/myproject/WebContent/images/letterHead.jpg)时,它的工作正常,但它无法在带有目录的服务器上运行(WebContent / images / letterHead.jpg)。

I'm doing the letter generation with iText (pdf/rtf) in java servlet and got a problem with accessing images. The images are in the WebContent/images folder. When I run it in a local server and pointing the full path of images directory (c://eclipse/myproject/WebContent/images/letterHead.jpg) its working, but it fails running on the server with the directory ("WebContent/images/letterHead.jpg").

该项目在tomcat服务器上被部署为WAR,最终得到的地址类似于

The project is being deployed as a WAR on a tomcat server, thus ending up with an address similar to

http://someserver:8081/projectName/someJSP.jsp

我不明白如何在这种环境中相对地引用图像,并且非常感谢任何帮助。

I don't understand how to reference the images relatively in this environment, and any help would be much appreciated.

这是我的代码

Image imghead = Image.getInstance("WebContent/images/letterHead.jpg");
imghead.setAbsolutePosition(35,770);
imghead.scaleAbsolute(125, 42);
document.add(imghead);


推荐答案

你绝不应该在<$ c $中使用相对路径c> java.io 东西。您将依赖于当前工作目录,在Web应用程序的情况下,该目录无法控制。始终使用绝对磁盘文件系统路径。因此, c:/full/path/to/file.ext

You should never use relative paths in java.io stuff. You will be dependent on the current working directory which is in no way controllable in case of a webapplication. Always use absolute disk file system paths. Thus, c:/full/path/to/file.ext.

你可以使用 ServletContext #getRealPath() 将相对Web路径转换为绝对磁盘文件系统路径。相对Web路径根植于公共webcontent文件夹,在此情况下为 / WebContent 。因此,您需要将以上代码的第一行替换为:

You can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path. The relative web path is rooted on the public webcontent folder which is in your case thus /WebContent. So, you need to replace the first line of above code by:

String relativeWebPath = "/images/letterHead.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Image imghead = Image.getInstance(absoluteDiskPath);
// ...

这篇关于java servlet中的iText图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆