Skip to content

Instantly share code, notes, and snippets.

@scobal
Created July 31, 2013 19:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save scobal/6125427 to your computer and use it in GitHub Desktop.
Save scobal/6125427 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;
}
}
@jrobertsz66
Copy link

your function has an ArrayOutofBoundsException for the columns and when I fix that id runs and creates the PDF table but the text is not wrapped.

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