PDFBox

You are currently browsing articles tagged PDFBox.

So I’m mixing it up a little bit.  Today’s example prints from a StringBuffer and not a File.  Printing from a File should be pretty similar.  This is useful whenever something needs to be printed out for auditing purposes.

There is some code in here to get around the limitations of a page.  The number of lines on a page and the font size are part of this.  In practice, if the line in the StringBuffer is bigger than the page, it will just disappear.    In this case, the lines were already formatted to be a length that did not skip off of the page.

The code treats the page as a canvas and writes to specific part of that canvas.  If you use this code, be sure to pay attention to all of the settings that inpact the way the text appears on the page.  Some changes will impact other settings.  For example, if the font size is increased, the spacing between lines should increase.

This isn’t particularly object oriented as it is an example.

PrintService printService = PrintHelper.getPrintService(YOUR_PRINTER_NAME);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(new JobName(YOUR_JOB_NAME,Locale.getDefault()));
PrinterJob pjob = PrinterJob.getPrinterJob();
pjob.setPrintService(printService);

PDDocument document = new PDDocument();
//To load a file do this:   pd = PDDocument.load(input);
PDPage page = new PDPage();
document.addPage( page );
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont( font, 12 );
//The first number in moveTextPositionByAmount is to provide a left margin.
//The second number in moveTextPositionByAmount is to miss the header
contentStream.moveTextPositionByAmount( 100, 550 );
StringReader strReader = new StringReader(printText.toString());
BufferedReader strBufRdr = new BufferedReader(strReader);
String line = "";
Integer linesPrinted = 0;
while((line=strBufRdr.readLine()) != null)
{
contentStream.drawString(line);
linesPrinted++;
//The second parameter will change if the font changes.
//It's something that has to be guessed and checked to get right.
contentStream.moveTextPositionByAmount( 0, SPACE BETWEEN LINES -15 SHOULD BE GOOD);
if (linesPrinted % INTEGER_FOR_LINES ON A PAGE 30 SHOULD BE GOOD == 0)
{
contentStream.endText();
contentStream.close();
page = new PDPage();
document.addPage( page );
contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont( font, 12 );
contentStream.moveTextPositionByAmount( 100, 550 );
}
}
contentStream.endText();
contentStream.close();
//For testing, write this to a file
//document.save("outpdf.pdf");
document.silentPrint(pjob);
document.close();
}

catch (PrinterException e)
{
//Handle Error
}
catch (IOException e)
{
//Handle Error
}
}

Tags: , ,