gpt4 book ai didi

Java 打印字体拉伸(stretch)

转载 作者:搜寻专家 更新时间:2023-11-01 03:25:43 24 4
gpt4 key购买 nike

我刚刚让打印机在 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;

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

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

最佳答案

默认的 DPI 是正常的 72 DPI(我相信),这在打印纸上非常糟糕。您需要提示打印 API 以尝试找到具有更好 DPI 的打印机。

基本上您需要使用打印服务 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 的打印件。您还可以添加打印对话框以查看它在做什么,但这是我现在可以忍受的另一个复杂程度;)

关于Java 打印字体拉伸(stretch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14352243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com