首页 > 解决方案 > 如何在 asp.net core component.razor 中打印特定的“div”区域 ..?

问题描述

在这里,我在 asp.net 核心中放置了我的基本应用程序的编码,这是用于打印 div 的id="printableArea"。这段代码工作清楚。

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
<div id="printableArea" class="stylesheet">
    <table  id="myTable" class="table">
         <thead>

            <tr>                 
                <th>Pipe Type</th>
                <th>DIA</th>
                <th>Laek Type</th>
            </tr>
        </thead>
            <tr>
                <td>1</td>
                <td>2</td>
                <td>3</td>
            </tr>
    </table>
</div>

脚本

<script>
function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
}
</script>

但问题是,我必须在 component.razor 中做同样的事情,我不知道如何在没有脚本的情况下执行它。另一方面 blazor 页面(component.razor)不允许编写脚本。请给出你的解决方案。

<input type="button" />
<div id="printableArea" >
<div>
@code{

}

标签: javascriptasp.net-coreasp.net-blazorrazor-components

解决方案


我是这样解决的:

在 _Host.cshtml 中将此代码放在脚本部分:

<script type="text/javascript">

        function printDiv() {
            var divContents = document.getElementById("PrintDiv").innerHTML;
            var a = window.open('', '', 'height=500, width=500');
            a.document.write('<html>');
            a.document.write('<body > <br>');
            a.document.write(divContents);
            a.document.write('</body></html>');
            a.document.close();
            a.print();
        }
    </script>

在剃须刀组件中:

<div id="PrintDiv" class="row">
    <h1>Megatron</h1>
    <h3>Hola Mundo Megatron</h3>
    Here I put my design, for example an invoice.
</div>

<div class="row">
    <div class="col-4">
        <button class="btn btn-primary" @onclick="PrintAsiento">Imprimir DIV</button>
    </div>
</div>

在代码部分:

public async Task PrintAsiento()
    {
        await IJS.InvokeVoidAsync("printDiv");
    }

推荐阅读