私はApachePDFBoxJavaライブラリを使用してPDFを作成しています。pdfboxを使用してデータテーブルを作成する方法はありますか?そのようなAPIがない場合は、drawLineなどを使用して手動でテーブルを描画する必要があります。これを実行する方法についての提案はありますか?
32084 次
4 に答える
26
ソース: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" );
于 2010-10-06T13:17:36.903 に答える
16
PDFBox を使用してテーブルを作成するための小さな API を作成しました。これは github ( https://github.com/dhorions/boxable ) にあります。
生成された PDF のサンプルは、 http: //goo.gl/a7QvRMにあります。
ヒントや提案は大歓迎です。
于 2014-03-08T07:46:24.787 に答える