Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

Java Printing page size problem

1 min read

Java PDF printing

Java has a very flexible printing system called JPS which makes printing very easy. Any JComponent can be made to print its contents by adding a print method

public int print(Graphics graphics, PageFormat pf, int page) throws PrinterException {}

When Java needs to print, it calls this method and whatever you paint onto the graphics object will be printed. The graphics object is an ‘abstract’ concept which is then scaled down to fit the printed page by Java.The page size is set and Java prints it all for you. Here is some example code
Paper paper = new Paper(); //Create default Page format A4

//use this command to alter area in which it prints
//paper.setImageableArea(a,b,c,d);

pf.setPaper(paper);

MyJComponent decode_pdf=new MyJComponent(); //has print method

//debug code discussed below

//decode_pdf.showImageableArea();
printJob.setPrintable(decode_pdf,pf);

//Print  document
printJob.print(attributeSet); //attributeSet can be null or specific Print values

The printer page defines a page size to match the printer page, with an imageable area (some printers have a non-printable strip around a page which cannot be printed onto). It is very flexible and allows you to add alsorts of features. Learn more about some ideas of what is possible.

We have setup some sample values for different page sizes (A4, A5, A4 (Borderless) in a Java class PaperSizes.java

Unfortunately,  Java does not let you read what are appropriate values, and it lets you define values which do not work – you can give Java values which result in things being printed off the page or in the non-printable area without any errors being generated.

The workaround we have adopted is to draw a box with a diagonal line so we can choose the correct settings through trial and error with a method to enable debugging (showImageableArea()). It is not perfect but provides a workaround. If you have also come across this problem, we hopes this helps (and if you have a better solution please let us know!).



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

4 Replies to “Java Printing page size problem”

  1. Hi

    Thanks
    Tried the below code, but the printout ( re direction to XPS ) shrinks in size horizontally. How to set page size ( 3.14 by 50 inch SLEEK size ) using PrintRequestAttributeSet?

    If I use decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_FIT_TO_PRINTER_MARGINS); top portions of printouts got cut ) lost images/texts )

    //attributeSet.add(MediaSize.getMediaSizeForName(MediaSizeName.ISO_A4) ); is giving error

    Below is the code I used.
    ———————————-

    private static void printUsingJPedal() {
    //True won’t render it to screen
    PdfDecoder decodePdf = new PdfDecoder(true);

    try {
    decodePdf.openPdfFile(“FontTest.pdf”);
    FontMappings.setFontReplacements();
    } catch (Exception e) {
    //…
    }

    //Print Attributes
    PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
    JobName jobName = new JobName(“Example Print”, null);
    attributeSet.add(jobName);

    //Adjusting print outputs
    try {
    decodePdf.setPrintAutoRotateAndCenter(true);
    //decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_FIT_TO_PRINTER_MARGINS);
    decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_NONE);
    decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_REDUCE_TO_PRINTER_MARGINS);
    decodePdf.setPagePrintRange(1, decodePdf.getPageCount());
    } catch (PdfException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    //attributeSet.add(MediaSize.getMediaSizeForName(MediaSizeName.ISO_A4) );
    //Choosing Default Printer
    PrintService defaultPrintService = PrinterJob.getPrinterJob().getPrintService();

    //Create Printable Object
    PdfBook pdfBook = new PdfBook(decodePdf, defaultPrintService, attributeSet);
    SimpleDoc doc = new SimpleDoc(pdfBook, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);

    DocPrintJob printJob = defaultPrintService.createPrintJob();

    try {
    printJob.print(doc, attributeSet);
    } catch (PrintException e) {
    //
    }
    }

  2. Good questions and I will try to give a quick summary here. I usually like to answer questions like these on the support forum so other who may encounter similar problems can easily find the answers.

    To use a given paper size you will need to set the following flag.

    pdfBook.setUseExactPdfPageSize(true);

    On physical printers this may or may not work depending on what physical paper you actually have access to.
    There is also a method that will set the closest paper size two hat used in the pdf that the printer has support for.

    pdfBook.setChooseSourceByPdfPageSize(true);

    You should only use one of these two options.

    Also whilst I was running the code I was unable to reproduce the issue with missing content at the top of the page.

    Can you try my suggestions for correcting the paper size. If you have further questions please feel free to post them on our support forum.

    https://support.idrsolutions.com/forums/forum/java-pdf-library-support-forum/

    1. Thanks Kieran

      I tried pdfBook.setUseExactPdfPageSize(true) ;, it works, it neighther shrinks nor cut off top portions of the page. Used correct size.
      Looks this is better than what I used earlier, given below

      Earlier I tried this
      decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_NONE); // This avoided shrinking, but assumed A4 size and cut off top portion.

      Then I used both below decodePdf.setPrintPageScalingMode() & decodePdf.setPageFormat(), then it was fine.
      decodePdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_NONE); //This avoided shrinking
      decodePdf.setPageFormat(getPageFormat(“LEGAL LONG”)) ; //This set the corret size ( my page size was (3.14 by 50 ) and was not chopping off top portion.

      private static PageFormat getPageFormat(String receiptType) {
      PageFormat pageFormat = new PageFormat();
      pageFormat.setOrientation(PageFormat.PORTRAIT);
      Paper paper= pageFormat.getPaper();

      // default to A4 (8.3 * 11.7 inches)
      double paperWidth = 8.3;
      double paperHeight = 11.7;

      if (“SLEEK”.equalsIgnoreCase(receiptType)) {
      paperWidth = 3.14;
      paperHeight = 50;
      } else if (“LETTER”.equalsIgnoreCase(receiptType)) {
      paperWidth = 8.5;
      paperHeight = 11;
      } else if (“LEGAL”.equalsIgnoreCase(receiptType)) {
      paperWidth = 8.5;
      paperHeight = 14;
      }
      else if (“LEGAL LONG”.equalsIgnoreCase(receiptType)) {
      paperWidth = 3.14;
      paperHeight = 50;

      }
      else
      {

      paperWidth = 8.3;
      paperHeight = 11.7;

      }

      paper.setSize(paperWidth * 72.0, paperHeight * 72.0);
      paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
      pageFormat.setPaper(paper);
      return pageFormat;
      }

      Another thing, I observed was, If bigger size, than needed is used in decodePdf.setPageFormat(getPageFormat()
      ), then geeting full page without chopping off, but it takes longer time.

      So using the exact size and only as much size as required like pdfBook.setUseExactPdfPageSize(true) will give better performance.

      Regards
      Sridha. S

  3. Different printers work in different ways which means that different approaches / settings can give different performance. It appears you have found the best approach for your printer now.

    If you have any other questions please feel free to post them on our support Forums.

Comments are closed.