我正在尝试在iText中创建一个具有背景颜色和文本的矩形。
如果我按原样运行代码,则会得到文本,但没有背景色。调用canvas.fillStroke()会填充背景色,但不显示任何文本。
如何获取背景颜色和字体?
public void createPdf() {
try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
try(PdfWriter writer = new PdfWriter(os)) {
try(PdfDocument pdf = new PdfDocument(writer)) {
try (Document document = new Document(pdf)) {
PdfPage page = pdf.addNewPage();
PageSize ps = pdf.getDefaultPageSize();
Text green = new Text("This text is green. ")
.setFontColor(new DeviceRgb(27,255,0));
Paragraph p = new Paragraph("This is the text added in the rectangle.");
p.add(green);
PdfCanvas canvas = new PdfCanvas(pdf.getFirstPage());
Color orange = new DeviceRgb(255, 100, 20);
canvas.setFillColor(orange);
Rectangle rect = new Rectangle(1f,ps.getHeight()-101f,ps.getWidth()-1f,100f );
new Canvas(canvas, pdf, rect)
.add(p);
canvas.rectangle(rect);
// canvas.fillStroke();
}
}
}
Files.write(new File("C:\\users\\tim\\file.pdf").toPath(), os.toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
答案 0 :(得分:1)
感谢mkl的评论
我要做的就是先填充矩形,然后在其后添加段落
public void createPdf() {
try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
try(PdfWriter writer = new PdfWriter(os)) {
try(PdfDocument pdf = new PdfDocument(writer)) {
try (Document document = new Document(pdf)) {
PdfPage page = pdf.addNewPage();
PageSize ps = pdf.getDefaultPageSize();
Text green = new Text("This text is green. ")
.setFontColor(new DeviceRgb(27,255,0));
Paragraph p = new Paragraph("This is the text added in the rectangle.");
p.add(green);
PdfCanvas canvas = new PdfCanvas(pdf.getFirstPage());
Color orange = new DeviceRgb(255, 100, 20);
canvas.setFillColor(orange);
Rectangle rect = new Rectangle(1f,ps.getHeight()-101f,ps.getWidth()-1f,100f );
Canvas rectangleCanvas = new Canvas(canvas, pdf, rect);
canvas.rectangle(rect);
canvas.fillStroke();
rectangleCanvas.add(p);
}
}
}
Files.write(new File("C:\\users\\tim\\file.pdf").toPath(), os.toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch(IOException e) {
throw new RuntimeException(e);
}
}