How to set print setup properties on Existing Document with Apache PDFBox

java, pdfbox

Solution

You should able to do this by by updating the Paper of your PageFormat.

pdDocument.getPageFormat().getPaper().setSize(double width, double length);

the width and length are in inch. A4 size is 8.27 × 11.69 inch.

Problem

I am new to apache PDFBox api and I want to set print setup properties with apache PDFBox. Here I want to set the page size to `A4` and I also want to set Print Scaling option to `NO SCALING`. Make a note here that I have a ready PDF input stream which I am loading. So I want to set there print properties with `org.apache.pdfbox.pdmodel.PDDocument` class before printing. How can I do that ? EDITED : Here is my class to print the PDF file. Note that TODO marker where I want to add code the change PDF page size to A4 and to set page scaling to NO SCALING. ``` public class PrintPDF extends Applet{ private PrintPDF(){ //static class } public static void main(String a[]) throws Exception{ System.out.println("Printing Started..."); String password = ""; String pdfFile = "D://TEST//output.pdf"; boolean silentPrint = true; String printerindx = "1"; PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); if( pdfFile == null ) { usage(); } PDDocument document = null; try { document = PDDocument.load( pdfFile ); //TODO : ADD CODE TO SET PAPER SIZE TO A4 AND //ADD CODE TO SET PAGE SCALING TO : NO SCALING if( document.isEncrypted() ) { document.decrypt( password ); } PrinterJob printJob = PrinterJob.getPrinterJob(); if(printerindx != null ) { PrintService[] printServices = PrinterJob.lookupPrintServices(); for(PrintService printService : printServices){ if(printService.getName().equals("FG_LASER_PRINTER")){ printJob.setPrintService(printService); } } } if( silentPrint ){ document.silentPrint( printJob ); }else{ document.print( printJob ); } } finally{ if( document != null ){ document.close(); } } System.out.println("Printing Completed..."); } /** * This will print the usage requirements and exit. */ private static void usage() { System.err.println( "Usage: java org.apache.pdfbox.PrintPDF [OPTIONS] <PDF file>\n" + " -password <password> Password to decrypt document\n" + " -silentPrint Print without prompting for printer info\n" ); System.exit( 1 ); } } ```

Original source