如何在java中的pdfbox中将文本放入矩形?

时间:2018-05-02 10:24:08

标签: java pdfbox

通过内容流我希望在矩形中显示“连接我们”文本。

contentStream.beginText();
contentStream.setFont(PDType1Font.TIMES_ROMAN, 10);
contentStream.newLineAtOffset(260, 240);            
contentStream.showText("Connect with Us:");
contentStream.endText();
contentStream.setNonStrokingColor(235,235,235);
contentStream.addRect(50, 200, 500, 100);
contentStream.fill();

我尝试使用此代码在矩形中获取文本,但没有在矩形中看到文本。

1 个答案:

答案 0 :(得分:1)

首先绘制文字

contentStream.beginText();
contentStream.setFont(PDType1Font.TIMES_ROMAN, 10);
contentStream.newLineAtOffset(260, 240);            
contentStream.showText("Connect with Us:");
contentStream.endText();

然后填充矩形...

contentStream.setNonStrokingColor(235,235,235);
contentStream.addRect(50, 200, 500, 100);
contentStream.fill();

嗯,会发生什么?你的矩形覆盖了文字!

要解决此问题,请以相反的方式执行此操作,首先绘制矩形,重置非描边颜色,然后在其上书写。

contentStream.setNonStrokingColor(235,235,235);
contentStream.addRect(50, 200, 500, 100);
contentStream.fill();
contentStream.setNonStrokingColor(0,0,0);
contentStream.beginText();
contentStream.setFont(PDType1Font.TIMES_ROMAN, 10);
contentStream.newLineAtOffset(260, 240);            
contentStream.showText("Connect with Us:");
contentStream.endText();