我正在尝试将用户选择的图像添加到我在netbeans中通过pdfbox生成的pdf中。如果我直接给出直接路径然后它正在工作但是获取图像路径的URL并添加它不起作用。
看到给定的代码问题是URL和Path,因为输入没有被读取
public static ByteArrayOutputStream PDFGenerator(........,Path imagespath)
{
........
if (finalpdf.Images != null)
{
Path imagepath = Paths.get(imagespath.toString(), "room.png");
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath.toString(), pdf);
AddImages(content, Addedimage, 229.14f, 9.36f);
}
//AddImages method is following
public static void AddImages(PDPageContentStream content, PDImageXObject image, float x, float y) throws IOException
{
content.drawImage(image, x, y);
}
}
//Following is snippet from my test method
public void testClass()
{
........
finalpdf.Images = "room.png";
URL imageurl = testclass.class.getResource("room.png");
Path imagepath = Paths.get(imageurl.getPath().substring(1));
ByteArrayOutputStream baos = PDFGenerator.generatefurtherpdf(finalpdf, "0000.00", "00.00", imagepath);
writePDF(baos, "YourPdf.pdf");
}
我希望它以这种方式工作,但我确定它与Path的一些问题,我没有正确使用它。我希望代码足够解释,因为我很新也有安全原因所以我不能把整个代码。抱歉错误
对于资源(从来不是File
),存在一个广义类:Path
。
Path path = Paths.get(imageurl.toURI());
但是,只要该路径(例如使用URL'jar:file // ... .jar!... ... .png)将用作文件,path.toString()
建议,可以使用InputStream。
第二个广义类是更低级别的InputStream
:
InputStream in = TestClass.getResourceAsStream(imagepath);
这是从未使用过的getResource().openStream()
的捷径。当资源路径不正确时抛出NullPointerException。
最后的办法是使用qazxsw poi的实际qazxsw poi。
byte[]
使用临时文件
createFromByteArray