我创建了一个pdf,其中有一个表,但如果字符串的长度超过那么我想使用新行。
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;
}
}
我尝试比较字符串和列宽的长度,但它不起作用。我不知道如何在下一行显示半字符串。
答案 0 :(得分:0)
实际上只看到这件事对我有用,
String text = content[i][j];
List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
strings.add(text.substring(index, Math.min(index + 25,text.length())));
index += 25;
}
for (String line: strings){
contentStream.showText(line);
contentStream.newLineAtOffset(0, -leading);
}
但是在这里我不知道如何增加有很多字符的行的高度。