Image of iText in a Java Servlet

I am creating a letter using iText (pdf / rtf) in a Java servlet and am getting a problem accessing images. Images are located in the WebContent / images folder. When I run it on the local server and specifying the path of the full image directory (c: //eclipse/myproject/WebContent/images/letterHead.jpg), it works, but it does not work on the server with the directory ("WebContent / image / letterHead. jpg ").

The project is deployed as a WAR on the tomcat server, and ends with an address similar to

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

I do not understand how to relate to images relatively in this environment, and any help would be greatly appreciated.

Here is my code

 Image imghead = Image.getInstance("WebContent/images/letterHead.jpg"); imghead.setAbsolutePosition(35,770); imghead.scaleAbsolute(125, 42); document.add(imghead); 
+4
source share
5 answers

You should not use relative paths in java.io materials. You will depend on the current working directory, which is in no way controlled in the case of a web application. Always use the absolute path to the disk file system. So c:/full/path/to/file.ext .

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

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

The following code snippet can help you ...

 String path = request.getContextPath(); String split_path[] = path.split("/"); path = request.getRealPath(split_path[0]); String imagePath="\\resources\\images\\letterHead.jpg"; Image image = Image.getInstance(path+imagePath); 
+1
source

The following code can be used to access the image path inside the java class.

 URL imageUrl = getClass().getProtectionDomain().getCodeSource().getLocation(); Image img=Image.getInstance(imageurl+"../../../some/images/pic.gif"); 
0
source

So, I had the same problem, I wanted to add the image to pdf, but through a relative path, so when I created the executable program, it would work on any computer, even if it was or not. / p>

I found a way to add an image as a resource of your application. You need to put the image in the src directory or in the directory where you call it, and then you can use the following code:

 Image image = Image.getInstance(yourClassName.class.getResource("/yourImageName"))); 

If you place the image inside a folder, then obviously you will need to add the path through the folder name ("folderName / yourImageName"). Hope this helps!

0
source

Resources

 Image foto = Image.getInstance(this.getClass().getResource("/static/img/gobierno.jpg")); 
-1
source

Source: https://habr.com/ru/post/1303212/


All Articles