Domanda

Sto usando la libreria Java Apache PDFBox per creare file PDF. C'è un modo per creare un data-tabella utilizzando PDFBox? Se non c'è tale API per farlo, mi richiederebbe di disegnare manualmente la tabella utilizzando drawLine ecc, qualche suggerimento su come andare su questo?

È stato utile?

Soluzione

Sorgente : tavoli creando con PDFBox

Il metodo seguente disegna una tabella con il contenuto della tabella specificato. È un po 'un hack e lavorerà per piccole stringhe di testo. Esso non esegue il ritorno a capo, ma si può avere un'idea di come è fatto. Dategli un andare!

/**
 * @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;
    }
}

Utilizzo:

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" );

Altri suggerimenti

ho creato una piccola API per la creazione di tabelle utilizzando PDFBox. Si può trovare su github ( https://github.com/dhorions/boxable ).

Un campione di un PDF generato può essere trovato qui http://goo.gl/a7QvRM .

Eventuali suggerimenti o suggerimenti sono i benvenuti.

La risposta accettata è bello, ma che possa funzionare con Apache PDFBox 1.x solo, per Apache 2.x PDFBox è necessario modificare un po 'il codice per farlo funzionare correttamente.

Così qui è lo stesso codice, ma che è compatibile con Apache 2.x PDFBox :

Il metodo 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;
    }
}

L'uso aggiornato per utilizzare il try-con-le risorse dichiarazione per chiudere le risorse correttamente:

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");
}

Da quando ho avuto lo stesso problema qualche tempo fa ho iniziato a costruire una piccola biblioteca per questo che sto anche cercando di tenersi aggiornati.

Utilizza Apache 2.x PDFBox e può essere trovato qui: https://github.com/vandeseer/easytable

Permette per un po 'personalizzazioni come l'impostazione del tipo di carattere, colore di sfondo, imbottitura ecc a livello cellulare, l'allineamento verticale e orizzontale, spanning delle cellule, il ritorno a capo e le immagini nelle celle.

Disegno tabelle su diverse pagine è anche possibile.

È possibile creare tabelle in questo modo, per esempio:

 entrare descrizione dell'immagine qui

Il codice di questo esempio può essere trovato qui - altri esempi nella stessa cartella pure.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top