我正在尝试打印带有一些绘制图形的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());
使它开始绘制在正确的topleft角(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;
}
}
答案 0 :(得分:2)
在发布此问题并回到我的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()方法不会在每个页面上绘制得更多!