简体   繁体   中英

How to open a pdf file generated with itext 7 in new browser tab java

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!

PS I use Vaadin 14 and Itext 7.1.12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM