IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Java Discussion :

Problème de positionnement d'un text dans un PDF


Sujet :

API standards et tierces Java

  1. #1
    Membre éclairé
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    350
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2006
    Messages : 350
    Par défaut Problème de positionnement d'un text dans un PDF
    Bonjour,

    J'utilise l' API iText pour générer des PDF, je définit une entête pour le fichier et j'y ajoute une ligne.

    Le problème c'est que la ligne s'écrit sur l'entête et je vois pas comment la faire descendre (voir pièce jointe SVP).

    Voici mon code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Element;
    import com.lowagie.text.ExceptionConverter;
    import com.lowagie.text.Font;
    import com.lowagie.text.Image;
    import com.lowagie.text.PageSize;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.Phrase;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.ColumnText;
    import com.lowagie.text.pdf.PdfPCell;
    import com.lowagie.text.pdf.PdfPTable;
    import com.lowagie.text.pdf.PdfPageEventHelper;
    import com.lowagie.text.pdf.PdfTemplate;
    import com.lowagie.text.pdf.PdfWriter;
    import java.awt.event.FocusAdapter;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.sql.SQLException;
     
    public class MovieCountries1 {
     
        /** The resulting PDF file. */
        public static final String RESULT
            = "movie_countries1.pdf";
     
        /**
         * Inner class to add a table as header.
         */
        class TableHeader extends PdfPageEventHelper {
            /** The header text. */
            String header;
            /** The template with the total number of pages. */
            PdfTemplate total;
     
            /**
             * Allows us to change the content of the header.
             * @param header The new header String
             */
            public void setHeader(String header) {
                this.header = header;
            }
     
            /**
             * Creates the PdfTemplate that will hold the total number of pages.
             * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(
             *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
             */
            public void onOpenDocument(PdfWriter writer, Document document) {
                total = writer.getDirectContent().createTemplate(30, 16);
            }
     
            /**
             * Adds a header to every page
             * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
             *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
             */
            public void onEndPage(PdfWriter writer, Document document) {
                PdfPTable table = new PdfPTable(3);
                try {
                    table.setWidths(new int[]{24, 24, 2});
                    table.setTotalWidth(527);
                    table.setLockedWidth(true);
                    table.getDefaultCell().setFixedHeight(50);
                    table.getDefaultCell().setBorder(Rectangle.BOTTOM);
                    table.addCell(header);
                    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                    table.addCell(String.format("Page %d of", writer.getPageNumber()));
                    PdfPCell cell = new PdfPCell(Image.getInstance(total));
                    cell.setBorder(Rectangle.BOTTOM);
                    table.addCell(cell);
                    table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
                }
                catch(DocumentException de) {
                    throw new ExceptionConverter(de);
                }
            }
     
            /**
             * Fills out the total number of pages before the document is closed.
             * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(
             *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
             */
            public void onCloseDocument(PdfWriter writer, Document document) {
                ColumnText.showTextAligned(total, Element.ALIGN_LEFT,
                        new Phrase(String.valueOf(writer.getPageNumber() - 1)),
                        2, 2, 0);
            }
        }
     
        /**
         * Creates a PDF document.
         * @param filename the path to the new PDF document
         * @throws    DocumentException
         * @throws    IOException
         * @throws    SQLException
         */
        public void createPdf(String filename)
            throws IOException, DocumentException, SQLException {
            // step 1
            Document document = new Document(PageSize.A4, 36, 36, 54, 36);
            // step 2
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
            TableHeader event = new TableHeader();
            writer.setPageEvent(event);
            // step 3
            document.open();
            // step 4
            for (int i =0 ; i<2; i++) {
                StringBuilder sb = new StringBuilder();
                sb.append("entete de la page22");
                sb.append("\n");
                sb.append("amine rachid");
                sb.append("\n");
                sb.append("test entete");
                event.setHeader(sb.toString());
                //for(int j= 0; j<4;j++) {
                    Paragraph paragraph = new Paragraph();
                    paragraph.setSpacingBefore(500);
                    //paragraph.set
                    document.add((new Paragraph("Original1111::: ")));
                  //  document.add(new Paragraph("Original2222::: " +j));
                  //  document.add(new Paragraph("Original3333::: " +j));
                //}
                document.newPage();
            }
            // step 4
            document.close();
        }
     
        /**
         * Main method.
         *
         * @param    args    no arguments needed
         * @throws DocumentException
         * @throws IOException
         * @throws SQLException
         */
        public static void main(String[] args)
            throws IOException, DocumentException, SQLException {
            new MovieCountries1().createPdf(RESULT);
        }
    }
    Merci d'avance pour votre aide.
    Images attachées Images attachées

  2. #2
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Décembre 2003
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Santé

    Informations forums :
    Inscription : Décembre 2003
    Messages : 50
    Par défaut
    peut-être en ajoutant des marges au document.

    doc.setMargins(15,15,15,15); par exemple.

  3. #3
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Décembre 2003
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Santé

    Informations forums :
    Inscription : Décembre 2003
    Messages : 50
    Par défaut
    Désolé pour ma première réponsen je n'avais pas vu le constructeur.

    et en utilisant la méthode setHeader de l'objet Document.

  4. #4
    Membre éclairé
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    350
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2006
    Messages : 350
    Par défaut
    Merci pour la réponse mais apparemment t'as pas comprit mon problème.

    J'ai déja définit le headre de mon document en utilisant event.setHeader(sb.toString());

    Le problème que j'ai c'est que lorsque je veux ajouter un texte après le header le texte s'écrit sur le header comme c'est indiqué dans la pièce jointe.

    Merci d'avance.

  5. #5
    Membre confirmé
    Homme Profil pro
    Développeur Java
    Inscrit en
    Décembre 2003
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Santé

    Informations forums :
    Inscription : Décembre 2003
    Messages : 50
    Par défaut
    Bonjour,

    Voici un bout de code qui fonctionne pour l'ajout d'un header sur un pdf.

    Pour que cela fonctionne bien, le header doit être ajouté avant l'ouverture de ton objet document (document.open()). Ensuite tu peux ajouter les paragraph ou phrase qui conviennent.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    final Paragraph info = new Paragraph("Mon texte header");
            final HeaderFooter header = new HeaderFooter(info, false);
            header.setBorder(0);
            doc.setHeader(header);
            doc.open();
            doc.add((new Paragraph("Original1111::: ")));
    Dis moi si ça marche.

  6. #6
    Membre éclairé
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    350
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2006
    Messages : 350
    Par défaut
    Bonjour,

    Merci pour votre réponse, oui ça fonctionne bien , j'ai déjà essayé ça mais j'avais un souci de comment ajouter le header et footer en même temps.

    Voici un code qui permet d'ajouter les deux en même temps.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
     public static void main(String[] args) throws FileNotFoundException {
       Document document = new Document(PageSize.A4);
     
     
    		try{
    			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
     
     
     
     
    //			Ajout de l'entête
    			Paragraph para1 = new Paragraph();
    			para1.add("Entete du fichier PDF");
    			HeaderFooter header = new HeaderFooter(para1,false);
    			header.setAlignment(HeaderFooter.ALIGN_CENTER);
    			document.setHeader(header);
     
    //			Ajout du pied de page
    			Paragraph para2 = new Paragraph();
    			para2.add("Pied de page du fichier PDF");
    			HeaderFooter footer = new HeaderFooter(para2,false);
    			footer.setAlignment(HeaderFooter.ALIGN_CENTER);
    			document.setFooter(footer);
     
                            writer.close();
                            document.open();
                            document.newPage();
     
     
    			//Image img = Image.getInstance("Workspace/win/WebContent/images/zoomold.jpg");
    			//img.scalePercent(100);
    			Phrase h1 = new Phrase("header 1");
    			Phrase h2 = new Phrase("header 2");
    			//HeaderFooter header = new HeaderFooter(h1,h2);
    			//document.setHeader(header);
    			Phrase f1 = new Phrase("footer 1");
    			Phrase f2 = new Phrase("footer 2");
    			//HeaderFooter footer = new HeaderFooter(f1,f2);
    			//document.setFooter(footer);
    			//document.add(header);
    			//document.add(footer);
                            int numTransaction = 1560;
                            String titreEdTransaction = "l3onwan dyam transaction";
                            String numVoie = "30021";
                            String typeVoie ="9002";
                            String nomVoie = "Zen9at lbo3ara";
                            String codePostal = "20600";
                            String commune = "Bernoussi";
                            String prenomNego = "Rachid";
                            String nomNego = "AMINE";
    			Font fontRed = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL, new Color(255,0,0));
    			Font fontTitre =  new Font(Font.HELVETICA,Font.DEFAULTSIZE,Font.BOLD);
    			Font fontLibelle =  new Font(Font.HELVETICA,8,Font.NORMAL);
    			Phrase libNumTrans = new Phrase("Numéro de transaction :",fontLibelle);
    			Phrase intNumTrans = new Phrase(String.valueOf(numTransaction),fontLibelle);
    			Phrase titre = new Phrase("Photo du bien",fontRed);
    			PdfPTable table = new PdfPTable(2);
    			PdfPCell cell = new PdfPCell(new Paragraph(titreEdTransaction,fontTitre));
    			Cell celltest = new Cell(cell);
    			cell.setColspan(2);
    			cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
    			cell.setVerticalAlignment(Cell.ALIGN_CENTER);
    			celltest.setHeader(true);
    			table.addCell(cell);
    			table.addCell(libNumTrans);
    			table.addCell(intNumTrans);
    			table.addCell("Adresse : ");
    			table.addCell(numVoie.trim()+", "+typeVoie.trim()+" "+nomVoie.trim()+", "+codePostal.trim()+" "+commune.trim());
    			table.addCell("Négociateur : ");
    			table.addCell(prenomNego.trim()+" "+nomNego.trim());
    			table.addCell(titre);
    			//table.addCell(img);
    			document.add(table);
    			PdfPTable tableCustomized = new PdfPTable(3);
    			PdfPTable tableNested = new PdfPTable(6);
    			Phrase type = new Phrase("Type :",fontLibelle);
    			Phrase surface = new Phrase("Surface :",fontLibelle);
    			Phrase venteloc = new Phrase("Vente / Location :",fontLibelle);
    			tableNested.addCell(type);
    			tableNested.addCell(surface);
    			tableNested.addCell(venteloc);
    			tableNested.addCell("Bureau");
    			tableNested.addCell("5000 m²");
    			tableNested.addCell("Vente");
    			tableCustomized.setTotalWidth(40);
    			PdfPCell cellule = new PdfPCell(new Paragraph("test table",fontTitre));
    			cellule.setBackgroundColor(new Color(0,255,255));
    			cellule.setBorder(0);
    			tableCustomized.addCell(cellule);
    			tableCustomized.addCell("fffff");
    			tableCustomized.addCell("ddedede");
    			tableCustomized.addCell("jryjyjtjtyjtjty");
    			tableCustomized.addCell("ffhyjjuj");
    			tableCustomized.addCell(tableNested);
    			document.add(tableCustomized);
    			PdfPTable tableDyn = new PdfPTable(2);
    			tableDyn.setWidthPercentage(50);
    			//tableDyn.setHorizontalAlignment(80);
    			//tableDyn.setTotalWidth(25);
     
     
     
     
    				Phrase numTrans = new Phrase("NUM_TRANSACTION::2",fontLibelle);
    				PdfPCell celluleNumTrans = new PdfPCell(new Paragraph(numTrans));
    				celluleNumTrans.setBackgroundColor(new Color(255,0,0));
    				celluleNumTrans.setBorder(0);
    				tableDyn.addCell(celluleNumTrans);
    			        Phrase localCommune = new Phrase("LOCAL_COMMUNE::3",fontLibelle);
    				 tableDyn.addCell(localCommune);
     
    			document.add(tableDyn);
    			document.close();
    		} catch(DocumentException de){
    			System.out.println("Pb PDF : "+de);
    		}
    	}
      }
    J'espère que ça vous aide.

    Merci encore une fois.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. problème de "load" des fichiers textes dans un exe
    Par guefrachi dans le forum MATLAB
    Réponses: 8
    Dernier message: 13/10/2010, 15h21
  2. Problème pour centrer verticalement le texte dans un menu
    Par Greg12345 dans le forum Mise en page CSS
    Réponses: 5
    Dernier message: 26/05/2010, 19h43
  3. Problème de positionnement de balise object dans un DIV
    Par C moa dans le forum Mise en page CSS
    Réponses: 1
    Dernier message: 25/11/2007, 11h28
  4. Réponses: 4
    Dernier message: 17/07/2007, 16h49
  5. problème d'attribution d'un texte dans un widget text
    Par polo42 dans le forum Général Python
    Réponses: 5
    Dernier message: 11/07/2007, 08h34

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo