Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a text using PDFBox

My question is very simple: how can I center a text on a PDF, using PDFBox?

I don't know the string in advance, I can't find the middle by trial. The string doesn't always have the same width.

I need either:

  • A method that can center the text, something like addCenteredString(myString)
  • A method that can give me the width of the string in pixels. I can then calculate the center, for I know the dimensions of the PDF.

Any help is welcome!

like image 955
SteeveDroz Avatar asked Jun 28 '11 13:06

SteeveDroz


People also ask

What is the use of PDFBox?

It allows the creation of new PDF documents, manipulation of existing documents, bookmarking PDF and the ability to extract content from PDF documents. We can also use it to digitally sign, print and validate files against the PDF/A-1b standard. PDFBox library was originally developed in 2002 by Ben Litchfield.

Is PDFBox free for commercial use?

Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative ...


1 Answers

Ok, I found the answer myself. Here is how to center some text on a page:

String title = "This is my wonderful title!"; // Or whatever title you want. int marginTop = 30; // Or whatever margin you want.  PDDocument document = new PDDocument(); PDPage page = new PDPage(); PDPageContentStream stream = new PDPageContentStream(document, page); PDFont font = PDType1Font.HELVETICA_BOLD; // Or whatever font you want.  int fontSize = 16; // Or whatever font size you want. float titleWidth = font.getStringWidth(title) / 1000 * fontSize; float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;  stream.beginText(); stream.setFont(font, fontSize); // Deprecated, only before 2.0: // stream.moveTextPositionByAmount((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight); // From 2.0 and beyond: stream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight); stream.drawString(title); stream.endText(); stream.close(); 
like image 61
SteeveDroz Avatar answered Sep 28 '22 03:09

SteeveDroz