我正在尝试以自定义样式将表格打印到一张纸上,但是当我将其发送到打印机时,页面上只打印了列标题。
使用相同的代码打印到JPanel时,它可以正常工作。
我一直在像疯子一样进行调试,但我发现只是在写入打印机时使用了不同的图形,并且它以某种方式略微不同地计算字符串的宽度,尽管我看不到这应该如何影响所写的内容。
我已经确认所有代码都已运行。
绘制标题的代码:
private void drawColumnHeaders(Graphics2D g, PageFormat pf)
{
g.drawLine(columnWidths[0]-1, 0, columnWidths[0]-1, rowHeight);
drawText(g, 1, columnHeader[1]);
drawLineAround(g, 1);
drawText(g, 2, columnHeader[2]);
drawLineAround(g, 2);
etc...
...
g.translate(0, rowHeight);
}
绘制行的代码:
private void drawRow(Graphics2D g, Konto konto, boolean kunAfstanden)
{
...
drawAccountNo(g, konto, 1);
etc...
...
g.translate(0, rowHeight);
}
...
private void drawAccountNo(Graphics2D g, Account account, int columnNo)
{
switch (account.getType())
{
case SUMACCOUNT:
drawLineBeneath(g, columnNo);
default:
drawText(g, columnNo, "" + account.getAccountNo());
break;
}
}
实用方法:
private void drawText(Graphics2D g, int columnNo, String text)
{
int startX = calculatePosition(columnNo);
g.drawString(text, startX + lMargin, g.getFontMetrics().getAscent() + aMargin);
}
private void drawLineAround(Graphics2D g, int columnNo)
{
int startX = calculatePosition(columnNo);
drawLineBeneath(g, columnNo);
g.drawLine(startX + columnWidths[columnNo], 0, startX + columnWidths[columnNo], rowHeight);
}
...
private int calculatePosition(int columnNo)
{
int result = 0;
for (int i = 0; i < columnNo; i++)
{
result+= columnWidths[i];
}
return result;
}
感谢任何帮助。
修改
控制打印的代码:
@Override
public int print(Graphics ga, PageFormat pf, int pageIndex) throws PrinterException
{
ga.setFont(normalFont);
Graphics2D g = (Graphics2D) ga;
if (!writeToPrinter)
{
pf = standardPF;
}
int returnMessage = -1;
int noOfRowsOnPage = 0;
calculateColumnWidths(g, pf);
//Calculates how many pages there will be:
calculateNoOfPages(g, pf);
if (pageIndex < noOfPages)
{
//Translates Graphics:
prepareGraphics(g, pf);
//The parts that do show up:
drawHeader(g, pf);
drawStart(g, pf);
drawColumnHeaders(g, pf);
while (returnMessage == -1)
{
try
{
if (accounts.get(iReached).getType().t() != TypeAccount.NEWPAGE.t() && possibleRows > noOfRowsOnPage)
{
//The part that doesn't (even though the code is reached):
drawRow(g, accounts.get(iReached));
noOfRowsOnPage++;
}
else
{
//If the page isn't empty, go to the next page
if (noOfRowsOnPage > 0)
{
returnMessage = PAGE_EXISTS;
}
}
iReached++;
}
catch (IndexOutOfBoundsException e)
{
returnMessage = PAGE_EXISTS;
}
}
drawFooter(g, pf, false);
}
else
{
returnMessage = NO_SUCH_PAGE;
}
return returnMessage;
}
使用的PageFormat初始化:
standardPF = new PageFormat();
standardPF.setOrientation(PageFormat.PORTRAIT);
Paper paper = new Paper();
paper.setImageableArea(30, 30, 535, 780);
paper.setSize(595.44, 841.68);
standardPF.setPaper(paper);