javavaadinvaadin8

How to open browser print window with Vaadin BrowserFrame


I would like the PDF to open immediately to the browser's print window rather than the BrowserFrame in Vaadin. Right now my code is:

Window window = new Window();

StreamResource streamResource = getPdfAsStream();
streamResource.setMIMEType("application/pdf");

BrowserFrame browserFrame = new BrowserFrame("PDF File", streamResource);
browserFrame.setId("pdfToPrintBrowserFrame");

window.setContent(browserFrame);
UI.getCurrent().addWindow(window);

Is there a way to do something like:

JavaScript.getCurrent().execute(
    "document.getElementById('pdfToPrintBrowserFrame').contentWindow.print();");

This code doesn't work but in essence I'd like to call the browser's print through Javascript on the pdf. How can this be done?


Solution

  • I eventually found two options:

    The first is to use an iFrame:

    StreamRegistration registration = VaadinSession.getCurrent().getResourceRegistry().registerResource(streamResource);
    IFrame iframe = new IFrame(registration.getResourceUri().toString());
    // Setting the width to 100% results in a scrollbar for some reason and I cannot find a way to remove it. 
    iframe.setHeight("95%");
    iframe.setWidthFull();
    
    DialogWithCloseButton dialog = new DialogWithCloseButton();
    dialog.setWidth("80%");
    dialog.setHeight("90%");
    dialog.open();
    dialog.add(iframe);
    

    The other option which I like a lot is to use the Pdf Viewer add-on from the Vaadin directory which can be found at: https://vaadin.com/directory/component/pdf-viewer

    I found the second option (the pdf viewer component) to be the better option for me. It's a lot richer. The only thing is that it may be more than you want.

    Also I remember something about printing more than once but it's been a while so it could be something or it could be nothing. If the printing fails on the second attempt then there may be something that needs to be done, I just don't remember what.