I am trying to add an image to a pdf file. The image is in "WebContent / img / image.png". First, I save the relative path to the string, and then convert this relative path to the real path.
String relativeWebPath = "/img/image.png";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Image image1 = Image.getInstance(absoluteDiskPath);
Even this one
String absoluteDiskPath = getServletContext().getRealPath("/");
does not work.
I tried several options when I determined the relative path, but could not get them to work. I always get a nullPointerException when this line String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);tries to execute. Am I doing something wrong with a relative path or something else? I don't know if this is relevant, but I am using Spring .
@RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public void exportPhonebook(Model model, HttpServletResponse response) {
try {
setResponseHeaderPDF(response);
Document document = new Document();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter pdfWriter = null;
pdfWriter = PdfWriter.getInstance(document, baosPDF);
PageNumbersEventHelper events = new PageNumbersEventHelper();
pdfWriter.setPageEvent(events);
document.open();
addMetaData(document);
addTitlePage(document);
String relativeWebPath = "/img/image.png";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Image image1 = Image.getInstance(absoluteDiskPath);
document.add(image1);
addContent(document);
document.close();
pdfWriter.close();
OutputStream os = response.getOutputStream();
baosPDF.writeTo(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This is how I used it in jsp:
<input type="hidden" value="<%=getServletContext().getRealPath("/") %>" name="path">
I pass this to the controller and add a relative path to this path.
path = path + "img\\image.png";
Image image = Image.getInstance(path);
.
, .