Hola Galera, é o seguinte: Estou com uma questão referente a impressão de um nota de controle interno no seguinte formato.
Cabeçalho contendo [Nome da Empresa, Nome do Cliente, Usuario, etc] |
Lista de serviços e itens que são capturados de um jtable. |
Aqui no caso pode existir ‘N’ linhas, mas existe um limite de 17 itens |
devido ao tamanho de papel utilizado (21x14) |
---------------------------------------------------------------------------------------------------------- |
Pé de página |
__________________________________________________________________ |
Então a pergunta é, como posso repetir o cabeçalho e pé de pagina se as linhas do JTable forem superior a 17? Utilizando a classe print
exemplo:
@Override
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
String temp;
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
int lineSize=20;
Font testFont=new Font("Lucida Console", Font.BOLD, 20);
// font name, style (0 for Plain), font size
g.setFont(testFont);
int line=20;
g.drawString(" Fatura/Recibo nº"+nmrRec+" ", 5, line);
return PAGE_EXISTS;
}
Agradeço desde já.
Cria um método pra imprimir o cabeçalho, outro pra imprimir o rodapé e um que imprime os itens
Você terá que calcular quantas páginas poderão ser impressas (total de itens / limite de itens por página).
Enquanto o parâmetro page
for menor que o número de páginas que você calculou, você vai:
- imprimir o cabeçalho;
- imprimir os próximos 17 itens;
- imprimir o rodapé;
- retornar
PAGE_EXISTS
.
Quando o parâmetro page
for maior ou igual a quantidade de páginas calculadas, você retorna NO_SUCH_PAGE
.
1 curtida
Tentei Algo assim mas nao estou tendo sucesso.
if (iRowImprimindo<jtblDatos.getRowCount()) {
Graphics2D pg = (Graphics2D) g;
//==== - Define o formato da folha de impressão (area possivel de se fazer a impressão do conteudo) - =======
pg.translate(format.getImageableX(), format.getImageableX());
//======- Definição da font a ser utilizada - ================
pg.setFont( new Font( "Courier New",Font.PLAIN, 10) );
// Obtenho a altura da Font
iAlturaFont = pg.getFontMetrics().getHeight();
// Verifica si imprimir cabeçalho
if (bImprimirCabecalho)
{
pg.drawString("-----------------------",iPosX,iAlturaFont* (iEspaco));
bImprimirCabecalho=false;
}
// Ciclo para Imprimir Itens
for (iConteo=iRowImprimindo; iConteo<(jtblDatos.getRowCount());iConteo++)
{
sDato = jtblDatos.getValueAt(iConteo, COL_IMPORTE).toString();
pg.drawString(sDato ,iPosX,iPosY);
if (iConteo>=iLimiteLinhas)
{
bImprimirCabecalho=true;
//Sair do ciclo FOR
break;
}
}
// Pé de página
pg.drawString("----------------------------------------------------------------------------------------------",iPosX,iAlturaFont*30 );
// Atualiza a linha a ser Impresa
iRowImprimindo=iConteo;
if (page >= iTotalPaginas) {
iRowImprimindo=0;
EstadoImpresion = NO_SUCH_PAGE;
}
else
EstadoImpresion = (PAGE_EXISTS);
}
return EstadoImpresion;
}
Chamando o método de impressão assim, aqui também faço a definição do tamanho da folha:
book = new Book();
pageFormat = new PageFormat();
Folha = new Paper();
double width = 215.9 * fatorConverMMPt;
double height = 140.0 * fatorConverMMPt;
Folha.setSize(width, height);
Folha.setImageableArea(0.0, 0.0, width, height);
pageFormat.setPaper(Folha);
book.append(this, pageFormat);
PrinterJob impressoraPadrao = PrinterJob.getPrinterJob();
impressoraPadrao.setPrintable(this);
impressoraPadrao.setPageable(book);
try {
impressoraPadrao.print();
} catch (Exception e) {
e.printStackTrace();
}
Mesmo assim ele só imprime a primeira página.
Não estou encontrando a solução para imprimir mais de uma página.
Alguma ajuda?
Atte.
Posta o código completo de sua classe
Exemplo para Solução.
Utilizei essa classe como exemplo:
import java.awt.Font;
import java.awt.Graphics;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.util.Enumeration;
import java.util.Vector;
public class MainClass {
public static void main(String args[]) throws Exception {
PrinterJob pj = PrinterJob.getPrinterJob();
Book book = new Book();
PageFormat defaultFormat = new PageFormat();
defaultFormat = pj.defaultPage(defaultFormat);
PageFormat landscapeFormat = new PageFormat();
landscapeFormat.setOrientation(PageFormat.LANDSCAPE);
PagePrinter[] page = new PagePrinter[2];
int pageWidth = (int) defaultFormat.getImageableWidth();
int pageHeight = (int) defaultFormat.getImageableHeight();
Font font = new Font("Helvetica", Font.BOLD, 18);
page[0] = new PagePrinter();
page[0].addPrintElement(new MyItem("AAA", font, 100, pageHeight / 2));
page[0].addPrintElement(new MyItem("line", 0, pageHeight, pageWidth, pageHeight));
page[1] = new PagePrinter();
page[1].addPrintElement(new MyItem("rectangle", 100, 100, pageWidth - 200, pageHeight - 200));
page[1].addPrintElement(new MyItem("oval", 120, 120, pageWidth - 240, pageHeight - 240));
book.append(page[0], defaultFormat);
book.append(page[1], landscapeFormat);
pj.setPageable(book);
pj.print();
}
}
class PagePrinter implements Printable {
Vector pageContents;
public PagePrinter() {
pageContents = new Vector();
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
Enumeration printElements = pageContents.elements();
while (printElements.hasMoreElements()) {
MyItem pe = (MyItem) printElements.nextElement();
pe.print(g);
}
return Printable.PAGE_EXISTS;
}
public void addPrintElement(MyItem pe) {
pageContents.addElement(pe);
}
}
class MyItem {
static final int TEXT = 1;
static final int GRAPHICS = 2;
int type;
String text;
Font font;
String shape;
int x, y, width, height;
public MyItem(String text, Font font, int x, int y) {
type = TEXT;
this.text = text;
this.font = font;
this.x = x;
this.y = y;
}
public MyItem(String shape, int x, int y, int width, int height) {
type = GRAPHICS;
this.shape = shape.toUpperCase();
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void print(Graphics g) {
Font oldFont = g.getFont();
if (type == TEXT) {
g.setFont(font);
g.drawString(text, x, y);
} else if (type == GRAPHICS) {
if (shape.equals("LINE")) {
g.drawLine(x, y, width, height);
} else if (shape.equals("OVAL")) {
g.drawOval(x, y, width, height);
} else if (shape.equals("RECTANGLE")) {
g.drawRect(x, y, width, height);
}
}
g.setFont(oldFont);
}
}