I have a PDF viewer before that works using the StreamResource class. Now I am using version 24.8 and I need to display the PDF in the Dialog component. My issue is I am getting gibberish data when displayed. Below is my implementation.
VerticalLayout pdfLayout = new VerticalLayout();
pdfLayout.setSizeFull();
// Create an anchor link to download the file.
Anchor pdfViewerAnchor = new Anchor(DownloadHandler.fromInputStream(downloadEvent -> {
try {
return new DownloadResponse(new ByteArrayInputStream(fileData), fileName, mimeType, fileData.length);
} catch (Exception e) {
return DownloadResponse.error(500);
}
}), "Download attachment");
// Create a PDF viewer to view the file in the dialog component.
HtmlObject pdfStreamObject = new HtmlObject();
pdfStreamObject.setData(downloadHandler -> {
try (OutputStream out = downloadHandler.getOutputStream()) {
out.write(fileData);
downloadHandler.setFileName(fileName);
downloadHandler.setContentType(mimeType);
downloadHandler.setContentLength(fileData.length);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
pdfStreamObject.getElement().addAttachListener(elementAttachEvent -> {
String pdfUrl = pdfStreamObject.getElement().getAttribute("src");
if (pdfUrl != null) {
Html pdfViewer = new Html("<iframe src='" + pdfUrl + "' width='100%' height='600px' style='border:none;'></iframe>");
pdfLayout.add(pdfViewer);
} else {
pdfLayout.add(new Html("<p>Unable to load PDF preview.</p>"));
}
});
dialogLayout.add(pdfViewerAnchor, pdfStreamObject);
May I know what I did wrong? Also, you may see my output screenshot below.
Thank you for your advance help. ![]()
