Skip to content

Instantly share code, notes, and snippets.

@scobal
Created July 31, 2013 19:40
Show Gist options
  • Save scobal/6125430 to your computer and use it in GitHub Desktop.
Save scobal/6125430 to your computer and use it in GitHub Desktop.
Pdfbox table with line wrapping and custom column widths
private void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content, float[] colWidths) throws IOException {
final int rows = content.length;
final int cols = content[0].length;
final float rowHeight = 40f;
final float tableWidth = page.findMediaBox().getWidth() - margin - margin;
final float tableHeight = rowHeight * rows;
final float colWidth = tableWidth/(float)cols;
final float cellMargin=5f;
//draw the rows
float nexty = y ;
for (int i = 0; i <= rows; i++) {
contentStream.drawLine(margin, nexty, margin+tableWidth, nexty);
nexty-= rowHeight;
}
//draw the columns
float nextx = margin;
for (int i = 0; i <= cols; i++) {
contentStream.drawLine(nextx, y, nextx, y-tableHeight);
nextx += (colWidths != null) ? colWidths[i] : colWidth;
}
float textx = margin+cellMargin;
float texty = y-15;
for(int i = 0; i < content.length; i++){
for(int j = 0 ; j < content[i].length; j++){
String text = content[i][j];
contentStream.beginText();
contentStream.moveTextPositionByAmount(textx,texty);
if (text.contains("\n")) {
String[] lines = text.split("\n");
contentStream.appendRawCommands(10 + " TL\n");
for (int k = 0; k < lines.length; k++) {
contentStream.drawString(lines[k]);
if (k < lines.length - 1) {
contentStream.appendRawCommands("T*\n");
}
}
} else {
contentStream.drawString(text);
}
contentStream.endText();
textx += (colWidths != null) ? colWidths[j] : colWidth;
}
texty-=rowHeight;
textx = margin+cellMargin;
}
}
@vvolkgang
Copy link

You'll get an Index Out Of Bounds in line 22 if you use the colWidths, because the for loop in line 20 has a <= instead of a <

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment