gpt4 book ai didi

java - Apache PDFBox Java 库 - 是否有用于创建表格的 API?

转载 作者:IT老高 更新时间:2023-10-28 21:18:10 24 4
gpt4 key购买 nike

我正在使用 Apache PDFBox java 库来创建 PDF。有没有办法使用 pdfbox 创建数据表?如果没有这样的 API 可以做到这一点,我需要使用 drawLine 等手动绘制表格,有什么建议可以解决这个问题吗?

最佳答案

来源:Creating tables with PDFBox

下面的方法用指定的表格内容绘制表格。它有点小技巧,适用于小文本字符串。它不执行自动换行,但您可以了解它是如何完成的。试一试!

/**
* @param page
* @param contentStream
* @param y the y-coordinate of the first row
* @param margin the padding on left and right of table
* @param content a 2d array containing the table data
* @throws IOException
*/
public static void drawTable(PDPage page, PDPageContentStream contentStream,
float y, float margin,
String[][] content) throws IOException {
final int rows = content.length;
final int cols = content[0].length;
final float rowHeight = 20f;
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 += colWidth;
}

//now add the text
contentStream.setFont( PDType1Font.HELVETICA_BOLD , 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.moveTextPositionByAmount(textx,texty);
contentStream.drawString(text);
contentStream.endText();
textx += colWidth;
}
texty-=rowHeight;
textx = margin+cellMargin;
}
}

用法:

PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage( page );

PDPageContentStream contentStream = new PDPageContentStream(doc, page);

String[][] content = {{"a","b", "1"},
{"c","d", "2"},
{"e","f", "3"},
{"g","h", "4"},
{"i","j", "5"}} ;

drawTable(page, contentStream, 700, 100, content);
contentStream.close();
doc.save("test.pdf" );

关于java - Apache PDFBox Java 库 - 是否有用于创建表格的 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3871879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com