Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDFBox: clipping text when writing to PDPageContentStream or PDPage

I am looking into options to layout a PDF document that must be very neat and accurate.

The document is a sort of report and displays data onto an existing background. In some situation, the text is larger that the room it should fit in.

I would like to clip the text to the precise area it is allowed to take (this is not wrapping or "elipsizing" as the text is most of the times numbers).

Here is the effect I am looking for (this is an example, I am not looking into shortening the string, I want the string to remain untouched, but being actually clipped outside its allowed area).

enter image description here

Thanks, JM

like image 581
jmc34 Avatar asked Oct 25 '25 17:10

jmc34


1 Answers

First create a path, e.g. with PDPageContentStream.addRect(). Then call PDPageContentStream.clip(). This will intersect the current clipping path with your path. Then draw whatever you want to be clipped.

Don't forget to put the whole thing between saveGraphicsState() and restoreGraphicsState() or your clipping path will become empty at some time, due to it being intersected again.

To verify that your clipping path is correct while developing, replace the clip() call with stroke() so that you can see where it is.

like image 69
Tilman Hausherr Avatar answered Oct 29 '25 09:10

Tilman Hausherr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!