Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDFBox: How to draw text on top of a filled rectangle?

Tags:

java

pdfbox

I am trying to use Java with PDFBox to draw some text to a PDF file, and set a background color for the text. I know how to draw text and draw filled rectangles, but when I try to draw text in the same position as a rectangle, the text is never shown. Example:

//draw rectangle
content.setNonStrokingColor(200, 200, 200); //gray background
content.fillRect(cursorX, cursorY, 100, 50);

//draw text
content.setNonStrokingColor(0, 0, 0); //black text
content.beginText();
content.setFont(family, fontPt);
content.moveTextPositionByAmount(cursorX, cursorY);
content.drawString("Test Data");
content.endText();

The text never shows up. It is always covered by the rectangle. Any ideas for how to make the text draw on top of the rectangle?

EDIT: As Mkl mentioned in answer, the code I provided actually works. My problem ended up being that the code was in a loop, drawing the background for each line, but the background was drawing over the previous line, and not the current line, overwriting previous text. I just needed to alter the order of events in my looping. Should this question be deleted? It seems unlikely that anyone else would find it useful.

like image 405
dave823 Avatar asked Nov 30 '25 05:11

dave823


1 Answers

The code you show works.

I made it runnable like this:

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA_BOLD;

int cursorX = 70;
int cursorY = 500;

//draw rectangle
content.setNonStrokingColor(200, 200, 200); //gray background
content.fillRect(cursorX, cursorY, 100, 50);

//draw text
content.setNonStrokingColor(0, 0, 0); //black text
content.beginText();
content.setFont(font, 12);
content.moveTextPositionByAmount(cursorX, cursorY);
content.drawString("Test Data");
content.endText();

content.close();
document.save(new File("textOnBackground.pdf"));
document.close();

(DrawOnBackground.java)

And the result looks like this:

enter image description here

Thus, the cause for your issue lies beyond the code you provided.

PS: I use PDFBox 1.8.10.

like image 111
mkl Avatar answered Dec 01 '25 21:12

mkl