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.
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:

Thus, the cause for your issue lies beyond the code you provided.
PS: I use PDFBox 1.8.10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With