Skip to main content

Printing using SpringBoot - cups4j

One of the easiest ways to print something from Java, in this case, using a SpringBoot Java Api Rest is with CUPS.

Let's assume you've set up your CUPS server up and running,

add to your pom.xml file this dependency

    <dependency>
    <groupId>org.cups4j</groupId>
    <artifactId>cups4j</artifactId>
    <version>0.7.6</version>

</dependency>


now at this imports to

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.cups4j.CupsClient;
import org.cups4j.CupsPrinter;
import org.cups4j.PrintJob;
import org.cups4j.PrintJobAttributes;
import org.cups4j.PrintRequestResult;
import org.cups4j.WhichJobsEnum;

add this method to print using CUPS

private static void print(String hostString printerNameString fileName
int copiesString pagesboolean duplex, String attributesthrows Exception {
    FileInputStream fileInputStream = new FileInputStream(fileName);

    CupsPrinter printer = null;
    CupsClient cupsClient = new CupsClient(host, CupsClient.DEFAULT_PORT);
    if (printerName == null) {

      printer = cupsClient.getDefaultPrinter();
    } else {
      printer = new CupsPrinter(new URL("http://" + host + ":" +
CupsClient.DEFAULT_PORT + "/printers/" + printerName),
          printerName, false);
    }

    HashMap<StringStringattributeMap = new HashMap<StringString>();
    if (attributes != null) {
      attributeMap.put("job-attributes"attributes.replace("+""#"));
    }

    PrintJob printJob = new PrintJob.Builder(fileInputStream)
.jobName("testJobName").userName("harald").copies(copies)
        .pageRanges(pages).duplex(duplex).attributes(attributeMap).build();

    PrintRequestResult printRequestResult = printer.print(printJob);
    if (printRequestResult.isSuccessfulResult()) {
      int jobID = printRequestResult.getJobId();

      System.out.println("file sent to " + printer.getPrinterURL() + 
" jobID: " + jobID);
      System.out.println("... current status = " + printer.getJobStatus(jobID));
      Thread.sleep(1000);
      System.out.println("... status after 1 sec. = " + printer.getJobStatus(jobID));

      System.out.println("Get last Printjob");
      PrintJobAttributes job = cupsClient.getJobAttributes(host, jobID);
      System.out.println("ID: " + job.getJobID() + " user: " + 
job.getUserName() + " url: " + job.getJobURL()
          + " status: " + job.getJobState());
    } else {
      // you might throw an exception or try to retry printing the job
      throw new Exception("print error! status code: " + 
printRequestResult.getResultCode() + " status description: "
          + printRequestResult.getResultDescription());

    }

now wherever you are to use it

 try {
      print("192.168.70.45""juandavid""D://zm.txt"1"1"false"");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

in that way I am giving it the hostname or IP address, the printer name as it was given on the CUPS server, and the path of the file I want to print.

to have a better understanding get it from

https://github.com/harwey/cups4j/blob/master/src/main/java/org/cups4j/client/Cups.java

https://github.com/harwey/cups4j

https://github.com/juandavidmarin368/Printing-With-SpringBoot-Cups


How to set up CUPS on Linux Centos

1-
yum install cups
2-
yum install ghostscript.x86_64 hplip-common.x86_64
3- start the service and let it run automatically each time the server gets restarted
service cups start
chkconfig cups on
to manage CUPs via web
vim /etc/cups/cupsd.conf
Allowing what IPS are going to get connected to the server

Allowing the sub local network having access to the GUI

Allowing the IP which will have access as admin, by default it is the same username and root password when it is tried to be accessed via web 

save changes now and restart with service cups restart

let's create a new printer inside the GUI

let's click on Add Printer 

and after that lpd://192.168.70.46/epsonlx_300


Let's click on continue

on that way you've got your printer ready to be used with CUPS, and do not forget SeLINUX

Comments

Popular posts from this blog

How to secure SpringBoot with SSL and Tomcat or Undertow

when we are going to take our applications to production mode, we must have an SSL certificate for the FrontEnd and   BackEnd too, in this case, our backend is a  SpringBoot which is using a tomcat embedded server. Terminology TLS vs SSL TLS is the successor to SSL. It is a protocol that ensures privacy between communicating applications. Unless otherwise stated, in this document consider TLS and SSL as interchangable. Certificate (cert) The public half of a public/private key pair with some additional metadata about who issued it etc. It may be freely given to anyone. Private Key A private key can verify that its corresponding certificate/public key was used to encrypt data. It is never given out publicly. Certificate Authority (CA) A company that issues digital certificates. For SSL/TLS certificates, there are a small number of providers (e.g. Symantec/Versign/Thawte, Comodo, GoDaddy, LetsEncrypt) whose certificates are included by most browsers and Op...

How to deploy a VueJS App using Nginx on Ubuntu

There are thousands of blogs and websites out there explaining how to do a hello world and how to start with VueJS, but in this little post, I’m just going to be explaining how to do deploy a VueJs app after you have run the command through the CLI npm run build . So when you run the command npm run build a dist folder is created and that folder’s got the essential .js files to run our app, when we want to run our app on an Nginx server by default the vue-router is not going to work well so that Nginx does not come ready to work by default with a VueJs app This is basically for a Linux Ubuntu distribution if you’ve got any other Linux distribution just pay attention where is going to be set the www/html folder and the Nginx settings so that this is useful for any Linux distribution  Install and configure nginx sudo apt install nginx Double check to make sure the nginx service is running with command service nginx status, then open your browser and enter ...