英文:
How to open a pdf file generated with itext 7 in new browser tab java
问题
我使用iText 7在Java中创建了一个PDF文件,并可以将其保存到我的本地计算机。
有什么方法可以在新的浏览器选项卡中打开这个文件,而不必将它存储在我的计算机上?
英文:
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?
答案1
得分: 0
我解决了我的问题。
在这里,我生成一个 PDF 文件并返回其 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;
}
之后,我在页面上添加了一个带有监听器的按钮,该监听器会在浏览器的新标签页中打开生成的文件:
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());
});
我不确定这个解决方案是否正确,但它对我起作用。谢谢大家!
附注:我使用的是 Vaadin 14 和 Itext 7.1.12。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论