Java awt print pdf

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.8   

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.

Читайте также:  Sign Up

See Also

Источник

Coding With File Formats

Like Word, Excel, PowerPoint, PDF, BarCode, HTML, Outlook, etc

Java – How to Print PDF Document

Printing PDF documents is a very common task in our work. In this post, I am going to share with you three code snippets of printing PDF documents in Java. They’re:

  • Print PDF with default printer without print dialog
  • Print PDF with the specified printer
  • Print PDF by invoking print dialog

Before start, download Download Spire.PDF for Java and add Spire.Pdf.jar as a dependency in your project.

import javax.print.PrintService; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class PrintPDF < public static void main(String[] args) throws PrinterException < //create and return a PrinterJob which is initially associated with the default printer PrinterJob printerJob = PrinterJob.getPrinterJob(); //create a new PageFormat instance and sets 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); //load a PDF document PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Invoice.pdf"); //call painter to render the pages in the specified format printerJob.setPrintable(pdf, pageFormat); //execute print try < printerJob.print(); >catch (PrinterException e) < e.printStackTrace(); >> >
import javax.print.PrintService; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class PrintPDF < public static void main(String[] args) throws PrinterException < //create and return a PrinterJob 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 new PageFormat instance and sets 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); //load a PDF document PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Invoice.pdf"); //call painter to render the pages in the specified format printerJob.setPrintable(pdf, pageFormat); //execute print try < printerJob.print(); >catch (PrinterException e) < e.printStackTrace(); >> 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; > >
import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class PrintPDF < public static void main(String[] args) throws PrinterException < //create and return a PrinterJob which is initially associated with the default printer PrinterJob printerJob = PrinterJob.getPrinterJob(); //create a new PageFormat instance and sets 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); //load a PDF document PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Quote - SHI.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(); >> > >

Источник

Читайте также:  Дэн бейдер чистый python pdf

and also from other different ways there on the internet, but with all the ways I’ve tried, when I print the document, print odd numbers and letters, like this:

3 Answers 3

I think PDFBox from Apache better suit your need (http://pdfbox.apache.org/).

Here is how it can fit inside your code:

static public void main(String[] args) < PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pf = job.defaultPage(); Paper paper = new Paper(); paper.setSize(612.0, 832.0); double margin = 10; paper.setImageableArea(margin, margin, paper.getWidth() - margin, paper.getHeight() - margin); pf.setPaper(paper); pf.setOrientation(PageFormat.LANDSCAPE); // PDFBox PDDocument document = PDDocument.load("yourfile.pdf"); job.setPageable(new PDPageable(document, job)); job.setJobName("funciona?"); try < job.print(); >catch (PrinterException e) < System.out.println(e); >> 

You can find more info about this if you look at the source of org.apache.pdfbox.PrintPDF.

Hello, I did what you told me. Download the PDFBOx.jar and copy your code . Even so the printer will not print what should be printed. The file I have is «test.pdf» is a sheet containing some text and an image. But what is printed on the sheet are just numbers like it is printing in hexadecimal

The best option is to use iTEXT

We have tried PDFBox too, also PDFView and IText, but what worked best for us was using the systems ghostscript to render the PDF into an image — otherwise in our PDF with a couple of images and form fields, things would get rendered not perfectly.

First write your pdf to an temporary file, then call gs:

 String command; if (System.getProperty("os.name").toLowerCase().contains("windows")) < command = "gswin32"; >else < command = "gs"; >String absolutePath = pngFile.getAbsolutePath(); command = command + " -q -dSAFER -dBATCH -dNOPAUSE -sDEVICE=" + color.name() + " -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -dFirstPage=" + pageNo + " -dLastPage=" + pageNo + " -r" + dpi + " -sOutputFile=" + absolutePath + " " + pdfFile.getAbsolutePath(); System.out.println(command); Process p = Runtime.getRuntime().exec(command); boolean success = false; for (int i = 0; i < 1200; i++) //wait for completion < try < p.exitValue(); success = true; break; >catch (Exception e) < logger.trace(e.getMessage()); >Thread.currentThread(); Thread.sleep(200); > if (!success)

Источник

Читайте также:  Java convert binary to hex

I use document.silentPrint(job); and job.print(printRequestAttributeSet); — it works fine. If I use document.silentPrint(job); — I can’t set the PrintRequestAttributeSet . Can anyone tell me how to set the PrintRequestAttributeSet?

6 Answers 6

My Printer did not support native PDF printing.

I used the open source library Apache PDFBox https://pdfbox.apache.org to print the PDF. The printing itself is still handeled by the PrinterJob of Java.

import java.awt.print.PrinterJob; import java.io.File; import javax.print.PrintService; import javax.print.PrintServiceLookup; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.printing.PDFPageable; public class PrintingExample < public static void main(String args[]) throws Exception < PDDocument document = PDDocument.load(new File("C:/temp/example.pdf")); PrintService myPrintService = findPrintService("My Windows printer Name"); PrinterJob job = PrinterJob.getPrinterJob(); job.setPageable(new PDFPageable(document)); job.setPrintService(myPrintService); job.print(); >private static PrintService findPrintService(String printerName) < PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null); for (PrintService printService : printServices) < if (printService.getName().trim().equals(printerName)) < return printService; >> return null; > > 

This worked for me to print a PDF with a plain JRE:

public static void main(String[] args) throws PrintException, IOException < DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE; PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet(); patts.add(Sides.DUPLEX); PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts); if (ps.length == 0) < throw new IllegalStateException("No Printer found"); >System.out.println("Available printers: " + Arrays.asList(ps)); PrintService myService = null; for (PrintService printService : ps) < if (printService.getName().equals("Your printer name")) < myService = printService; break; >> if (myService == null) < throw new IllegalStateException("Printer not found"); >FileInputStream fis = new FileInputStream("C:/Users/John Doe/Desktop/SamplePDF.pdf"); Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null); DocPrintJob printJob = myService.createPrintJob(); printJob.print(pdfDoc, new HashPrintRequestAttributeSet()); fis.close(); > 

Источник

Как распечатать PDF-документ на Java

java печатает PDF-документ. С тегами print, java, pdf.

Шпиль.PDF имеет мощную функцию для печати PDF-документа. В этой статье показано, как распечатать PDF-файл в приложениях Java с помощью следующих методов печати:

  • Печать PDF на принтере по умолчанию
  • Печать PDF-документа с помощью диалогового окна печати
  • Печать PDF-документа с настраиваемым размером страницы
  • Выберите несколько страниц в файле PDF для печати

Распечатайте PDF-документ на принтере по умолчанию без отображения диалогового окна печати, мы также можем настроить некоторые параметры печати, такие как удаление полей печати по умолчанию, установка количества копий и т.д.

import com.spire.pdf.*; import java.awt.print.*; public class PrintPdfDocument < public static void main(String[] args) < //load the sample document String inputFile = "Sample.pdf"; PdfDocument loDoc = new PdfDocument(inputFile); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //Remove the default printing margins loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); //Set the number of copies loPrinterJob.setCopies(1); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(loDoc,loPageFormat); try < loPrinterJob.print(); >catch (PrinterException e) < e.printStackTrace(); >> >

Печать PDF-документа с помощью диалогового окна печати

import com.spire.pdf.*; import java.awt.print.*; public class PrintPdfWithDialog < public static void main(String[] args) < //load the sample document String inputFile = "Sample.pdf"; PdfDocument loDoc = new PdfDocument(inputFile); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //Remove the default printing margins loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(loDoc,loPageFormat); //display the print dialog if (loPrinterJob.printDialog()) < try < loPrinterJob.print(); >catch (PrinterException e) < e.printStackTrace(); >> > >

Печать PDF-документа с настраиваемым размером страницы. Мы можем использовать lo Paper.setSize(500 600), чтобы задать размер страницы при печати PDF.

import com.spire.pdf.*; import java.awt.print.*; public class printWithCustomizedPageSize < public static void main(String[] args) < //load the sample document String inputFile = "Sample.pdf"; PdfDocument loDoc = new PdfDocument(inputFile); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //Set page size loPaper.setSize(500,600); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(loDoc,loPageFormat); //Print try < loPrinterJob.print(); >catch (PrinterException e) < e.printStackTrace(); >> >

Выберите страницы, которые мы хотим распечатать, установив диапазон печати. Мы также могли бы настроить печать одной или обеих сторон с помощью объекта PrintRequestAttributeSet.

import com.spire.pdf.*; import javax.print.attribute.*; import javax.print.attribute.standard.*; import java.awt.print.*; public class setPrintRange < public static void main(String[] args) < //load the sample document String inputFile = "Sample.pdf"; PdfDocument loDoc = new PdfDocument(inputFile); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //Remove the default printing margins loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(loDoc, loPageFormat); //Set print range PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); aset.add(new PageRanges(6,7)); //duplex Print aset.add(Sides.TWO_SIDED_SHORT_EDGE); try < loPrinterJob.print(aset); >catch (PrinterException e) < e.printStackTrace(); >> >

Источник

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