简体   繁体   English

如何使用 itext 2.1.7 垂直创建矩形并在 PDF 中向其添加文本

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

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 (基本上是 90 度框)在 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我尝试使用下面的代码快照来实现它,但我希望它包含在框的特定尺寸内,我无法使用此ColumnText方法控制它

for example:例如:

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

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.对于像您这样的任务, ColumnText的静态便捷方法是不够的,您需要实际创建并参数化一个完整的ColumnText实例。

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 ) AddTextBox测试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.) (虽然此测试是为 iText 5 创建的,但在调整导入包后,它应该与 iText 2.1.7 和 OpenPdf 工作相同。)

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:空源页面上的结果:

截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM