airmil
airmil

Reputation: 115

Setting up page margins on pdf-renderer (java)

I am using pdf-renderer library to print an already generated pdf file. This pdf file has already been created and needs to be printed as is in order to fit a certain pre-printed A4 paper. The problem is that some information needs to be printed at the very top which I cannot make it print up top. I am following this guide http://lynema.org/2010/12/29/printing-a-pdf-in-java-with-pdfrenderer in order to set up page sizes but there is no clue about the page margins. Is there a way to set up page margins so as to print the pdf page as it is? Thank you in advance

Upvotes: 0

Views: 3517

Answers (1)

user4376437
user4376437

Reputation:

In theory you can make the PDF fit the paper by calling setImageableArea on the Paper object to get rid of the print job's default margins.

PDFFile pdfFile = new PDFFile(ByteBuffer.wrap(pdfBytes));
PDFPrintPage pages = new PDFPrintPage(pdfFile);
PrinterJob job = PrinterJob.getPrinterJob();
Paper paper = new Paper();
paper.setSize(595, 842); // A4 dimensions in font points

// Make the document fill the whole page without stupid extra margins!
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());

PageFormat pageFormat = new PageFormat(); // or printerJob.defaultPage();
pageFormat.setPaper(paper);
pageFormat.setOrientation(PageFormat.PORTRAIT);

Book book = new Book();
book.append(pages, pageFormat, pdfFile.getNumPages());
job.setPageable(book);
if (job.printDialog()) {
    job.print();
}

Now, there is a bug in Java that messes up the orientation, resulting in extra space even for the above code.

To work around it, go to this page, scroll down about 70%, and look for Barrett's answer at December 19th, 2009, at 7:47 pm, where he suggests to double the setImageableArea width:

paper.setImageableArea(0, 0, paper.getWidth() * 2, paper.getHeight());

I think * 2 is hacky. A more logical solution is to pass whichever dimension is bigger. But beware it might fowl up if you mess with the orientation.

double biggerDimension = Math.max(paper.getWidth(), paper.getHeight());
paper.setImageableArea(0, 0, biggerDimension, biggerDimension).

Upvotes: 1

Related Questions