gpt4 book ai didi

java - 使用 java 打印时如何获取纸张的边距?

转载 作者:行者123 更新时间:2023-11-30 09:55:53 25 4
gpt4 key购买 nike

我正在尝试打印一个带有一些已绘制图形的 JPanel(覆盖 paintComponent)。图形太大,无法放在一页上,因此我让它跨越多个页面。我的问题在于,如果我让用户通过调用来选择 pageFormat/Paper 类型:

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PageFormat pf = printJob.pageDialog(aset);
printJob.setPrintable(canvas, pf);

当我在我的 JPanel 类中编写 print() 方法(实现 Printable)时,我似乎无法控制边距?我使用 graphics.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); 使其在正确的左上角 (0;0) 开始绘制,并且它考虑了边距(即,从 (80; 100) 左右开始。但随后它打印在底部和右边距上,我不希望它这样做,因为这否定了用户的意愿。

这里是我的 print() 方法的代码作为引用,当你不让用户设置纸张时它工作正常(使用默认值):

    Rectangle[] pageBreaks;

public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
//Calculate how many pages our print will be
if(pageBreaks == null){
double pageWidth = pageFormat.getPaper().getWidth();
double pageHeight = pageFormat.getPaper().getHeight();

//Find out how many pages we need
int numberOfPagesHigh = (int) Math.ceil(size.getHeight()/pageHeight);
int numberOfPagesWide = (int) Math.ceil(size.getWidth()/pageWidth);
pageBreaks = new Rectangle[numberOfPagesHigh*numberOfPagesWide];

double x = 0;
double y = 0;
int curXPage = 0;

//Calculate what we will print on each page
for (int i = 0; i < pageBreaks.length; i++){
double xStart = x;
double yStart = y;
x += pageWidth;

pageBreaks[i] = new Rectangle((int)xStart, (int)yStart, (int)pageWidth, (int)pageHeight);

curXPage++;
if (curXPage > numberOfPagesWide){
curXPage = 0;
x = 0;
y += pageHeight;
}
}


}

if (pageIndex < pageBreaks.length){
//Cast graphics to Graphics2D for richer API
Graphics2D g2d = (Graphics2D) graphics;

//Translate into position of the paper
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

//Setup our current page
Rectangle rect = pageBreaks[pageIndex];

g2d.translate(-rect.x, -rect.y);
g2d.setClip(rect.x, rect.y, rect.width, rect.height);

//Paint the component on the graphics object
Color oldBG = this.getBackground();
this.setBackground(Color.white);
util.PrintUtilities.disableDoubleBuffering(this);
this.paintComponent(g2d);
util.PrintUtilities.enableDoubleBuffering(this);
this.setBackground(oldBG);

//Return
return PAGE_EXISTS;
}
else {
return NO_SUCH_PAGE;
}
}

最佳答案

在发布这个问题并返回我的 IDE 后,我很容易找到答案。而不是使用

double pageWidth = pageFormat.getPaper().getWidth();
double pageHeight = pageFormat.getPaper().getHeight();

使用

double pageWidth = pageFormat.getImageableWidth();
double pageHeight = pageFormat.getImageableHeight();

getImageableWidth() 返回 totalPaperWidth-totalMargins 而 getWidth() 只返回 totalPaperWidth。这使得 print() 方法不会在每个页面上绘制更多内容!

关于java - 使用 java 打印时如何获取纸张的边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2622045/

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