Print to pdf in java

Java: Print PDF Documents

The java.awt.print package provides classes and interfaces for a general printing API. It has the ability to specify the document types and manage the print options, 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 in Java using this package and Spire.PDF for Java library.

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.

  com.e-iceblue e-iceblue https://repo.e-iceblue.com/nexus/content/groups/public/    e-iceblue spire.pdf 9.7.0   

The following are the steps to print PDF documents with the default printer using java.awt.print and Spire.PDF for Java.

  • 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.
  • Call PrinterJob.print() method to print the PDF pages.
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(); >> >

The following are the steps to print a page range with a specified printer using java.awt.print and Spire.PDF for Java.

  • 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; > >

The following are the steps to print PDF documents with print dialog using java.awt.print and Spire.PDF for Java.

  • 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.
  • Call PrinterJob.printDialog() method to display print dialog.
  • Call PrinterJob.print() method to print the PDF pages.
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 PrintWithPrintDialog < 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); //Display the print dialog if (printerJob.printDialog()) < try < printerJob.print(); >catch (PrinterException e) < e.printStackTrace(); >> > >

The following are the steps to print PDF documents in duplex mode using java.awt.print and Spire.PDF for Java.

  • 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.
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(); >> >

The following are the steps to print PDF documents in a custom paper size using java.awt.print and Spire.PDF for Java.

  • Create an instance of PrinterJob class and calls methods in this class to set up a job.
  • Set the with and height of the Paper object using Paper.setSize() 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.
  • Call PrinterJob.print() method to print the PDF pages.
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 PrintInCustomPaperSize < 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 width and height of this Paper object paper.setSize(500,600); //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(); >> >

Apply for a Temporary License

If you’d like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Читайте также:  Java create error log file

See Also

Источник

How To Print PDF Files Using Java

PDF is important in Java applications because it allows developers to create and manipulate PDF documents in a platform-independent manner. The PDF format is widely used for storing and sharing documents, so being able to work with it is important for many Java applications that deal with document management or document-based workflows.

There are several ways to generate and print PDF files in Java. A common approach is to use a library that provides classes for creating and manipulating PDF documents. This How-to Guide will show how to use the IronPDF library to generate and print PDF files in Java applications.

How to Print PDF Files in Java

  1. Install Java library to print PDF files
  2. Utilize PdfDocument class to load existing PDF file
  3. Use printWithoutDialog method to print immediately with default printer
  4. Change printer settings to get customized output in Java
  5. Print PDF after configuration with print method

IronPDF: Java PDF Library

IronPDF is a Java library that can be used to generate, manipulate, and convert PDF documents. It is based on the IronPDf C# .NET library, which provides a similar set of features for the .NET platform.

IronPDF provides a high-level API for working with PDF documents, allowing developers to work with PDF files without having to deal with the low-level details of the file type. It supports common PDF operations such as creating new documents, adding content, formatting text, and merging PDF files, and splitting PDF files.

IronPDF provides support for converting HTML, CSS, and JavaScript code to PDF, making it easy to generate PDF files from web pages or HTML templates. It also offers the option to print PDF documents.

Steps to Print a PDF Document Using IronPDF Java

Prerequisites

To print PDF files in Java, there are some prerequisites:

  1. Eclipse IDE or any other Java IDE
  2. A Maven Project running in Eclipse or in any other IDE
  3. A stable internet connection to install the IronPDF Java library

Install IronPDF Library in Maven Project

To install IronPDF in a Maven project, you need to add the IronPDF dependency to your project’s pom.xml file.

Add the following dependencies to the section of the pom.xml file:

 
com.ironsoftware
com.ironsoftware
2023.7.2

After adding the dependencies to the pom.xml file, run the mvn install command in the terminal, or press Ctrl+S to download and install IronPDF in your Maven project.

Before we can start using IronPDF, must first import the IronPDF classes in the main App.java source file, as found in the src folder.

Java Print PDFs - Figure 1: Package explorer tree for ironpdf-java

Package Explorer Tree for IronPDF for Java

Open the «App.java» file and add the IronPDF package by using the following code.

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.*;

Load a PDF in a Java Application

IronPDF for Java provides a constructor for loading PDF content into the library. Valid arguments that this constructor can accept include a byte array and a file path. For password-protected documents, a third parameter containing the password for the PDF file also be provided.

The code snippet below loads a PDF located on the filesystem.

License.setLicenseKey("Enter-Your-License"); PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf"));
License.setLicenseKey("Enter-Your-License"); PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf"));

IronPDF provides two ways to print PDF files. The first way is to print the document immediately using default printer and page settings. You can use the printWithoutDialog method to perform this action.

The Print Dialog

The second way is to allow the user to specify printing options prior to printing. You can achieve this functionality using the print method.

The print dialog window will appear when the this method is invoked, allowing the user to change the printer, set paper size, change the number of copies, etc.

Java Print PDFs - Figure 2: Print dialog shown after running the program using print()

Print dialog shown after running the program using the print() method

Full Source Code

The complete source file used in this How-To Guide is below.

package IronPDF.ironpdf_java; //Import statement for IronPDF Java import com.ironsoftware.ironpdf.*; import java.awt.print.PrinterException; import java.io.IOException; import java.nio.file.Paths; public class App < public static void main( String[] args ) throws PrinterException,IOException < // Apply your license key License.setLicenseKey("Enter-Your-License"); PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf")); pdf.printWithoutDialog(); pdf.print(); >>
package IronPDF.ironpdf_java; //Import statement for IronPDF Java import com.ironsoftware.ironpdf.*; import java.awt.print.PrinterException; import java.io.IOException; import java.nio.file.Paths; public class App < public static void main( String[] args ) throws PrinterException,IOException < // Apply your license key License.setLicenseKey("Enter-Your-License"); PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf")); pdf.printWithoutDialog(); pdf.print(); >>

Learn more about PDF Printing in Java using the IronPDF library by clicking this link.

Summary

In conclusion, IronPDF is a powerful and easy-to-use library for printing PDFs in Java applications. With its rich set of features and extensive documentation, IronPDF makes it simple to generate and customize professional-quality PDFs that can be printed or shared with others. Whether you need to create invoices, reports, or any other type of document, IronPDF has you covered.

IronPDF offers a 30 day free trial for testing in production. Pricing of IronPDF starts from $749. Give IronPDF a try and see how it can help you streamline your PDF printing workflow.

You can download the software product from this link.

View the IronPDF YouTube Playlist

Источник

Оцените статью