简体   繁体   中英

How can I set default margins for my page in java

I have to print a page in a 80mm * 297 mm paper. I'm using the following code:

 public static void printCard(final String bill ){



Printable contentToPrint = new Printable(){
   @Override
   public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws     PrinterException {


       Graphics2D g2d = (Graphics2D) graphics;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    pageFormat.setOrientation(PageFormat.PORTRAIT);
    Paper pPaper = pageFormat.getPaper();
     pPaper.setImageableArea(1.0, 1.0, pPaper.getWidth() , pPaper.getHeight() -2);
     pageFormat.setPaper(pPaper);

       if (pageIndex >0){return NO_SUCH_PAGE;} //Only one page

      String Bill [] = bill.split(";");

      int y = 0;
    for (int i = 0; i < Bill.length; i++) {

        g2d.drawString(Bill[i], 0, y);
        y = y + 15;
    }

    return PAGE_EXISTS;

   }


};  
  PrinterJob job = PrinterJob.getPrinterJob();
  job.setPrintable(contentToPrint);
    boolean dojob = job.printDialog();
  //You can show a print dialog before printing by job by wrapping the following blocks     with a conditional statement if(job.printDialog()){...}


try {
    job.print();
} catch (PrinterException e) {
    System.err.println(e.getMessage());
}

}

The code is working fine but the only problem is that one has to set margins every time to use this code. The preset margins are 20mm from top, 21 mm from left and 18 mm from bottom. So the text doesn't fit on the small page. How can I set custom margins from my code? or can I set default printer settings so that I don't need to set the margins everytime?

I can't see anything specifically wrong in your code but worth a look at setImageableWidth and setImageableHeight in the java.awt.print.PageFormat class.

If you have tried this ( I assume you have) and find that it didn't work then don't assume that you are going mad, I have found specific printers which simply don't appear to accept the java print api.

At work our Xerox MFDs blithely ignore print commands or formatting from the print api. For a solution to printing to a specific user account we had to save and then alter certain bytes in the pcl file before passing it to the printer. Not a nice solution but it appeared to be the only way...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM