gpt4 book ai didi

java - java打印时如何调整页面宽度

转载 作者:行者123 更新时间:2023-12-01 11:13:56 25 4
gpt4 key购买 nike

我可以通过这段代码巧妙地打印带有页脚的任何组件。它的工作方式很巧妙。

public class MultiPagePrintable implements Printable {

private JComponent component;
private int lastPage = 0;
private double yOffset;

private Font footerFont;

public MultiPagePrintable(JComponent component) {
this.component = component;

footerFont = new Font("Arial", Font.BOLD, 24);
}

@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int result = NO_SUCH_PAGE;

String name = "I be mighty!";
String page = Integer.toString(pageIndex);

FontMetrics fm = graphics.getFontMetrics(footerFont);
double footerHeight = fm.getHeight() + 4;

double height = pageFormat.getImageableHeight() - footerHeight;
component.setSize(component.getPreferredSize());

if (lastPage != pageIndex) {
lastPage = pageIndex;
yOffset = height * pageIndex;
if (yOffset > component.getHeight()) {
yOffset = -1;
}
}

if (yOffset >= 0) {
Graphics2D g2d = (Graphics2D) graphics.create();

g2d.translate((int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY());

g2d.translate(0, -yOffset);
component.printAll(g2d);
g2d.translate(0, +yOffset);
Shape footerArea = new Rectangle2D.Double(0, height, pageFormat.getImageableWidth(), footerHeight);
g2d.setColor(Color.WHITE);
g2d.fill(footerArea);
g2d.setColor(Color.RED);
g2d.draw(footerArea);

g2d.setColor(Color.BLACK);


g2d.translate(0, (pageFormat.getImageableHeight() - footerHeight));
float x = 2;
float y = (float)((footerHeight - fm.getHeight()) / 2d);
g2d.drawString(name, x, y + fm.getAscent());

x = (float)(pageFormat.getImageableWidth() - fm.stringWidth(page) - 2);
g2d.drawString(page, x, y + fm.getAscent());

g2d.dispose();
result = PAGE_EXISTS;
}
return result;
}

}

但问题是,它无法缩放组件宽度以适合页面。但是我不想适应高度。因为这段代码已经可以打印多页了。我需要它。

最佳答案

您想要缩放 Graphics2D:

g2d.translate(0, -yOffset);
double width = pageFormat.getImageableWidth();
double scale = Math.min(width / component.getWidth(),
height / component.getHeight());
if (scale < 1) {
AffineTransform oldTransform = g2d.getTransform();
g2d.scale(scale, scale);
component.printAll(g2d);
g2d.setTransform(oldTransform);
} else {
component.printAll(g2d);
}
g2d.translate(0, +yOffset);

我不确定你所说的“我不想适应高度”是什么意思,但如果你愿意,你可以随时忽略高度:

g2d.translate(0, -yOffset);
double width = pageFormat.getImageableWidth();
double scale = width / component.getWidth();
if (scale < 1) {
AffineTransform oldTransform = g2d.getTransform();
g2d.scale(scale, scale);
component.printAll(g2d);
g2d.setTransform(oldTransform);
} else {
component.printAll(g2d);
}
g2d.translate(0, +yOffset);

关于java - java打印时如何调整页面宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32059202/

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