How to Print in Vaadin Flow?

三世轮回 提交于 2019-12-13 01:28:31

问题


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?


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/58754154/how-to-print-in-vaadin-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!