Question:
I am creating an application which commands Graphics
objects to be printed to a specific printer, what I need is to be able to change the paper size settings through java code.
This is my code with which I print and put printing attributes, such as the number of copies, the color of the paper, orientation, etc., that if it does it correctly.
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = new PageFormat();
int numero = Integer.parseInt(SNumero.getValue().toString());
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(numero));
aset.add(new MediaPrintableArea(0, 0, 62, 29, MediaPrintableArea.MM));
aset.add(Chromaticity.COLOR);
aset.add(OrientationRequested.PORTRAIT);
Paper paper = new Paper();
paper.setSize(175.748031496, 82.204724409);
double margin = 8.503937008;
paper.setImageableArea(0, 0, 175.748031496, 82.204724409);
pf.setPaper(paper);
job.setPrintable(new ObjetoDeImpresion(),pf);
job.setJobName("nombre_de_impresion");
try {
job.print(aset);
} catch (PrinterException ex) {
System.out.println(ex);
}
}
I've tried adding something like this to tell the printer to print a paper size that I want, but it doesn't work:
aset.add(new MediaSize(62, 29, MediaSize.MM));
My paper size is 62mm wide and the paper is continuous in length, so it should be possible to define a length size.
Does anyone have any idea how to do it?
Answer:
Have you tried Paper like this?
- Create a Paper with your measurements using the setSize and setImageableArea methods, for example.
- Create a PageFormat and assign it the paper that you have previously created with the setPaper method.
- Add the PageFormat you created to your
aset
.
aset.add(myPageFormat);
Hope this can help you.
EDIT: Seeing that this solution has not served you. Let me know if you've tried the following: You use the setPrintable method like this: job.setPrintable(new ObjetoDeImpresion());
But you could also use it from this: setPrintable(Printable painter, PageFormat format)
This could be a good way to pass it your PageFormat that you can create as I commented in my first answer.
Another option:
Taken from here , it looks good.
Book book = new Book(); //java.awt.print.Book
book.append(this, pf);
job.setPageable(book);
instead of:
job.setPrintable (new PrintObject (), pf);