如何解决使用java中的PDFBox在pdf表格单元格中自动换行
我正在使用 Java 中的 PDFBox 库创建 pdf 格式的表格。我能够绘制表格并在表格中填充数据,但在单元格中有很长的数据可用,我需要进行自动换行。 在我的项目中,不允许使用其他库,我们只能使用 PDFBox 来完成。
PDFBox 版本为 2.0.22
这是我正在使用的代码,
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class Test2 {
private static final String[] PARKING_SPACE_REPORT_HEADERS = { "PARKING SPACE NAME","PARKING SPACE ADDRESS","APPROVED/REJECTED ON" };
public static void main(String[] args) throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc,page);
String[][] content = { { "Bini k","TEST1","01-Sep-2020 01:57 PM" },{ "c","Job Description: Lorem ipsum dolor sit knajdsn kabsjflsnijasd kjdoisaosd sisa saihsihsahc sassah","2" },{ "e","f","3" },{ "g","h","4" },{ "i","j","5" } };
drawTable(page,contentStream,700,100,content);
contentStream.close();
doc.save("C:\\software\\hello1030.pdf");
}
public static void drawTable(PDPage page,PDPageContentStream contentStream,float y,float margin,String[][] content) throws IOException {
final int rows = content.length + 1;
final int cols = content[0].length;
final float rowHeight = 20f;
final float tableWidth = page.getMediaBox().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.moveTo(margin,nexty);
contentStream.lineTo(margin + tableWidth,nexty);
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.stroke();
nextx += colWidth;
}
// now add the text
contentStream.setFont(PDType1Font.TIMES_ROMAN,12);
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.newLineAtOffset(textx,texty);
if (text.length() > 20) {
printMultipleLines(text,contentStream);
textx += colWidth;
contentStream.endText();
continue;
}
contentStream.showText(text);
contentStream.endText();
textx += colWidth;
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}
private static void printMultipleLines(String line,PDPageContentStream contentStream) {
try {
// Print line as 2 lines
contentStream.showText(line.substring(0,90));
contentStream.newLine();
contentStream.showText(line.substring(90,line.length()));
} catch (IOException e) {
e.printStackTrace();
}
} }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。