java 设置打印界面字体,Java打印字体拉伸

I just got the printer to work in java how I need it too, but there's one last problem I need to solve. When it prints, the font's width is rather stretched, and not crisp and clear like it should be.

Here is my code my the actual drawing to the paper:

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;

How do I get rid of the stretching? It can be noted that this is based off this tutorial:

http://docs.oracle.com/javase/tutorial/2d/printing/set.html

Any advice or help is greatly appreciated.

解决方案

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;

}

}

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值