I am trying to add a legend as a single line (Paragraph) to a chart drawn as an image on my page. The legend needs to have the descriptor (Chunk) followed by a line of the appropriate color to match the chart. When I search on how to draw a line, it appears that I can only do it using absolute positioning. Is there some way to draw the line following the descriptor regardless of where the descriptor will be in the paragraph and on the page? It will also be followed by one or more additional descriptors (Chunks) each with an appropriately colored line. TIA.
String[] monitors=Configuration.getInstance().getMonitorIds();
Chunk title=new Chunk("Legend: ");
title.setFont(legendFont);
Paragraph legend=new Paragraph(title);
for (String entry : monitors) {
Monitor mon=Configuration.getInstance().getMonitor(entry);
Chunk name=new Chunk(mon.getName());
Font nameFont=new Font(FontFamily.TIMES_ROMAN, 20.f, Font.BOLD,new BaseColor(mon.getColor().getRGB()));
name.setFont(nameFont);
// What goes here to draw the line???
legend.add(name);
}
document.add(legend);
Update after a comment from @mkl:
I think I found what you meant in this article: Drawing diagonal line in a cell of a table in iTExt?. So I added the following to my helper to draw a horizontal line rather than the diagonal in the article:
@Override
public void onGenericTag(PdfWriter writer_, Document document_, Rectangle rectangle_, String tag_) {
PdfContentByte canvas = writer_.getDirectContent();
canvas.saveState();
Monitor mon=Configuration.getInstance().getMonitor(tag_);
canvas.setColorStroke(new BaseColor(mon.getColor().getRGB()));
canvas.moveTo(Rectangle.LEFT,Rectangle.ALIGN_CENTER);
canvas.lineTo(Rectangle.RIGHT,Rectangle.ALIGN_CENTER);
canvas.stroke();
canvas.restoreState();
}
Then I changed my code (along with some other tweaking) to include the onGenericTag Chunk but it was not a direct thing as I interpreted the article. I can't put just a Chunk in a Cell. Here is my current code:
String[] monitorIds=Configuration.getInstance().getMonitorIds();
PdfPTable leg=new PdfPTable(monitorIds.length+2);
Paragraph p=new Paragraph("Legend: ",legendFont);
PdfPCell title=new PdfPCell(p);
title.setBorder(Rectangle.NO_BORDER);
leg.addCell(title);
for (String entry : monitorIds) {
Monitor mon=Configuration.getInstance().getMonitor(entry);
Font nameFont=new Font(FontFamily.TIMES_ROMAN, 14.f, Font.BOLD,new BaseColor(mon.getColor().getRGB()));
Paragraph name=new Paragraph(mon.getName(),nameFont);
PdfPCell c=new PdfPCell(name);
c.setBorder(Rectangle.NO_BORDER);
leg.addCell(c);
Chunk line=new Chunk();
line.setGenericTag(entry);
c=new PdfPCell(new Paragraph(line));
c.setBorder(Rectangle.NO_BORDER);
leg.addCell(c);
}
document.add(leg);
Unfortunately the line does not show up. What am I doing wrong? TIA.
After all the suggestions
Thanks for them. I've decided to try to stick with the OnGenericTag. I think it is more appropriate, at this point, to start a new thread. Drawing a Line in a PdfPCell Using OnGenericTag