简体   繁体   English

如何在 Angular 中实现打印功能?

[英]How can I implement a print functionality in Angular?

I am trying to implement a print functionality within my invoicing app, however, the print function I have only works for me once-that is, on the first click only.我正在尝试在我的发票应用程序中实现打印功能,但是,我只有一次打印 function 对我有用 - 也就是说,仅在第一次点击时。 When I try to click again the click function is not triggered.当我尝试再次单击时,不会触发单击 function。 And when I check my console.log, the following is error is thrown: ERROR TypeError: Cannot read property 'postMessage' of null当我检查我的console.log时,抛出以下错误: ERROR TypeError: Cannot read property 'postMessage' of null

Here is what i have tried:这是我尝试过的:

 printInvoice() { const printContents = document.getElementById('print-index-invoice').innerHTML; const originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; }
 <div class="modal fade" id="modalIndexInvoicePreview" tabindex="-1" role="dialog"> <button type="submit" class="btn btn-info btn-lg mt-2 position-absolute" (click)="printInvoice()"> <i class="fa fa-print icon-print"></i>Print</button> <div class="modal-dialog modalContent"> <div class="modal-content modalIndexInvoicePreview" id="print-index-invoice"> <div class="modal-header div-logo"> <img class="logo-invoice" [src]="logoUrl"> <div> <b>Invoice|Receipt|Attachment</b> </div> </div> </div> </div> </div>

There are 2 ways to achieve the print functionality.有两种方法可以实现打印功能。 First is you can utilize CSS media which will allow you to use media as "print".首先是您可以使用 CSS 媒体,这将允许您将媒体用作“打印”。

The second option is to attach CSS to your print section part.第二个选项是将 CSS 附加到您的打印部分。 You can easily enable media to "print while" attaching the external stylesheet to your print module.您可以轻松地启用媒体“打印”,同时将外部样式表附加到您的打印模块。 For now, I have enabled the bootstrap in the print module.现在,我已经在打印模块中启用了引导程序。 You can use your own stylesheet in place of the bootstrap.您可以使用自己的样式表代替引导程序。

Visit jsfiddle.net/rdtzvf2c/1/访问jsfiddle.net/rdtzvf2c/1/

As you can see in the result, the top text and image are being pulled in the center which is happening through the bootstrap CSS applied dynamically while printing the div.正如您在结果中看到的,顶部的文本和图像被拉到中心,这是通过在打印 div 时动态应用的引导程序 CSS 发生的。

Do let me know in case of any other help.如果有任何其他帮助,请告诉我。

 function printDiv() { var divToPrint = document.getElementById('print-index-invoice'); var newWin = window.open('', 'Print-Window'); newWin.document.open(); newWin.document.write('<html><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" media="print"/><body onload="window.print()">' + divToPrint.innerHTML + '</body></html>'); newWin.document.close(); setTimeout(function() { newWin.close(); }, 10); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="modal-content modalIndexInvoicePreview" id="print-index-invoice"> <div class="container col-md-12"> <div class="text-center"> This is right aligned: <img src="https.//www.gstatic.com/webp/gallery3/1.png" class=" rounded mx-auto d-block" alt="..;"> </div> </div> <div class="modal-header div-logo"> <div> <b>Invoice|Receipt|Attachment</b> </div> </div> </div> <input type='button' id='btn' value='Print' onclick='printDiv();'>

Try this尝试这个

printInvoice() {
            var divToPrint = document.getElementById('print-index-invoice');
            var newWin = window.open('', 'Print-Window', 'width=1200,height=700');
            newWin.document.open();
            newWin.document.write('<html><head><link href="app/assets/css/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/><link href="app/assets/css/print.css" rel="stylesheet" type="text/css"/><style></style> </head><body onload="window.print()">' + divToPrint.innerHTML + '</body></html>');
            newWin.document.title = 'Your PDF Title';
            newWin.document.close();
            }

do it in a clean way and can add CSS and data to print page以干净的方式进行操作,可以将 CSS 和数据添加到打印页面

     //inside component where print button event triggered
        PrintTransformerResult(): void {
            // const transformerPanels = this.transformer;
            this.printService.printDocument('T146', this.transformer);
          }

        //inside service
        printDocument(documentName: string, documentData: any): void {
            this.router.navigate(['/', { outlets: { print: ['print', {queryParams: JSON.stringify(documentData)}]}}]);
          }


        //inside print layout component.ts
        export class PrintLayoutComponent implements OnInit {

          invoiceIds: any;
         data: any;
          constructor(route: ActivatedRoute,
                      private router: Router,
                      private printService: PrintService) {
            this.invoiceIds = route.snapshot.paramMap;
          }

        ngOnInit(): void {
            console.log('xsssdsd' + JSON.stringify(this.invoiceIds));
            this.data= JSON.parse(this.invoiceIds.params.queryParams);
            setTimeout(() => {
              window.print();
              this.router.navigate([{ outlets: { print: null }}]);
            }, 2000);
          }

        }

        //inside print layout component.html
        <div class="color-black font-18 ml-auto mb-10 text-center">
          <span class="font-w9">{{data?.customer_name}}</span>
          <span class="opacity-4 font-14 pl-4"><b>{{data?.object_id}}</b></span>
        </div>


        <div>
           <span class="color-black2 font-16 width-full font-w9">T146 Input P146-1 : </span> <span class="ml-15">{{data?.modified_on}}</span>
          <div class="mt-10">
              Identification: {{data?.name}}
          </div>
        </div>

           <-- custome tag, passing data -->
          <div class="height-full" style="height: 100%;">
            <app-t146-panel1-view [data]="data">
            </app-t146-panel1-view>
          </div>


    // inside app component html
    <router-outlet></router-outlet>
    <router-outlet name="print"></router-outlet>

    //inside routing module.ts
    const appRoutes: Routes = [
        { path: '', redirectTo: '/home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent },

        { path: 'print', outlet: 'print', component: PrintLayoutComponent}
    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何实现Javascript自动完成功能? - How can I implement Javascript autocomplete functionality? 如何实现 2048 的合并功能 - How can I implement the merge functionality for 2048 如何获得IE的Javascript来实现“ this”关键字功能? - How can I get IE's Javascript to implement the 'this' keyword functionality? 如何在GMail中实现聊天窗口的弹出功能? - How can I implement the pop out functionality of chat windows in GMail? Angular中如何实现分享到facebook/twitter的功能 - How to implement sharing to facebook/twitter functionality in Angular Angular:如何在Angular 5中实现ng-include功能? - Angular: How to implement ng-include like functionality in Angular 5? 如何在 React 应用程序中实现类似 Wordle 的共享功能? - How can I implement a Wordle-like sharing functionality in a React application? 如何在Three.js中从任何摄像机角度实现ZoomAll功能? - How can I implement ZoomAll functionality from any camera angle in Three.js? 在没有滚动条的情况下,如何在具有“文本溢出:省略号”的文本上实现水平滚动拖动功能? - How can I implement horizontal scroll on drag functionality on text that has “text-overflow: ellipsis” without the scrollbar? 如何在所有浏览器中禁用网页的打印屏幕功能? - How can I disable print-screen functionality for a webpage in all browsers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM