bazi
bazi

Reputation: 1866

java printing : incorrect paper size

im trying to print a pdf in A4 size but the output varies from the expected one.

this is what it looks like

enter image description here

but it supposed to be like this

enter image description here

both images are same resolution

this is the code that generates this output.

PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintService(service);
PageFormat pf = new PageFormat();
Paper paper = new Paper();
paper.setSize(595, 842); // a4 in px
paper.setImageableArea(0, 0, 595, 842);
pf.setPaper(paper);

Book book = new Book();
book.append(pages, pf, pdfFile.getNumPages());
pj.setPageable(book);

pj.print();

basically its just shrunk. what should i do to fix this?

and by the way, im not using a real printer. im using a virtual printer that takes a print request and outputs a pdf.

Upvotes: 3

Views: 3214

Answers (1)

bazi
bazi

Reputation: 1866

i have found a solution to this. i used javax.print library instead of java.awt.print.

File file = new File("path/to/pdf");
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(MediaSizeName.ISO_A4);
FileInputStream fis = new FileInputStream(file);
Doc doc = new SimpleDoc(fis, flavor, null);
DocPrintJob job = printService.createPrintJob();
job.print(doc, attr);
fis.close();

now it gets printed correctly.

Upvotes: 2

Related Questions