Direct PDF Printing on the Printer in Java

3

So, I need to print a PDF directly to the printer, because I need to print invoices. If I use this form Desktop d = Desktop.getDesktop().print("Caminho do arquivo") it prints normally the first time, but opens the adobe together and the adobe closes the document and from there when I print again, it "buga" and prints everything that is in the extremely small PDF. And the idea is to print directly and in the size of the paper.

I have these 3 printers: Bematech MP 4200 TH, Bematech MP 4000 TH e MP2500TH. Below is how I learned to print directly from the printer.

PrintService iPadrao = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor docFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;

try {
    FileInputStream stream = new FileInputStream("C:\Users\EX-PHP\Documents\TestePDF2\vai.pdf");

    Doc doc = new SimpleDoc(stream, docFlavor, null);
    DocPrintJob p = iPadrao.createPrintJob();
    p.print(doc, null);
} catch (PrintException e) {
    e.printStackTrace();
}

The PDF in question contains an invoice containing a QR code. Also I tried with PDFRenderer, and with some codes that I found on the internet but without success, it could be some error in the codes or something that is missing.

    
asked by anonymous 19.09.2017 / 21:02

1 answer

2

An option to work with PDF is to use the Apache PDFBox library that will extract the contents of your file and allow is printed:

public static void main(String args[]) throws Exception {

  PDDocument documento = PDDocument.load(new File("C:/Users/EX-PHP/Documents/TestePDF2/vai.pdf"));
  PrintService servico = PrintServiceLookup.lookupDefaultPrintService();

  PrinterJob job = PrinterJob.getPrinterJob();
  job.setPageable(new PDFPageable(documento));
  job.setPrintService(servico);
  job.print();
  documento.close();
}

Dependencies for use of Apache PDFBox can be found in the Dependencies section of the site. For this example, Apache Commons Logging and fontbox .

If you are using Maven use the following dependency import:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.7</version>
</dependency>

Answer to similar question in Stack Overflow : Print a PDF file using PrinterJob in Java .

    
21.09.2017 / 16:44