gpt4 book ai didi

java - 带黑色字体的 iText 矩形

转载 作者:行者123 更新时间:2023-12-02 10:15:23 24 4
gpt4 key购买 nike

我正在尝试在 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);
}
}

最佳答案

感谢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);
}
}

关于java - 带黑色字体的 iText 矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com