views:

635

answers:

2

Hi,

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").

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.

Here is my code

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

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.

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);
// ...
BalusC
It works perfectly! Thank you very much.
Jon
A: 

it really works but it is weird solution

Levent
It may indeed look weird if you don't **understand** how/why it works that way "under the hoods". Once you understand it, it'll be nothing more than obvious. Oh, this "answer" should rather have been posted as a comment, not as an answer. If you earn 50 reputation, you'll be able to post comments on other's questions/answers :)
BalusC