Using window.print() or alternative on Android devices
Asked Answered
L

8

20

On Android devices (I have tested Nexus 5, Nexus 10, Galaxy S4 and Galaxy Tab 3), the window.print() command in JavaScript doesn't do anything. As far as I can tell it doesn't even register an error.

I know for a fact that most if not all of these browsers can print because you can use mobile Chrome's menu to choose "print".

Why doesn't window.print() trigger the behavior you would expect (opening the clients print menu)? And is there an Android alternative to window.print()?

Linebreeding answered 31/10, 2014 at 22:12 Comment(1)
You need an app to print from an android: play.google.com/store/apps/…Talmud
A
10

It is clearly stated in this Documentation, "The command is supported on iOS, Chrome on Windows and Safari and Chrome on Mac. It is not supported on Android."

Android phones don't have native support for printing yet, so window.print() will not work. Which means you need to use third-party app to do the printing. You could find some alternatives in this article.

Azedarach answered 6/11, 2014 at 3:40 Comment(1)
yea i installed google cloud print app, when i click the google cloud print button, the dialog box will open and i choose printer then click the print nothing happen. now what should i do?Jaleesa
M
7

I'm working on a simular problem and came up with this solution:

$(document).ready(function($) {
  var ua = navigator.userAgent.toLowerCase();
  var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");

  $('button.print').click(function(e) {
    e.preventDefault();
    if (isAndroid) {
      // https://developers.google.com/cloud-print/docs/gadget
      var gadget = new cloudprint.Gadget();
      gadget.setPrintDocument("url", $('title').html(), window.location.href, "utf-8");
      gadget.openPrintDialog();
    } else {
      window.print();
    }
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="print">Print this page</button>

I haven't had the time to check if this works, i don't have an android device with me at the moment. I Would love to have some feedback on this ;-)

Miquelon answered 6/3, 2015 at 9:27 Comment(5)
This is a nice solution, actually more or less what I went with in the end, but my main concern was that I can do the equivilent of File -> Print on my android device (Menu button -> Print) but I can not trigger this with the semi standard window.print() functionLinebreeding
I could not find the Print command on Chrome android. I can find share ... > Printer.Cruciferous
I have not been able to find the mobile character string in any user agent character string so far. Also, the trouble is that sometimes the web browser on the mobile electronic device may emulate the desktop mode, so the android character string does not show up. I could not test with the Google Chrome web browser because it did not seem to work properly. The android character string did show up on the mobile electronic device while using the Firefox web browser and the web Browser web browser made by Litter Penguin.Alley
Now that google cloud print has stopped its support. How do we handle this is android?Schedule
Are you using Google cloud print?I didn't understand this line... new cloudprint.Gadget();Antemeridian
T
4

⚠️ [Deprecated] : Google Cloud Print will no longer be supported as of December 31, 2020. Please see the support article for help migrating.

Use Google Cloud Print (GCP) - there is no app required. The user must have set up a printer via GCP though.

This example uses GCP gadget

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Print</title>
    </head>
    <body>
        <div>
            <p>On android devices (I have tested Nexus 5, Nexus 10, Galaxy S4 and Galaxy Tab 3) the window.print() command in javascript doesn't do anything, as far as I can tell it doesn't even register an error.</p>
            <p>I know for a fact that most if not all of these browsers can print because you can use mobile chromes menu to choose "print".  My questions is, why doesn't window.print() trigger the behavior you would expect (opening the clients print menu).
            And is there an android alternative to window.print()?</p>
        </div>

        <div id="gcpPrint"></div>

        <script src="https://www.google.com/cloudprint/client/cpgadget.js">
        </script>

        <script>
            var gadget = new cloudprint.Gadget();
            gadget.setPrintButton(cloudprint.Gadget.createDefaultPrintButton("gcpPrint"));
            gadget.setPrintDocument("text/html", "Print", document.documentElement.innerHTML);
        </script>
    </body>
</html>
Tat answered 10/11, 2014 at 5:13 Comment(3)
yea i installed google cloud print app, when i click the google cloud print button, the dialog box will open and i choose printer then click the print nothing happen. now what should i do?Jaleesa
gcp is not avaiable by 2021Shawana
Now that google cloud print has stopped its support. How do we handle this is android?Schedule
U
0

I think, direct print() method is disabled on devices by default. I not saw so many phones or other Android devices with printer, however by USB it should be possible of course.

Instead, recommended is saving content/page as pdf and print it via some cloud print service.

Ushaushant answered 2/11, 2014 at 23:1 Comment(2)
Like I said, chrome for android has a "print" option in its menu. This has to be somehow accessible from javascript and as for converting to PDF could you possible elaborate on that.Linebreeding
That's true. But this option is more for cloud print or "print to file" like a pdf or eps where "direct" print can be disabled. Here I found answer #9269340, can be many reasons why it not working in most of browsers on mobile devices, but in fact, it is just not implemented or disabled. Instead you can still print with share options or save as pdf etcUshaushant
R
0

At this moment, window.print() functionality works perfectly on my Android 5.0.1 device with both, Chrome and the default browser.

Rundlet answered 2/11, 2016 at 9:59 Comment(2)
I tried with andriod 7. window.print() does nothing. silently ignored.Cruciferous
Firefox on android still doesn't support it though.Bogtrotter
S
0

Now, window.print() is working on Android devices.

Slant answered 1/1, 2018 at 18:44 Comment(0)
Y
-1
export const printPdf = (() => {
  const isFirefox = /Gecko\/\d/.test(navigator.userAgent);
  const isAndroid = /Android/.test(navigator.userAgent);
  const firefoxDelay = 1000;
  let iframe;

  return function (url) {
    if (iframe) {
      iframe.parentNode.removeChild(iframe);
    }

    iframe = document.createElement("iframe");
    iframe.style.cssText =
      "width: 1px; height: 100px; position: fixed; left: 0; top: 0; opacity: 0; border-width: 0; margin: 0; padding: 0";

    const xhr = new XMLHttpRequest();
    try {
      xhr.responseType = "arraybuffer";
    } catch (e) {
      window.open(url, "_blank");
      return;
    }

    xhr.addEventListener("load", function () {
      if (xhr.status === 200 || xhr.status === 201) {
        const pdfBlob = new Blob([xhr.response], { type: "application/pdf" });
        const iframeUrl = URL.createObjectURL(pdfBlob);
        iframe.src = iframeUrl;

        iframe.addEventListener("load", function () {
          const openPrintPreview = () => {
            try {
              iframe.focus();
              iframe.contentWindow.print();
            } catch (error) {
              console.error("Print preview failed: " + error, error);
            } finally {
              URL.revokeObjectURL(iframeUrl);
            }
          };

          if (isFirefox) {
            window.setTimeout(openPrintPreview, firefoxDelay);
          } else if (isAndroid) {
            const newWindow = window.open("", "_blank");
            if (newWindow) {
              newWindow.document.write(`
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Print PDF</title>
                    <style>
                        /* CSS Reset */
                        * {
                            margin: 0;
                            padding: 0;
                            box-sizing: border-box;
                        }
                
                        html, body {
                            width: 100%;
                            height: 100%;
                            overflow: hidden;
                        }
                
                        #printButton {
                            position: fixed;
                            bottom: 10px;
                            left: 50px;
                            z-index: 9999;
                            padding: 10px;
                            background: #1F51FF;
                            color: #fff;
                            cursor: pointer;
                        }
                
                        #pdfContainer {
                            width: 100%;
                            height: 100%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }
                
                        @media print {
                            #printButton {
                                display: none;
                            }
                
                            html, body, #pdfContainer {
                                margin: 0 !important;
                                padding: 0 !important;
                                width: 100%;
                                height: 100%;
                                overflow: hidden !important;
                            }
                
                            #pdfContainer canvas {
                                width: 100% !important;
                                height: 100% !important;
                            }
                        }
                    </style>
                </head>
                <body>
                <button id="printButton">Print</button>
                <div id="pdfContainer"></div>
                
                <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
                <script>
                    document.getElementById('printButton').addEventListener('click', function() {
                        window.print();
                    });
                
                    // Initialize PDF.js
                    const pdfContainer = document.getElementById('pdfContainer');
                    const loadingTask = pdfjsLib.getDocument("${iframeUrl}"); // Use the blob URL created for the PDF
                    loadingTask.promise.then(function(pdf) {
                        // Fetch the first page
                        pdf.getPage(1).then(function(page) {
                            const scale = 2; // Adjust scale to ensure full-page fit
                            const viewport = page.getViewport({ scale: scale });
                            const canvas = document.createElement('canvas');
                            const context = canvas.getContext('2d');
                            canvas.height = viewport.height;
                            canvas.width = viewport.width;
                            const renderContext = {
                                canvasContext: context,
                                viewport: viewport
                            };
                            page.render(renderContext).promise.then(function() {
                                pdfContainer.innerHTML = '';
                                pdfContainer.appendChild(canvas);
                                // Adjust canvas to fit the container
                                canvas.style.width = '100%';
                                canvas.style.height = '100%';
                            });
                        });
                    });
                </script>
                </body>
                </html>
                `);
              newWindow.document.close();
            } else {
              alert("Please allow popups for this website");
            }
          } else {
            openPrintPreview();
          }
        });

        document.body.appendChild(iframe);
      }
    });

    xhr.open("GET", url, true);
    xhr.send();
  };
})();

This is the complete function code, compatible with both PC and mobile devices, and all browsers.

Yehudit answered 7/6 at 11:1 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Merideth
C
-6

Download adobe acrobat in your phone and you can use windows.print() in mobile.

Cervantes answered 6/2, 2019 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.