DEV Community

AnnaGraz
AnnaGraz

Posted on

How to Print PDF Files in Java?

Printing PDF documents is a key function in our daily life. You can make a tangible duplicate of a PDF file that can be read and used offline by printing the document. This is especially helpful for paperwork that needs to be manually filled out or signed, like contracts, reports, and forms.

You can easily print a PDF file programmatically in Java applications with the help of Spire.PDF.
Spire.PDF for Java is a PDF API that enables Java applications to read, write, save and print PDF documents without using Adobe Acrobat. Using this Java PDF component, developers and programmers can implement rich capabilities to create PDF files from scratch or process existing PDF file. Let us show you how to print PDF files from the following aspects:

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>9.6.2</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Print PDF with the Default Printer Silently

Printing of PDF files can be automated in your java applications. Spire.PDF for Java uses java.awt.print to print the PDF files silently with the default printer.

import com.spire.pdf.PdfDocument;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithDefaultPrinter {

    public static void main(String[] args) {

        //Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Create a PageFormat object and set it to a default size and orientation 
        PageFormat pageFormat = printerJob.defaultPage();

        //Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        //Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        //Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

        //Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Call painter to render the pages in the specified format
        printerJob.setPrintable(pdf, pageFormat);

        //Execute printing
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Print Page Ranges with a Specified Printer

You can print only particular pages of a document rather than the entire file by printing page ranges. The following are the steps to print a page range with a specified printer.

  • Create an instance of PrinterJob class and calls methods in this class to set up a job.
  • Find the available print service using the custom method findPrintService(), and specify the printer name using PrinterJob.setPrintService() method.
  • Create a PdfDocument object, and load a PDF document using PdfDocument.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Create a PrintRequestAttributeSet object, and add the print range to the attribute set.
  • Call PrinterJob.print() method to print the selected pages.
import com.spire.pdf.PdfDocument;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithSpecifiedPrinter {

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

        //Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        //Specify printer name
        PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
        printerJob.setPrintService(myPrintService);

        //Create a PageFormat instance and set it to a default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        //Return a copy of the Paper object associated with this PageFormat.
        Paper paper = pageFormat.getPaper();

        //Set the imageable area of this Paper.
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        //Set the Paper object for this PageFormat.
        pageFormat.setPaper(paper);

        //Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Call painter to render the pages in the specified format
        printerJob.setPrintable(pdf, pageFormat);

        //Create a PrintRequestAttributeSet object
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        //Set print range
        attributeSet.add(new PageRanges(1,7));

        //Execute printing
        try {
            printerJob.print(attributeSet);
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }

    //Find print service
    private static PrintService findPrintService(String printerName) {

        PrintService[] printServices = PrinterJob.lookupPrintServices();
        for (PrintService printService : printServices) {
            if (printService.getName().equals(printerName)) {

                System.out.print(printService.getName());
                return printService;
            }
        }
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Print PDF in Duplex Mode

Printing PDF files in double-sided (also known as duplex) mode. It minimizes printing costs by saving paper. Here are the procedures for using Spire.PDF to print a PDF in duplex mode.

  • Create an instance of PrinterJob class and calls methods in this class to set up a job.
  • Create a PdfDocument object, and load a PDF document using PdfDocument.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Create a PrintRequestAttributeSet object, and add the two-sided printing mode to the attribute set.
  • Call PrinterJob.print() method to print the PDF pages.
  • Spire.PDF for Java.
import com.spire.pdf.PdfDocument;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintInDuplexMode {

    public static void main(String[] args) {

        //Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        //Create a PageFormat object and set it to a default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        //Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        //Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        //Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

        //Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Call painter to render the pages in the specified format
        printerJob.setPrintable(pdf, pageFormat);

        //Create a PrintRequestAttributed object
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        //Set to duplex printing mode
        attributeSet.add(Sides.TWO_SIDED_SHORT_EDGE);

        //Execute printing
        try {
            printerJob.print(attributeSet);
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, it is easy to print the pdf files by using Spire.PDF for java. When printing PDF files, Spire.PDF Java additionally allows you to specify the page size and the number of copies to print.

Related topics:

  1. Java Convert HTML to PDF
  2. Java Extract Text from a PDF Document
  3. Java: Insert Text Watermarks to PDF
  4. Java: Rotate Pages in PDF
  5. Java: Add, Edit, or Delete Bookmarks in PDF

Top comments (0)