How to print React component on click of a button?

前端 未结 8 2060
执念已碎
执念已碎 2020-12-03 01:42

How can I print only one component on click of a button.

I know this solution:

window.frames[\"print_frame\"].window.focus();
window.frames[\"print         


        
8条回答
  •  一整个雨季
    2020-12-03 01:54

    There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though:

    var content = document.getElementById("divcontents");
    var pri = document.getElementById("ifmcontentstoprint").contentWindow;
    pri.document.open();
    pri.document.write(content.innerHTML);
    pri.document.close();
    pri.focus();
    pri.print();
    

    This expects this html to exist

    
    

    The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print.

    
    

    Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs.

提交回复
热议问题