How to create rectangle vertically and add text to it in PDF using itext 2.1.7

1k views Asked by At

My requirement is straight, I want to create a rectangle positioned vertically and add text to it starting from bottom to going upward direction. (basically 90 degree box) in all pages of PDF

I tried achieving it using below code snap, but I want it to be enclosed within a specific dimension of box, which I cant control using this ColumnText approach

for example:

ColumnText.showTextAligned(canvas, PdfContentByte.ALIGN_LEFT, note,
                        .03F * pageWidth, .68F * pageHeight, 90);
1

There are 1 answers

1
mkl On BEST ANSWER

For a task like yours the static convenience methods of ColumnText don't suffice, you need to actually create and parameterize a full ColumnText instance.

For example like this:

float width = Utilities.millimetersToPoints(10);
float height = Utilities.millimetersToPoints(100);
float x = Utilities.millimetersToPoints(15);
float y = Utilities.millimetersToPoints(150);
float fontHeight = Utilities.millimetersToPoints(4);
String content = "Some text to fill the box. There's nothing really to say, just a box to fill. So let's fill the box.";

PdfReader reader = new PdfReader(YOUR_SOURCE_FILE);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "RotatedBoxForAbbas.pdf")));
Rectangle cropBox = reader.getCropBox(1);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.concatCTM(0, 1, -1, 0, cropBox.getLeft() + x + width, cropBox.getBottom() + y);
canvas.rectangle(0, 0, height, width);
canvas.stroke();
ColumnText columnText = new ColumnText(canvas);
columnText.addText(new Chunk(content, new Font(FontFamily.HELVETICA, fontHeight)));
columnText.setLeading(fontHeight);
columnText.setSimpleColumn(2, 0, height - 4, width);
columnText.go();
stamper.close();

(AddTextBox test testRotatedBoxForAbbas)

(While this test has been created for iText 5, it should work identically with iText 2.1.7 and OpenPdf after adapting the import packages.)

You didn't mention dimensions in this question but in your previous, removed one you mentioned dimensions given in mm, so I also used millimeters here.

The result on an empty source page:

screen shot