Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jsp javaservlet中的iText图像_Jsp_Image_Servlets_Itext - Fatal编程技术网

Jsp javaservlet中的iText图像

Jsp javaservlet中的iText图像,jsp,image,servlets,itext,Jsp,Image,Servlets,Itext,我在Javaservlet中使用iText(pdf/rtf)生成字母,但在访问图像时遇到问题。图像位于WebContent/images文件夹中。当我在本地服务器上运行它并指向images目录(c://eclipse/myproject/WebContent/images/letterHead.jpg)的完整路径时,它可以正常工作,但它无法在服务器上使用目录(“WebContent/images/letterHead.jpg”)运行 该项目作为WAR部署在tomcat服务器上,因此最终的地址类似

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

该项目作为WAR部署在tomcat服务器上,因此最终的地址类似于

http://someserver:8081/projectName/someJSP.jsp
我不知道在这种环境下如何相对地引用这些图像,任何帮助都将不胜感激

这是我的密码

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

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

可以使用将相对web路径转换为绝对磁盘文件系统路径。相对web路径以公共webcontent文件夹为根,在您的案例中,该文件夹是
/webcontent
。因此,您需要将上述代码的第一行替换为:

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

以下代码可用于访问java类内的映像路径

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

下面的代码可能会帮助您

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);

所以我也遇到了同样的问题,我想通过一个相对路径向pdf添加一个图像,所以当我制作一个可执行程序时,它可以在任何计算机上运行,即使它保存了或没有保存图像

我找到了一种方法,可以将图像添加为应用程序的资源。您需要将映像放在调用它的类的src目录或dir目录中,然后可以使用以下代码:

Image image = Image.getInstance(yourClassName.class.getResource("/yourImageName")));
如果将图像放在文件夹中,那么显然需要通过文件夹名称(“folderName/yourmagename”)添加路径。希望有帮助


对于Kotlin,如果图像位于
resources
文件夹中,还可以尝试以下操作:

Image.getInstance(this::class.java.classLoader.getResourceAsStream(“images/your_Image.png”).readBytes())

参考资料中没有op的图像。
Image foto = Image.getInstance(this.getClass().getResource("/static/img/gobierno.jpg"));