Java打印字体拉伸

我只是让打印机在
java中工作我也需要它,但是我需要解决的最后一个问题.当它打印时,字体的宽度相当拉伸,并且不像它应该的那样清晰和清晰.

这是我的代码我的实际绘图到论文:

    FontMetrics metrics = graphics.getFontMetrics(font);
    int lineHeight = metrics.getHeight();

    arrangePage(graphics, pageFormat, lineHeight);

    if (page > pageBreaks.length){
        return NO_SUCH_PAGE;
    }

    Graphics2D g = (Graphics2D) graphics;

    g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g.setFont(font);

    int y = 0;
    int begin = 0;

    if (page == 0){
        begin = 0;
    }else begin = pageBreaks[page-1];

    int end = 0;

    if (page == pageBreaks.length){
        end = lines.length;
    }else end = pageBreaks[page];

    for (int line = begin; line < end; line++){
        y += lineHeight;
        g.drawString(lines[line], 0, y);
    }

    string = deepCopy;

    return PAGE_EXISTS;

如何摆脱拉伸?可以注意到,这是基于本教程:
http://docs.oracle.com/javase/tutorial/2d/printing/set.html

非常感谢任何建议或帮助.

最佳答案 默认的DPI是正常的72 DPI(我相信),在印刷纸上,它非常糟糕.您需要提示打印API尝试找到具有更好DPI的打印机.

基本上您需要使用print services API.

试试像……

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;
    }
  }
}

你可能会发现Working with Print Services and Attributes的一些帮助……

我应该警告你,这将打印到它可以找到的第一个符合PrintRequestAttributeSet的打印件.你也可以添加打印对话框来查看它在做什么,但这是我现在可以生活的另一个复杂程度;)

点赞