Java Printing Font Stretch

杀马特。学长 韩版系。学妹 提交于 2019-12-05 15:22:42

The default DPI is normal 72 DPI (I believe), which, on printed paper, is pretty terrible. You need to prompt the print API to try and find a printer with a better DPI.

Basically you need to use the print services API.

Try something like...

public class PrintTest01 {

  public static void main(String[] args) {

    PrinterResolution pr = new PrinterResolution(300, 300, PrinterResolution.DPI);

    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.ISO_A4);
    aset.add(pr);
    aset.add(OrientationRequested.PORTRAIT);

    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setPrintable(new Page());
    try {
      pj.print(aset);
    } catch (PrinterException ex) {
      ex.printStackTrace();
    }

  }

  public static class Page implements Printable {

    @Override
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
      if (pageIndex > 0) {
        return NO_SUCH_PAGE;
      }

      Graphics2D g2d = (Graphics2D) g;
      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

      g.setFont(new Font("Arial", Font.PLAIN, 128));
      FontMetrics fm = g.getFontMetrics();
      int x = (int)(pageFormat.getWidth() - fm.stringWidth("A")) / 2;
      int y = (int)((pageFormat.getHeight() - fm.getHeight()) / 2) + fm.getAscent();

      g2d.drawString("A", x, y);

      return PAGE_EXISTS;
    }
  }
}

You might find Working with Print Services and Attributes of some help...

I should warn you, this is going to print to the first print that it can find that meets the PrintRequestAttributeSet. You could also add in the print dialog to see what's it doing, but that's another level of complexity I can live without right now ;)

The above worked! To open a print dialog with it, use this:

    PrinterJob job = PrinterJob.getPrinterJob();
    TextDocumentPrinter document = new TextDocumentPrinter();

    PrinterResolution pr = new PrinterResolution(300, 300, PrinterResolution.DPI);

    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.ISO_A4);
    aset.add(pr);
    aset.add(OrientationRequested.PORTRAIT);

    job.setPrintable(document);

    boolean doPrint = false;

    if (showDialog){
        doPrint = job.printDialog(aset);
    }else doPrint = true;

    if (doPrint){
        try{
            job.print();
        }catch(PrinterException e){
            e.printStackTrace();
        }
    }

The aset variable contains all of your new default values, and by plugging it into the printDialog, those are inputted into the printJob and consequently show up on the paper! They can be changed in the dialog, as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!