Santhucool Santhucool - 5 months ago 26
Java Question

PDFBOX unable to find number of pixels which contain a particular character

I am using

PDFBOX
for pdf creation. In pdfbox is there any function which will give the font size in pixels? For example letters
A
and
a
, will take different spaces for printing. Where obviosely
A
will take more pixels than
a
. How can I get find number of pixels supposed to take a character or a word?

Answer

First of all the concept of pixels is a bit vague. Generally a document is of a certain size, e.g. inches/cm etc.

The javadocs for PDFBox shows that PDFont has a few methods to determine the width of a string or character. Take a look at for example these pages:

getStringWidth(String text)

getWidth(int code)

getWidthFromFont(int code)

These units are in 1/1000 of an Em. Also see this page.

For a full example:

float fontSize = 12;
String text = "a";

PDRectangle pageSize = PDRectangle.A4;
PDFont font = PDType1Font.HELVETICA_BOLD;


PDDocument doc = new PDDocument();
PDPage page = new PDPage(pageSize);
doc.addPage(page);

PDPageContentStream stream = new PDPageContentStream(doc,page);
stream.setFont( font, fontSize );

// charWidth is in points multiplied by 1000.
double charWidth = font.getStringWidth(text);
charWidth *= fontSize; // adjust for font-size.

stream.beginText();
stream.moveTextPositionByAmount(0,10);

float widthLeft = pageSize.getWidth();
widthLeft *= 1000.0; //due to charWidth being x1000.

while(widthLeft > charWidth){
    stream.showText(text);
    widthLeft -= charWidth;
}

stream.close();
// Save the results and ensure that the document is properly closed:
doc.save( "example.pdf");
doc.close();
Comments