Question

J'utilise la bibliothèque java Apache PDFBox à créer des fichiers PDF. Est-il possible de créer un tableau de données à l'aide PDFBox? S'il n'y a pas l'API pour le faire, je requiers pour dessiner manuellement la table à l'aide drawLine etc., Toutes les suggestions sur la façon d'aller à ce sujet?

Était-ce utile?

La solution

Source : Création de tables avec PDFBox

Le procédé suivant dessine une table avec le contenu de la table spécifiée. C'est un peu un hack et travaillera pour les petites chaînes de texte. Il ne fonctionne pas de mot emballage, mais vous pouvez avoir une idée de la façon dont il est fait. Donnez-lui un aller!

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

Utilisation:

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

Autres conseils

J'ai créé une petite api pour créer des tables à l'aide PDFBox. Il se trouve sur GitHub ( https://github.com/dhorions/boxable ).

Vous trouverez un échantillon d'un pdf généré ici http://goo.gl/a7QvRM .

Les conseils ou suggestions sont les bienvenus.

La réponse acceptée est agréable mais il fonctionnera avec Apache PDFBox 1.x uniquement Apache 2.x PDFBox , vous aurez besoin de modifier un peu le code pour le faire fonctionner correctement.

Voici donc le même code mais qui est compatible avec Apache 2.x PDFBox :

La méthode 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'utilisation mis à jour pour utiliser le essayer avec-ressources déclaration pour fermer les ressources correctement:

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

Depuis que j'ai eu le même problème il y a quelque temps j'ai commencé à construire une petite bibliothèque pour ce que je suis aussi en train de tenir à jour.

Il utilise Apache 2.x PDFBox et peuvent être trouvés ici: https://github.com/vandeseer/easytable

Il permet tout à fait quelques personnalisations comme le réglage de la police, la couleur de fond, etc. rembourrage au niveau cellulaire, l'alignement vertical et horizontal, Spanning cellulaire, emballage texte et des images dans les cellules.

tables à dessin sur plusieurs pages est également possible.

Vous pouvez créer des tableaux comme celui-ci par exemple:

 entrer image description ici

Le code de cet exemple peut être trouvé ici - d'autres exemples dans le même dossier ainsi.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top