I would like to print out the content of a homepage created with Vaadin 14 from a button.
with Vaadin 8 was a solution that unfortunately is no longer applicable:
Button print = new Button("Print This Page");
print.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
// Print the current page
JavaScript.getCurrent().execute("print();");
}
});
Any Idea how to do this in Vaadin14 please?
In Vaadin 10 and later, you can run arbitrary JavaScript by calling Page::executeJs
UI.getCurrent().getPage().executeJs( … )
There you should be able to call the same print function. See: Executing JavaScript in the Browser.
So in your case, for printing the current page:
UI.getCurrent().getPage().executeJs( "print();" ) ;
Full example in Vaadin 14.0.12, using lambda syntax:
package com.example;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
/**
* The main view contains a button and a click listener.
*/
@Route ( "" )
public class MainView extends VerticalLayout
{
public MainView ( )
{
this.add( new H1( "Print example" ) );
Button printButton = new Button( "Print…" );
printButton.addClickListener( ( ClickEvent < Button > clickEvent ) ->
{
UI.getCurrent().getPage().executeJs( "print();" );
} );
this.add(printButton);
}
}