When trying to print a PDF on a mobile phone using Angular 2, the window.print() function is not creating the document or allowing it to be

I've encountered an issue while using the window.print() method in Angular 2 to print a receipt (Invoice) window as a PDF. It works perfectly on PC browsers - displaying and allowing downloading of the PDF. However, the problem arises when attempting this function on mobile browsers; it does not download or save the PDF file. Here is my downloadReceipt() method:

 downloadReciept(): void {
   var printContents, popupWin;
   printContents = document.getElementById('content').innerHTML;
   popupWin = window.open('', '_blank', 
   'top=0,left=0,height=100%,width=100%');
   popupWin.document.open();
   popupWin.document.write(`
       <html>
         <head>
         </head>

         <body onload="window.print();window.close()">${printContents} 
         </body>
       </html>`
);
popupWin.document.getElementById('hidden').style.display='block';
popupWin.document.close();
this.loading = false;


     }

This issue seems to be specific to phone browsers... I am looking for alternative ways to download invoices or generate HTML windows as PDFs in Angular 2. Any suggestions would be greatly appreciated.

Answer №1

Hey there, check out this piece of code

const displayElement = document.getElementById("componentID");
const newWindow = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
newWindow.document.write(displayElement.innerHTML);
newWindow.document.close();
newWindow.focus();
newWindow.print();
newWindow.close();

Answer №2

Greetings! I have successfully converted HTML to PDF by utilizing the print option and implementing a custom size for the document:

  1. Firstly, make sure to check the version of jQuery as the latest version may not support printing. In my case, I used

    <script src="/js/jquery.min.js"></script>

  2. To achieve a PDF with a specific canvas size, include the size property in the print media option and set the margin to zero so that the header and page count are hidden:

@media print { @page {   size:5.4cm 9.1cm; margin:0; 
page-break-after: auto;  }
  1. The printable div should have an id of target_warpper1;
  2. Additionally, use JavaScript to hide other elements using CSS

HTML:

<div id="target_warpper1_print">
    <div class="visiting-card-right">
        <div class="visiting-card-up active">Employee Id</div>
        <div class="visiting-card-down active">
            <div class="visiting-card-logo"><img src="../images/visiting-card/logo.svg" alt="Vishal Korade Logo"></div>
            <div class="visiting-card-detail">
                <div class="visiting-card-name">Vishal Korade</div>
                <div class="visiting-card-designation">Front End Developer</div>
                <div class="visiting-card-txt visiting-card-email1"><span class="card-img"><img src="../images/visiting-card/mail.svg" alt="Vishal Korade Logo"></span><span class="crad-text visiting-card-email"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed878c83858c9b84c39b849e858c81ad8a808c8481c38e8280">[email protected]</a></span></div>
                <div class="visiting-card-txt visiting-card-number1"><span class="card-img"><img src="../images/visiting-card/number.svg" alt="Vishal Korade Logo"></span><span class="crad-text visiting-card-number">9769367630</span></div>
                <div class="visiting-card-txt visiting-card-skype1"><span class="card-img"><img src="../images/visiting-card/skype.svg" alt="Vishal Korade Logo"></span><span class="crad-text visiting-card-skype">test</span></div>
                <div class="visiting-card-txt visiting-card-address1"><span class="card-img"><img src="../images/visiting-card/address.svg" alt="Vishal Korade Logo"></span><span class="crad-text visiting-card-address">7 Straits View Marina One East Tower, test, 66337</span></div>
            </div>
        </div>
    </div>
    <div class="visiting-card-left">
        <div class="visiting-card-up"><img src="../images/logohome.png" alt="Vishal Korade Logo"></div>
        <div class="visiting-card-down"><img class="page-cover" src="../images/visiting-card/page-cover.svg" alt="Vishal Korade ID Page Cover"></div>
    </div>
</div>
 <div class="download-pdf" id="create_pdf" onclick="PrintElem()">Download as PDF</div>

JS:
function PrintElem(target_warpper1)
{
    var mywindow = window.open('', 'PRINT', 'height=680,width=1200,toolbars=no,scrollbars=no,status=no,resizable=no');
   // mywindow.document.writeln('<html><head><title>' + document.title  + '</title>');
    mywindow.document.writeln('</head><body >');
    mywindow.document.writeln('<link rel="stylesheet" href="/style/style.css">');
    mywindow.document.writeln('<style>');
    mywindow.document.writeln(' * { -webkit-print-color-adjust: exact !important;  color-adjust: exact !important;        }');
    mywindow.document.writeln(' body {background-color: #1f2959;}');
    mywindow.document.writeln('.card-left {background-color: #1f2959;float: left;}');
    mywindow.document.writeln('#target_warpper1 {display: block;width: 204px;padding-bottom: 0px;float: none;margin: 0 auto;}');
    mywindow.document.writeln('.visiting-card-right {width: 204px; float: none; margin: 0px auto; }');
    mywindow.document.writeln('.visiting-card-left { width: 204px;float: none; margin: 25px auto 0;}');
    mywindow.document.writeln('#target_warpper1_print { display: block;width: 204px;padding-bottom: 0px;margin-right:0px;float: none;margin: 0 auto; }');
    mywindow.document.writeln(' .visiting-card-up, .visiting-card-down::after, .visiting-card-down::before, .visiting-measure  { display:none;}');
    mywindow.document.writeln(' @media print { @page {   size:5.4cm 9.1cm; margin:0;  page-break-after: auto;  }  html, body {  height: 99%;} .print:last-child { page-break-after: auto;}  }');
    mywindow.document.writeln('</style>');
    mywindow.document.writeln(document.getElementById('target_warpper1').innerHTML);
    mywindow.document.writeln('</body></html>');
    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/
    $(mywindow).load(function(){
       mywindow.print();
        mywindow.close();
    });
    return true;
}

If you require any further details, feel free to reach out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to conceal text that overflows from a div and seamlessly return to the beginning once the end of the text has been reached?

I am struggling to figure out how to hide the overflow text that is spilling out of the div. I attempted using overflow: hidden;, but unfortunately, it didn't work as expected. Additionally, I would like the text to loop back to the beginning once it ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

Building stateless functional components in React using Typescript version 0.14

Demonstration: import * as React from 'react' declare function obtainMarineLife(x: any): any; declare var Tank: any; var OceanicHabitat = ({category}) => ( <Tank> {obtainMarineLife(category)} </Tank> ); let y = <Ocea ...

Don't forget to save the selected tab in Angular 5 using a bootstrap tabset

Using the tabset feature from Bootstrap (specifically ngx-bootstrap.es2015.js) in an Angular 5 application has been mostly successful. However, a common issue arises when navigating between components. When transitioning back to the component with the tabs ...

The MongoDB search results did not yield the desired entries

i am attempting to display specific data for a user using req.session.user and passing the ID to the criteria i am constructing. (each entry also has a user field so i can match) but unfortunately, it is not functioning as expected. The Service : async fu ...

Http service not found

I am facing a problem with injecting HTTP into my Angular 2 application. Everything was working smoothly a few days ago, but now I am encountering this error: ORIGINAL EXCEPTION: No provider for Http! Here is the code snippet from main.ts: import { pl ...

Executing an asynchronous function within a TypeScript decorator

Apologies in advance for the lengthy question. I am striving to provide a clear explanation of the issue I am currently encountering. During the development of my decorators utilities library, I came across an unexpected behavior while working on one spec ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

The JavaScript forEach loop is compatible with every web browser except for Internet Explorer

All browsers are working with the loop except for Internet Explorer, which does not seem to support forEach. Here is the JavaScript code: function validate() { var msg = ''; var i = 0; arr.forEach( function validateinfo(){ ...

When users click on the tiles, they will act as interactive objects that will direct them to a different page within the Angular framework,

output Here is the code for my app component: <H1>AI API DEMOS</H1> <div> <ul> <li class="active"><a routerLink="/market">Market Size</a></li> <li role="presentation&qu ...

send JSON data to a Spring MVC endpoint

Here is the controller signature I have tried using @RequestBody: @RequestMapping(value = "/Lame", method = RequestMethod.POST) public @ResponseBody boolean getLame(@RequestParam String strToMatchA, @RequestParam String strToMatchB) {} This is the json I ...

TypeScript enables the use of optional arguments through method overloading

Within my class, I have defined a method like so: lock(key: string, opts: any, cb?: LMClientLockCallBack): void; When a user calls it with all arguments: lock('foo', null, (err,val) => { }); The typings are correct. However, if they skip ...

Avoiding reloading of iframe when switching between components in ReactJS

I am facing an issue with my main component that contains two child components. These child components have an array of iframe and we switch between them based on certain conditions. The problem arises when the iframe's reload every time we move betwe ...

Utilizing JSON and Javascript to dynamically generate and populate interactive tables

Here's how I've structured my JSON data to define a table: var arrTable = [{"table": "tblConfig", "def": [{"column": "Property", "type": "TEXT NOT NULL"}, {"column": "Value", "type": "TEXT NOT NULL"}], "data": [{"Property ...

Using Regular Expression to verify the presence of numbers and spaces

Currently, I have implemented a regular expression that ensures my string contains 5 digits. While this regex works flawlessly, I now also require it to allow white spaces: both "123 45" and "12345" should meet the criteria. string.match(/^\d{5}$/g); ...

Using Jquery and CSS to add a class with a 1-second delay when the mouse enters

I have successfully implemented the addClass function in my code, but I'm encountering issues when attempting to use delay or setTimeout functions. It's important to note that I'm avoiding the use of webkit attributes in CSS. If anyone has ...

The imported package is not functioning properly within the project

I've recently developed a Typescript Package and I want to test it in an application before publishing it on NPM. The main file (index.ts) of the package is structured like this => import Builder from './core/builder'; export default ...

Steps for verifying the presence of an element in Selenium using JavaScript

I'm facing an issue with a Jest and Selenium test. I'm trying to verify if an element is removed from the DOM after being clicked. Here's what I've attempted: test('User removes button after clicking on it', async (done) =& ...

Calling a Cloud Function directly with AngularFireFunction

I am currently facing an issue with integrating cloud functions as ExpressJS in my Angular website. While the cloud functions work perfectly fine when accessed directly at http://localhost:5001/project_id/us-central1/app, they seem to not function properly ...

Dynamic selection of elements using a parameterized variable in JQuery

Having some trouble with the following line of code: alert($('input' + ' #' + $id_bici).attr('value')); Here is the corresponding HTML code snippet: <input type="hidden" id="id_bici1" name="id_bici1" value="9"> ...