DEV Community

Alexis
Alexis

Posted on

Java Print PDF Files

Printing PDF documents is one of the most common tasks in our daily lives. You can easily print a PDF file programmatically for many different scenarios using Java language. Spire.PDF has a powerful function to print PDF document, such as specifying printer name, setting print range, printing in duplex, and printing in custom paper sizes. In this article, you will learn how to print PDF documents from the following four parts.

Install Spire.PDF for Java

First, 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>5.5.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Print PDF with a Print Dialog

Spire.PDF for java uses java.awt.print package to print the PDF files programmatically. You could also customize some print settings, such as removing the default print margins, setting the number of copies, etc.

  • Create a PdfDocument object, and load a PDF document using PdfDocument.LoadFromFile() method.
  • Create an instance of PrinterJob class, and calls methods in this class to set up a print job.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Call PrinterJob.setCopies(int) to set the print copies.
  • Call PrinterJob.print() method to print the PDF pages with print dialog.
import com.spire.pdf.*;

import java.awt.print.*;

       public class PrintPDF {
           public static void main(String[] args) throws Exception {
               //Create a PdfDocument object
               PdfDocument pdf = new PdfDocument();
               //Load a PDF file
               pdf.loadFromFile("Sample.pdf");

               //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);

               //Set the copies
               printerJob.setCopies(3);

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

               //Display the print dialog
               if (printerJob.printDialog()) {
                   try {
                       printerJob.print();
                   } catch (PrinterException e) {
                       e.printStackTrace();
                   }
               }
           }
       }
Enter fullscreen mode Exit fullscreen mode

Print PDF in a Custom Paper Size

The following are the steps to print PDF documents with the custom page size.

  • Load the sample PDF file.
  • Create an instance of PrinterJob class, and calls methods in this class to set up a print job.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Set the with and height of the Paper object using Paper.setSize() method.
  • Call PrinterJob.print() method to print the PDF pages without print dialog.
import com.spire.pdf.*;
import java.awt.print.*;

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

               //Create a PdfDocument object
               PdfDocument pdf = new PdfDocument();
               //Load a PDF file
               pdf.loadFromFile("Sample.pdf");

               //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 width and height of this Paper object
               paper.setSize(500,600);

               //Print the document without the print dialog
                   try {
                       printerJob.print();
                   } catch (PrinterException e) {
                       e.printStackTrace();
                   }
               }
           }

Enter fullscreen mode Exit fullscreen mode

Print PDF in Duplex Mode

The following are the steps to print PDF documents in duplex mode.

  • Load the sample PDF file.
  • Create an instance of PrinterJob class, and calls methods in this class to set up a print job.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Create a PrintRequestAttributeSet object, and using add(Sides.TWO_SIDED_SHORT_EDGE) method to the attribute set to duplex print the PDF.
  • Call PrinterJob.print() method to print the PDF pages without print dialog.
import com.spire.pdf.*;

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 duplexPrint {
           public static void main(String[] args) throws Exception {
               //Create a PdfDocument object
               PdfDocument pdf = new PdfDocument();
               //Load a PDF file
               pdf.loadFromFile("Sample.pdf");

               //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();

               //Remove the default printing margins
               paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
               pageFormat.setPaper(paper);
               printerJob.setPrintable(pdf, pageFormat);

               //Duplex print
               PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
               //Two sides short edge
               aset.add(Sides.TWO_SIDED_SHORT_EDGE);

               try {
                   printerJob.print(aset);
               } catch (PrinterException e) {
                   e.printStackTrace();
               }
           }

       }
Enter fullscreen mode Exit fullscreen mode

Print Page Ranges with a Specified Printer

The following are the steps to print PDF documents with a specified Printer and choose a range of PDF pages to print.

  • Load the sample PDF file.
  • Create an instance of PrinterJob class, and calls methods in this class to set up a print job.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Find the available print service using the custom method findPrintService(), and specify the printer name using PrinterJob.setPrintService() method.
  • Create a PrintRequestAttributeSet object, and add the print range to the attribute set.
  • Call PrinterJob.print() method to print the PDF pages without print dialog.
import com.spire.pdf.*;

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 setPrinter {
           public static void main(String[] args) throws Exception {
               //Create a PdfDocument object
               PdfDocument pdf = new PdfDocument();
               //Load a PDF file
               pdf.loadFromFile("Test.pdf");

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

               //Specify printer name
               PrintService myPrintService = findPrintService("HP ColorLaserJet MFP M278-M281 PCL-6");
               printerJob.setPrintService(myPrintService);

               //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();

               //Remove the default printing margins
               paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
               pageFormat.setPaper(paper);
               printerJob.setPrintable(pdf, pageFormat);

               //Set print range
               PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
               aset.add(new PageRanges(1,2));

               try {
                   printerJob.print(aset);
               } 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

Conclusion

In this article, you have learned how to print the PDF files with the help of Spire.PDF for Java. If you have any other questions, please feel free to check the Free PDF forums.

Top comments (0)