Windows

Silent PDF Print with JavaScript and plugin

Today I am going to present you a plugin that I have just created. It is a plugin to print a PDF file silently, that is, without asking the user for confirmation.

This plugin exposes a REST API so that a PDF can be printed without confirmation using JavaScript. Just make an HTTP GET request to the plugin path sending the name of the PDF and the name of the printer.

The best thing about this is that you can use the virtual printers that Windows offers, in this way you can do your tests in an ecological way.

Throughout this post I will show you the documentation of the plugin and all the details of it, including how you can get it.

Using the plugin

The plugin should be running in the background whenever you want to print. You can run it manually or put it in the Windows startup folder to start automatically.

By the way, this plugin to print a PDF silently does not run in a window, it will be hidden. To stop it, go to the task manager.

However, sometimes a pop-up or temporary window is likely to open depending on the actions (for example, if the indicated PDF does not exist).

About PDFToPrinter

In the same location of the plugin, the file called PDFtoPrinter.exe must exist, for this there is no alternative.

This file is not mine, so I can’t distribute it. But it seems to me that you can download it totally free, as I indicate in my post on Printing PDF from the command line.

Printers

Any printer that appears in the Windows control panel is capable of being used by this plugin, just make sure you type the name of them correctly.

In fact, this plugin can print to ink, toner, thermal printers (POS) or even virtual printers.

Filename

For the examples that I am going to put, I will assume that the PDF file is called ticket.pdf. Let’s look at the first case.

If the PDF is in the same location as the plugin

In case the executable plugin and the PDF are in the same directory (folder), you must send only the name of the document to the API. For example, for this case it would be ticket.pdf.

In case the PDF is in another location

If the plugin is in a different directory than the plugin or if you like absolute paths, you can indicate the path without problems. For example, I have ticket.pdf on my desktop so the full path is:

C:\Users\Luis Cabrera Benito\Desktop\ticket.pdf

In this way you can print the PDF regardless of its location, as long as the plugin can access it. By this I mean that the PDF must be on the same computer as the plugin.

API documentation

This plugin creates a web server at localhost:8080 and exposes two routes; one to print a local PDF and one to print a remote PDF.

The root path is where the printing of a PDF document is requested indicating the following parameters in the URL:

  1. impresora: the name of the printer as it appears on the control panel
  2. nombrePdf: the absolute path or name of the PDF document. If it does not exist, a pop-up window will be displayed.

For example, to print a PDF called ticket.pdf on the ZJ58 printer, I would make a GET request to the following URL:

http://localhost:8080/?nombrePdf=ticket.pdf&impresora=ZJ58

And as I indicated earlier, if I wanted to print a PDF that is in another location, I would do it with a GET request like this:

http://localhost:8080/?nombrePdf=C:\Users\Luis%20Cabrera%20Benito\Desktop\ticket.pdf&impresora=ZJ58

Notice that the location of the PDF has spaces but I have replaced them with the entity %20. That can be done with JavaScript in the following function:

const reemplazarEspaciosConEntidad = cadena => cadena.replaceAll(" ", "%20");

Also take into account that the path must have the antidiagonal \ so if you want to indicate the path in the language, you must escape it with itself, that is, like this: \\. You will understand it better in the examples.

By the way, the API will return a 200 response code in case everything goes well. And a 500 code in case there is an error (if there is an error, it will be in the response body).

I want to clarify that even if the API returns a 200 response, if the printer does not exist or there is some internal error, this will not be reported. The most common case is when the printer does not exist; the other cases are under control.

Printing remote PDF from internet by URL

As you have noticed, up to this point I have taught you how to print a local PDF. But you can print a PDF that is on your hosting or on an internet site.

For example, to print a PDF from the internet that is at https://parzibyte.github.io/cv/assets/cv_LuisCabreraBenito.pdf on the Microsoft Print to PDF printer, I would make a GET request to the following URL:

http://localhost:8080/url?impresora=Microsoft%20Print%20to%20PDF&urlPdf=https://parzibyte.github.io/cv/assets/cv_LuisCabreraBenito.pdf

Notice that now the request is made to localhost:8080/url since when it is made to localhost:8080/ it is to print a local PDF. The parameters are impresora indicating the name of the printer and urlPdf indicating the URL of the PDF that is going to be printed.

To give another example, if I wanted to print a PDF that is in localhost/archivos/mi_pdf.pdf on the POS58 printer, I would make a request to the following URL:

http://localhost:8080/url?impresora=POS58&urlPdf=localhost/archivos/mi_pdf.pdf

Important note: it does not matter the site or domain where the PDF is to be printed silently from the cloud.

The only thing that is important is that it is publicly available (that anyone who visits that URL has access to it) since internally the plugin will download it and then print it; all this in a silent way.

Getting the plugin – Download

The plugin is not open source or free; It has a cost of 25 USD. If you want to get it, send me a message.

At the moment it is only compatible with Windows. Obviously the following examples won’t work if you don’t have the plugin, but once you have it running in the background, you can test them.

Examples

I will begin to explain the examples. Remember that you can try them from this link, and see the source code of the repository at this link.

Example 1

Let’s look at the first example. In this case we assume that the PDF file (ticketx.pdf) is in the same directory as the plugin. The code looks like this:

<!--

  ____          _____               _ _           _       
 |  _ \        |  __ \             (_) |         | |      
 | |_) |_   _  | |__) |_ _ _ __ _____| |__  _   _| |_ ___ 
 |  _ <| | | | |  ___/ _` | '__|_  / | '_ \| | | | __/ _ \
 | |_) | |_| | | |  | (_| | |   / /| | |_) | |_| | ||  __/
 |____/ \__, | |_|   \__,_|_|  /___|_|_.__/ \__, |\__\___|
         __/ |                               __/ |        
        |___/                               |___/         
    
____________________________________
/ Si necesitas ayuda, contáctame en \
\ https://parzibyte.me               /
 ------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
Creado por Parzibyte (https://parzibyte.me).
------------------------------------------------------------------------------------------------
Si el código es útil para ti, puedes agradecerme siguiéndome: https://parzibyte.me/blog/sigueme/
Y compartiendo mi blog con tus amigos
También tengo canal de YouTube: https://www.youtube.com/channel/UCroP4BTWjfM0CkGB6AFUoBg?sub_confirmation=1
------------------------------------------------------------------------------------------------
-->
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ejemplo 1 - Imprimir PDF sin confirmación con JavaScript</title>
</head>

<body>
    <h1>Ejemplo 1 - Imprimir PDF sin cuadro de diálogo usando JavaScript</h1>
    <br>
    <a href="//parzibyte.me/blog">By Parzibyte</a>
    <p id="estado"></p>
    <script>
        // Estos parámetros podrían venir de cualquier lugar
        const nombrePdf = "ticketx.pdf";
        const nombreImpresora = "ZJ58";
        const url = `http://localhost:8080/?nombrePdf=${nombrePdf}&impresora=${nombreImpresora}`;
        // Elemento DOM, solo es para depurar
        const $estado = document.querySelector("#estado");
        // Hacer petición...
        fetch(url)
            .then(respuesta => {
                // Si la respuesta es OK, entonces todo fue bien
                if (respuesta.status === 200) {
                    $estado.textContent = "Impreso correctamente (salvo que se haya indicado un error por parte de PDFtoPrinter";
                    console.log("Impresión OK");
                } else {
                    // Si no, decodificamos el mensaje para ver el error
                    respuesta.json()
                        .then(mensaje => {
                            $estado.textContent = "Error imprimiendo: " + mensaje;
                            console.log("Error: " + mensaje);
                        });
                }
            });
    </script>
</body>

</html>

We are making the request on line 50, and handling the response on line 51.

Example 2: user supplied values

If you want the user to be able to indicate the values such as the printer and the name or path of the PDF you can do it, here is an example:

<!--

  ____          _____               _ _           _       
 |  _ \        |  __ \             (_) |         | |      
 | |_) |_   _  | |__) |_ _ _ __ _____| |__  _   _| |_ ___ 
 |  _ <| | | | |  ___/ _` | '__|_  / | '_ \| | | | __/ _ \
 | |_) | |_| | | |  | (_| | |   / /| | |_) | |_| | ||  __/
 |____/ \__, | |_|   \__,_|_|  /___|_|_.__/ \__, |\__\___|
         __/ |                               __/ |        
        |___/                               |___/         
    
____________________________________
/ Si necesitas ayuda, contáctame en \
\ https://parzibyte.me               /
 ------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
Creado por Parzibyte (https://parzibyte.me).
------------------------------------------------------------------------------------------------
Si el código es útil para ti, puedes agradecerme siguiéndome: https://parzibyte.me/blog/sigueme/
Y compartiendo mi blog con tus amigos
También tengo canal de YouTube: https://www.youtube.com/channel/UCroP4BTWjfM0CkGB6AFUoBg?sub_confirmation=1
------------------------------------------------------------------------------------------------
-->
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ejemplo 2 - Imprimir PDF sin confirmación con JavaScript - El usuario indica los valores</title>
</head>

<body>
    <h1>Ejemplo 2 - Imprimir PDF sin cuadro de diálogo usando JavaScript - El usuario indica los valores</h1>
    <br>
    <a href="//parzibyte.me/blog">By Parzibyte</a>
    <br>
    <label for="nombreImpresora">Nombre de la impresora:</label>
    <input type="text" id="nombreImpresora">
    <br>
    <label for="nombrePdf">Nombre del PDF. Si es una ruta absoluta, recuerda escapar las <code>\</code></label>
    <input type="text" id="nombrePdf">
    <br>
    <button id="btnImprimir">Imprimir</button>
    <p id="estado"></p>
    <script>
        // Función ayudante
        const reemplazarEspaciosConEntidad = cadena => cadena.replaceAll(" ", "%20");

        const $nombreImpresora = document.querySelector("#nombreImpresora"),
            $nombrePdf = document.querySelector("#nombrePdf"),
            $btnImprimir = document.querySelector("#btnImprimir"),
            $estado = document.querySelector("#estado");
        // Esperar el clic del botón
        $btnImprimir.addEventListener("click", () => {
            // Tomar los valores de los campos
            const nombrePdf = reemplazarEspaciosConEntidad($nombrePdf.value);
            const nombreImpresora = $nombrePdf.value;
            if (!nombreImpresora || !nombrePdf) {
                return alert("El nombre de la impresora y el nombre del PDF son requeridos");
            }
            const url = `http://localhost:8080/?nombrePdf=${nombrePdf}&impresora=${nombreImpresora}`;
            // Hacer petición...
            $estado.textContent = "Imprimiendo...";
            fetch(url)
                .then(respuesta => {
                    // Si la respuesta es OK, entonces todo fue bien
                    if (respuesta.status === 200) {
                        $estado.textContent = "Impreso correctamente (salvo que se haya indicado un error por parte de PDFtoPrinter";
                        console.log("Impresión OK");
                    } else {
                        // Si no, decodificamos el mensaje para ver el error
                        respuesta.json()
                            .then(mensaje => {
                                $estado.textContent = "Error imprimiendo: " + mensaje;
                                console.log("Error: " + mensaje);
                            });
                    }
                });
        });
    </script>
</body>

</html>

Example 3: absolute path of PDF

If you want to indicate the name of the PDF as the absolute path (in case it is not in the same directory as the plugin) then remember to escape the backslash. Here the example:

<!--

  ____          _____               _ _           _       
 |  _ \        |  __ \             (_) |         | |      
 | |_) |_   _  | |__) |_ _ _ __ _____| |__  _   _| |_ ___ 
 |  _ <| | | | |  ___/ _` | '__|_  / | '_ \| | | | __/ _ \
 | |_) | |_| | | |  | (_| | |   / /| | |_) | |_| | ||  __/
 |____/ \__, | |_|   \__,_|_|  /___|_|_.__/ \__, |\__\___|
         __/ |                               __/ |        
        |___/                               |___/         
    
____________________________________
/ Si necesitas ayuda, contáctame en \
\ https://parzibyte.me               /
 ------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
Creado por Parzibyte (https://parzibyte.me).
------------------------------------------------------------------------------------------------
Si el código es útil para ti, puedes agradecerme siguiéndome: https://parzibyte.me/blog/sigueme/
Y compartiendo mi blog con tus amigos
También tengo canal de YouTube: https://www.youtube.com/channel/UCroP4BTWjfM0CkGB6AFUoBg?sub_confirmation=1
------------------------------------------------------------------------------------------------
-->
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ejemplo 3 - Imprimir PDF sin confirmación con JavaScript - Ruta del PDF es absoluta</title>
</head>

<body>
    <h1>Ejemplo 3 - Imprimir PDF sin cuadro de diálogo usando JavaScript - Ruta del PDF es absoluta</h1>
    <br>
    <a href="//parzibyte.me/blog">By Parzibyte</a>
    <p id="estado"></p>
    <script>
        // Función ayudante
        const reemplazarEspaciosConEntidad = cadena => cadena.replaceAll(" ", "%20");
        // Estos parámetros podrían venir de cualquier lugar
        // Presta atención al escape de la backslash \
        let nombrePdf = "C:\\Users\\Luis Cabrera Benito\\Desktop\\ticket.pdf";
        // Debemos remover los espacios:
        nombrePdf = reemplazarEspaciosConEntidad(nombrePdf);

        const nombreImpresora = "ZJ58";
        const url = `http://localhost:8080/?nombrePdf=${nombrePdf}&impresora=${nombreImpresora}`;
        // Elemento DOM, solo es para depurar
        const $estado = document.querySelector("#estado");
        $estado.textContent = "Imprimiendo...";
        // Hacer petición...
        fetch(url)
            .then(respuesta => {
                // Si la respuesta es OK, entonces todo fue bien
                if (respuesta.status === 200) {
                    $estado.textContent = "Impreso correctamente (salvo que se haya indicado un error por parte de PDFtoPrinter";
                    console.log("Impresión OK");
                } else {
                    // Si no, decodificamos el mensaje para ver el error
                    respuesta.json()
                        .then(mensaje => {
                            $estado.textContent = "Error imprimiendo: " + mensaje;
                            console.log("Error: " + mensaje);
                        });
                }
            });
    </script>
</body>

</html>

The sequence escape I mention is on line 47, please note that since Windows paths are indicated with \, I must escape this character with \\. Also, I am also using the function that replaces spaces, as my path has spaces.

Example 4: PDF from URL

Here I show you an example to print a PDF through its URL:

<!--

  ____          _____               _ _           _       
 |  _ \        |  __ \             (_) |         | |      
 | |_) |_   _  | |__) |_ _ _ __ _____| |__  _   _| |_ ___ 
 |  _ <| | | | |  ___/ _` | '__|_  / | '_ \| | | | __/ _ \
 | |_) | |_| | | |  | (_| | |   / /| | |_) | |_| | ||  __/
 |____/ \__, | |_|   \__,_|_|  /___|_|_.__/ \__, |\__\___|
         __/ |                               __/ |        
        |___/                               |___/         
    
____________________________________
/ Si necesitas ayuda, contáctame en \
\ https://parzibyte.me               /
 ------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
Creado por Parzibyte (https://parzibyte.me).
------------------------------------------------------------------------------------------------
Si el código es útil para ti, puedes agradecerme siguiéndome: https://parzibyte.me/blog/sigueme/
Y compartiendo mi blog con tus amigos
También tengo canal de YouTube: https://www.youtube.com/channel/UCroP4BTWjfM0CkGB6AFUoBg?sub_confirmation=1
------------------------------------------------------------------------------------------------
-->
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ejemplo 4 - Imprimir PDF desde la nube según URL</title>
</head>

<body>
    <h1>Ejemplo 4 - Imprimir PDF desde la nube según URL</h1>
    <br>
    <a href="//parzibyte.me/blog">By Parzibyte</a>
    <p id="estado"></p>
    <script>
        // Estos parámetros podrían venir de cualquier lugar
        const urlPdf = "https://parzibyte.github.io/plugin-silent-pdf-print-examples/ticket.pdf";
        const nombreImpresora = "Microsoft Print to PDF";
        const url = `http://localhost:8080/url?urlPdf=${urlPdf}&impresora=${nombreImpresora}`;
        // Elemento DOM, solo es para depurar
        const $estado = document.querySelector("#estado");
        // Hacer petición...
        $estado.textContent = "Imprimiendo...";
        fetch(url)
            .then(respuesta => {
                // Si la respuesta es OK, entonces todo fue bien
                if (respuesta.status === 200) {
                    $estado.textContent = "Impreso correctamente (salvo que se haya indicado un error por parte de PDFtoPrinter";
                    console.log("Impresión OK");
                } else {
                    // Si no, decodificamos el mensaje para ver el error
                    respuesta.json()
                        .then(mensaje => {
                            $estado.textContent = "Error imprimiendo: " + mensaje;
                            console.log("Error: " + mensaje);
                        });
                }
            });
    </script>
</body>

</html>

Conclusion

In short, just download the PDFtoPrinter.exe file, contact me to get the plugin, put both files in the same directory and run the plugin, either when starting Windows or manually.

With the examples and the API it is more than enough to understand how it works, but I also leave you a video on YouTube:

By the way, I also have another plugin to print to POS thermal printers.


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

parzibyte

Freelancer programmer ready to work with you. Web, mobile and desktop applications. PHP, Java, Go, Python, JavaScript, Kotlin and more :) https://parzibyte.me/

Ver comentarios

Entradas recientes

Receipt designer for thermal printers – Free and open source

In the last months I have been working on a ticket designer to print on…

12 months hace

JavaScript: store and read files with the Origin Private File System

In this post you will learn how to use the Origin Private File System with…

1 year hace

JavaScript: download file with fetch

In this post you will learn how to download a file in the background using…

1 year hace

SQLite3 with vanilla JavaScript and OPFS – Hello world

In this post I will show you how to use SQLite3 directly in the web…

1 year hace

Python Thermal Printing: A Comprehensive Guide for Printing on Thermal Printers

In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…

1 year hace

Image printing on Thermal printer

When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…

1 year hace

Esta web usa cookies.