I have created a pdf where I have a table but if the length of the string exceeds then I want to use new line.
public static void drawtable1(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content) throws IOException {
int rows = content.length;
int cols = content[0].length;
float rowHeight = 20f;
float tableWidth = page.getMediaBox().getWidth() - margin - margin;
float tableHeight = rowHeight * rows;
float colWidth = tableWidth / (float)cols;
float cellMargin = 5f;
PDFont font1 = PDType1Font.HELVETICA_BOLD;
PDFont font2 = PDType1Font.HELVETICA;
//draw the rows
float nexty = y;
for (int i = 0; i <= rows; i++) {
contentStream.moveTo(margin, nexty);
contentStream.lineTo(margin + tableWidth, nexty);
contentStream.setStrokingColor(220,220,220);
contentStream.stroke();
nexty -= rowHeight;
}
//draw the columns
float nextx = margin;
for (int i = 0; i <= cols ; i++) {
contentStream.moveTo(nextx, y);
contentStream.lineTo(nextx, y - tableHeight);
contentStream.setStrokingColor(220,220,220);
contentStream.stroke();
// contentStream.stroke();
if(content[0].length == 2){
if(i==0){
nextx += colWidth/2;
}if(i == 1){
nextx += colWidth + colWidth/2;
}
}else{
nextx += colWidth;
}
}
//now add the text
contentStream.setFont(PDType1Font.HELVETICA, 10);
float textx = margin + cellMargin;
float texty = y - 15;
float col = tableWidth / (float)cols;
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.setLeading(12.5f);
contentStream.newLineAtOffset(textx, texty);
if (j == 0 || j == 2){
if(font1.getStringWidth(content[i][j]) > col){
System.out.println(content[i][j]);
}
contentStream.setFont(font1, 10);
contentStream.showText(text);
contentStream.setFont(font2, 10);
}else{
contentStream.showText(text);
}
contentStream.endText();
if(content[0].length == 2){
if(j==0){
textx += colWidth/2;
}
if(j == 1){
textx += colWidth + colWidth/2;
}
}else{
textx += colWidth;
}
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}
I tried comparing the length of the string and column width but it is not working. I have no idea how to display half string in the next line.