Biblioteca Apache PDFbox Java - Existe uma API para criar tabelas?
Pergunta
Estou usando a biblioteca Java Apache PDFbox para criar PDFs. Existe uma maneira de criar uma mesa de dados usando PDFBox? Se não houver essa API para fazê -lo, eu precisaria desenhar manualmente a mesa usando a linha de drawline etc., alguma sugestão sobre como fazer isso?
Solução
Fonte: Criando mesas com PDFBox
O método a seguir desenha uma tabela com o conteúdo da tabela especificado. É um pouco de hack e trabalhará para pequenas cordas de texto. Ele não executa o embrulho de palavras, mas você pode ter uma idéia de como isso é feito. Dê uma chance!
/**
* @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;
}
}
Uso:
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" );
Outras dicas
Criei uma pequena API para criar tabelas usando PDFBox. Pode ser encontrado no github ( https://github.com/dhorions/boxable ) .
Uma amostra de um PDF gerado pode ser encontrada aqui http://goo.gl/a7qvrm.
Quaisquer dicas ou sugestões são bem -vindas.
A resposta aceita é boa, mas funcionará com Apache PDFBox 1.x apenas para Apache PDFbox 2.x Você precisará modificar um pouco o código para fazê -lo funcionar corretamente.
Então, aqui está o mesmo código, mas isso é compatível com Apache PDFbox 2.x:
O método drawTable
:
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 = 20.0f;
final float tableWidth = page.getMediaBox().getWidth() - 2.0f * margin;
final float tableHeight = rowHeight * (float) rows;
final float colWidth = tableWidth / (float) cols;
//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.HELVETICA_BOLD, 12.0f);
final float cellMargin = 5.0f;
float textx = margin + cellMargin;
float texty = y - 15.0f;
for (final String[] aContent : content) {
for (String text : aContent) {
contentStream.beginText();
contentStream.newLineAtOffset(textx, texty);
contentStream.showText(text);
contentStream.endText();
textx += colWidth;
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}
O uso atualizado para usar o Tente-com resmunção declaração para fechar os recursos corretamente:
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
try (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.0f, 100.0f, content);
}
doc.save("test.pdf");
}
Desde que tive o mesmo problema há algum tempo, comecei a construir uma pequena biblioteca que também estou tentando me manter atualizada.
Ele usa Apache PDFbox 2.x e pode ser encontrado aqui:https://github.com/vandeseer/easytable
Ele permite algumas personalizações, como definir a fonte, cor de fundo, preenchimento etc. no nível da célula, alinhamento vertical e horizontal, abrangência de células, embrulho de palavras e imagens nas células.
Também é possível desenhar mesas em várias páginas.
Você pode criar tabelas como esta, por exemplo:
O código para este exemplo pode ser encontrado aqui - Outros exemplos na mesma pasta também.