I make a pdf file in java using itext 7 and can save it on my local computer.
How can I open this file in new browser tab somehow without storing it on my computer?
I solved my problem that.
Here I generate a pdf file and return his StreamResource:
public static StreamResource generateTestPdf(){
ByteArrayOutputStream dest = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
Paragraph title = new Paragraph("Hello World!");
document.add(title);
StreamResource streamResource = null;
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
document.close();
ByteArrayInputStream inputStream = new ByteArrayInputStream(dest.toByteArray());
streamResource = new StreamResource("file.pdf", new InputStreamFactory() {
@Override
public InputStream createInputStream() {
return inputStream;
}
});
return streamResource;
}
After that I add on my page a Button with listener, that opens generated file in browser new tab:
Button print = new Button("Print");
print.addClickListener(e -> {
this.close();
final StreamRegistration registration = VaadinSession.getCurrent().getResourceRegistry().registerResource(PdfGenerator.generateTestPdf());
UI.getCurrent().getPage().setLocation(registration.getResourceUri());
}
);
I don’t know how correct this solution is, but it worked for me. Thanks to all!
P.S. I use Vaadin 14 and Itext 7.1.12