iText image in java servlet

后端 未结 6 657
逝去的感伤
逝去的感伤 2021-01-13 13:45

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

相关标签:
6条回答
  • So I had the same problem, I wanted to add an image to the pdf but through a relative path, so when I made a executable program it would work in any computer, even if it had or not the image saved.

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

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

    If you put the image inside a folder then, obviously, you'll need to add the path through the folders name ("folderName/yourImageName"). Hope it helps!

    0 讨论(0)
  • 2021-01-13 14:07

    Following code can be used to access image path inside a java class.

    URL imageUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
    Image img=Image.getInstance(imageurl+"../../../some/images/pic.gif");    
    
    0 讨论(0)
  • 2021-01-13 14:12

    Resources

    Image foto = Image.getInstance(this.getClass().getResource("/static/img/gobierno.jpg"));
    
    0 讨论(0)
  • 2021-01-13 14:14

    For Kotlin, if the image is in the resources folder, you can also try the following:

    Image.getInstance(this::class.java.classLoader.getResourceAsStream("images/your_image.png").readBytes())

    0 讨论(0)
  • 2021-01-13 14:19

    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);
    // ...
    
    0 讨论(0)
  • 2021-01-13 14:19

    Following piece of code may 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);
    
    0 讨论(0)
提交回复
热议问题