目录结构
MYProjectName
WebContent(Folder)
-Images (Folder)
--isilog.gif
/*下面是我的代码。我已将 WebContent 中的图像作为静态图像。 我想从图像文件夹中动态获取它。 */
public class ABC {
public static final String DEST = "G://HRS Barcode/ISILOGO.pdf";
public static final String IMG = "D://MyFolder Workplace/MYProjectName/WebContent/images/isilog.gif";
public static void main(String[] args) throws IOException,
DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new ABC().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
OutputStream out = null;
Document document = new Document();
Rectangle pageSize = new Rectangle(432, 288);
document.setPageSize(pageSize);
document.setMargins(11, 11, 11, 11);
PdfWriter.getInstance(document, new FileOutputStream(dest));
Barcode128 code128 = new Barcode128();
out = new FileOutputStream(DEST);
out = new BufferedOutputStream(out);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
document.setMarginMirroringTopBottom(true);
PdfPTable table = new PdfPTable(2);
table.setWidths(new int[] { 2, 7 });
Image img = Image.getInstance(IMG);
PdfPCell cell = new PdfPCell(img, true);
cell.setPadding(0);
cell.setBorder(PdfPCell.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_LEFT); // ALIGN_BASELINE
cell.setVerticalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
table.addCell("XYZ company Ltd");
cell.setBorder(PdfPCell.NO_BORDER);
document.add(table);
LineSeparator separator = new LineSeparator();
Chunk linebreak = new Chunk(separator);
document.add(linebreak);
document.close();
System.out.println("Document Generated...!!!!!!");
writer.close();
}
}
最佳答案
从项目的图像文件夹加载图像的简单方法是使用这个简单的 1 行代码。(相应地尝试您的 URL)
方式一:
File sourceimage = new File("D://MyFolder Workplace/MYProjectName/WebContent/images/isilog.gif");
Image image = ImageIO.read(sourceimage);
方式2:
BufferedImage img = ImageIO.read(getClass().getResourceAsStream("/images/isilog.jpg"));
如果您想进一步了解,可以随时查看文档。
这是link to Reading/Loading an Image using java
关于java - 如何从Web项目内的文件夹(WebContent/images/isilog.gif)获取图像文件URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45647466/