4 Replies Latest reply: Jan 25, 2011 2:59 AM by faoilean RSS

    Java Printing - Set Page Margin

    faoilean
      Java JRE version 1.6.0_18

      Hi there,

      I'm trying to set the margin of a pdf page that is being sent to my printer. I've tried two methods below and neither seem to work. Is there anything wrong with the code I'm using below to set the margin of my printout?

      The two methods I've tried are setImageableArea and I've also tried to pass PrintRequestAttributeSet to the print job. Is there any other way to set the margin on my printout?

      thanks,
      faoilean.
      URL pdfFile = new URL(pdfURLStr);
      write_message("Printing URL: " + pdfURLStr);
      document = PDDocument.load(pdfFile);
      
      List pages = document.getDocumentCatalog().getAllPages();
      
      if (pages.isEmpty())
      {
         write_message("Pages list is empty");
      } else 
        {
         write_message("Pages list is NOT empty");
         Iterator it = pages.iterator();
      
         while (it.hasNext()) 
         {
             PDPage currentPage = (PDPage) it.next();
             Map map = currentPage.findResources().getFonts();
      
             write_message("Map is: "+map.toString());
             Set mySet = map.keySet();
      
             Iterator setInt = mySet.iterator();
      
             while (setInt.hasNext()) 
             {
      
                 String val = (String)setInt.next();
      
                 PDType1Font pdt = (PDType1Font)map.get(val);
                 write_message("'"+val+""+pdt.getFontDescriptor().getFontName()+"'");
      
                 PDFont currFont = this.loadFontByName(document,pdt.getFontDescriptor().getFontName(),val);
      
                 if(currFont != null)
                 {
                       currentPage.findResources().getFonts().put(val,currFont);
                 }
              }
         }
      }
      
      
      PrinterJob printJob = PrinterJob.getPrinterJob();
      printJob.setPrintService(currentPrintService);
      
      PageFormat pForm = new PageFormat();
      Paper paper = new Paper();
      paper.setSize(594.936, 841.536);
      
      double margin = 36; // half inch
      paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight()  - margin * 2);
      pForm.setPaper(paper);
      
      Book book = new Book();
      book.append(document.getPrintable(0), pForm, (int)document.getDocumentCatalog().getPages().getCount());
      printJob.setPageable(book);
      
      PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
      float xmargin = 0.5f;
      float ymargin = 0.5f;
      float w = 595;
      float h = 842;
      attributes.add(new MediaPrintableArea(xmargin, ymargin, w - 2*xmargin, h - 2*ymargin, MediaPrintableArea.INCH));
      
      printJob.print(attributes);
      
      document.close();