begin process at 2010 02 10 01:19:33
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Api

 > CREER UN PDF AVEC XML ET FOP

CREER UN PDF AVEC XML ET FOP


 Information sur la source

Note :
5,14 / 10 - par 7 personnes
5,14 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Api Classé sous :xml, fop, pdf, création, génération Niveau :Débutant Date de création :15/05/2003 Date de mise à jour :07/07/2004 21:19:54 Vu :37 331

Auteur : lolofx

Ecrire un message privé
Commentaire sur cette source (18)
Ajouter un commentaire et/ou une note

 Description

Ce code permet de creer un document pdf avec un fichier xml et une feuille de style xsl et l'API fop
il est simple et marche avec tout fichier xml si la feuille xsl est bien faite


Source

  • /*
  • * $Id$
  • * ============================================================================
  • * The Apache Software License, Version 1.1
  • * ============================================================================
  • *
  • * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  • *
  • * Redistribution and use in source and binary forms, with or without modifica-
  • * tion, are permitted provided that the following conditions are met:
  • *
  • * 1. Redistributions of source code must retain the above copyright notice,
  • * this list of conditions and the following disclaimer.
  • *
  • * 2. Redistributions in binary form must reproduce the above copyright notice,
  • * this list of conditions and the following disclaimer in the documentation
  • * and/or other materials provided with the distribution.
  • *
  • * 3. The end-user documentation included with the redistribution, if any, must
  • * include the following acknowledgment: "This product includes software
  • * developed by the Apache Software Foundation (http://www.apache.org/)."
  • * Alternately, this acknowledgment may appear in the software itself, if
  • * and wherever such third-party acknowledgments normally appear.
  • *
  • * 4. The names "FOP" and "Apache Software Foundation" must not be used to
  • * endorse or promote products derived from this software without prior
  • * written permission. For written permission, please contact
  • * apache@apache.org.
  • *
  • * 5. Products derived from this software may not be called "Apache", nor may
  • * "Apache" appear in their name, without prior written permission of the
  • * Apache Software Foundation.
  • *
  • * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  • * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  • * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  • * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  • * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
  • * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  • * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  • * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  • * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  • * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  • * ============================================================================
  • *
  • * This software consists of voluntary contributions made by many individuals
  • * on behalf of the Apache Software Foundation and was originally created by
  • * James Tauber <jtauber@jtauber.com>. For more information on the Apache
  • * Software Foundation, please see <http://www.apache.org/>.
  • */
  • package embedding;
  • //Java
  • import java.io.File;
  • import java.io.IOException;
  • import java.io.OutputStream;
  • //JAXP
  • import javax.xml.transform.Transformer;
  • import javax.xml.transform.TransformerFactory;
  • import javax.xml.transform.TransformerException;
  • import javax.xml.transform.Source;
  • import javax.xml.transform.Result;
  • import javax.xml.transform.stream.StreamSource;
  • import javax.xml.transform.sax.SAXResult;
  • //Avalon
  • import org.apache.avalon.framework.ExceptionUtil;
  • import org.apache.avalon.framework.logger.ConsoleLogger;
  • import org.apache.avalon.framework.logger.Logger;
  • //FOP
  • import org.apache.fop.apps.Driver;
  • import org.apache.fop.apps.FOPException;
  • import org.apache.fop.messaging.MessageHandler;
  • /**
  • * This class demonstrates the conversion of an XML file to PDF using
  • * JAXP (XSLT) and FOP (XSL:FO).
  • */
  • public class ExampleXML2PDF {
  • public void convertXML2PDF(File xml, File xslt, File pdf)
  • throws IOException, FOPException, TransformerException {
  • //Construct driver
  • Driver driver = new Driver();
  • //Setup logger
  • Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
  • driver.setLogger(logger);
  • MessageHandler.setScreenLogger(logger);
  • //Setup Renderer (output format)
  • driver.setRenderer(Driver.RENDER_PDF);
  • //Setup output
  • OutputStream out = new java.io.FileOutputStream(pdf);
  • try {
  • driver.setOutputStream(out);
  • //Setup XSLT
  • TransformerFactory factory = TransformerFactory.newInstance();
  • Transformer transformer = factory.newTransformer(new StreamSource(xslt));
  • //Setup input for XSLT transformation
  • Source src = new StreamSource(xml);
  • //Resulting SAX events (the generated FO) must be piped through to FOP
  • Result res = new SAXResult(driver.getContentHandler());
  • //Start XSLT transformation and FOP processing
  • transformer.transform(src, res);
  • } finally {
  • out.close();
  • }
  • }
  • public static void main(String[] args) {
  • try {
  • System.out.println("FOP ExampleXML2PDF ");
  • System.out.println("Preparing...");
  • //Setup directories
  • File baseDir = new File(".");
  • File outDir = new File(baseDir, "out");
  • outDir.mkdirs();
  • //Setup input and output files
  • File xmlfile = new File(baseDir, "xml/xml/projectteam.xml");
  • File xsltfile = new File(baseDir, "xml/xslt/projectteam2FO.xsl");
  • File pdffile = new File(outDir, "ResultXML2PDF.pdf");
  • System.out.println("Input: XML (" + xmlfile + ")");
  • System.out.println("Stylesheet: " + xsltfile);
  • System.out.println("Output: PDF (" + pdffile + ")");
  • System.out.println();
  • System.out.println("Transforming...");
  • ExampleXML2PDF app = new ExampleXML2PDF();
  • app.convertXML2PDF(xmlfile, xsltfile, pdffile);
  • System.out.println("Success!");
  • } catch (Exception e) {
  • System.err.println(ExceptionUtil.printStackTrace(e));
  • System.exit(-1);
  • }
  • }
  • }
/*
* $Id$
* ============================================================================
*                    The Apache Software License, Version 1.1
* ============================================================================
* 
* Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
* 
* 1. Redistributions of source code must retain the above copyright notice,
*    this list of conditions and the following disclaimer.
* 
* 2. Redistributions in binary form must reproduce the above copyright notice,
*    this list of conditions and the following disclaimer in the documentation
*    and/or other materials provided with the distribution.
* 
* 3. The end-user documentation included with the redistribution, if any, must
*    include the following acknowledgment: "This product includes software
*    developed by the Apache Software Foundation (http://www.apache.org/)."
*    Alternately, this acknowledgment may appear in the software itself, if
*    and wherever such third-party acknowledgments normally appear.
* 
* 4. The names "FOP" and "Apache Software Foundation" must not be used to
*    endorse or promote products derived from this software without prior
*    written permission. For written permission, please contact
*    apache@apache.org.
* 
* 5. Products derived from this software may not be called "Apache", nor may
*    "Apache" appear in their name, without prior written permission of the
*    Apache Software Foundation.
* 
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
* DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
* 
* This software consists of voluntary contributions made by many individuals
* on behalf of the Apache Software Foundation and was originally created by
* James Tauber <jtauber@jtauber.com>. For more information on the Apache
* Software Foundation, please see <http://www.apache.org/>.
*/ 
package embedding;

//Java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;

//Avalon
import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;

//FOP
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;

/**
* This class demonstrates the conversion of an XML file to PDF using 
* JAXP (XSLT) and FOP (XSL:FO).
*/
public class ExampleXML2PDF {

    public void convertXML2PDF(File xml, File xslt, File pdf) 
                throws IOException, FOPException, TransformerException {
        //Construct driver
        Driver driver = new Driver();
        
        //Setup logger
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
        driver.setLogger(logger);
        MessageHandler.setScreenLogger(logger);

        //Setup Renderer (output format)        
        driver.setRenderer(Driver.RENDER_PDF);
        
        //Setup output
        OutputStream out = new java.io.FileOutputStream(pdf);
        try {
            driver.setOutputStream(out);

            //Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xslt));
        
            //Setup input for XSLT transformation
            Source src = new StreamSource(xml);
        
            //Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(driver.getContentHandler());

            //Start XSLT transformation and FOP processing
            transformer.transform(src, res);
        } finally {
            out.close();
        }
    }


    public static void main(String[] args) {
        try {
            System.out.println("FOP ExampleXML2PDF ");
            System.out.println("Preparing...");

            //Setup directories
            File baseDir = new File(".");
            File outDir = new File(baseDir, "out");
            outDir.mkdirs();

            //Setup input and output files            
            File xmlfile = new File(baseDir, "xml/xml/projectteam.xml");
            File xsltfile = new File(baseDir, "xml/xslt/projectteam2FO.xsl");
            File pdffile = new File(outDir, "ResultXML2PDF.pdf");

            System.out.println("Input: XML (" + xmlfile + ")");
            System.out.println("Stylesheet: " + xsltfile);
            System.out.println("Output: PDF (" + pdffile + ")");
            System.out.println();
            System.out.println("Transforming...");
            
            ExampleXML2PDF app = new ExampleXML2PDF();
            app.convertXML2PDF(xmlfile, xsltfile, pdffile);
            
            System.out.println("Success!");
        } catch (Exception e) {
            System.err.println(ExceptionUtil.printStackTrace(e));
            System.exit(-1);
        }
    }
}



 Sources du même auteur

XSL VERS HTML VIA JAVA
XSL:FO API FOP
CREER UN FICHIER XML AVEC DOM ET U E BASE DE DONNEES
CREER UNE PAGE HTML GRACE A UNE FEUILLE DE STYLE XSL, UN FIC...

 Sources de la même categorie

ENVOI D'UNE ARBORESSENCE EN JAVA VERS SERVEUR FTP par moumou95
ENREGISTRER L'ARBORESCENCE D'UN JTREE DANS UN XML AVEC JDOM par coltman
Source avec Zip WIZARD JAVA API par aissam36
JCONFIGURATIONMANAGER - GESTION DES CONFIGURATIONS par Francks11
Source avec Zip Source avec une capture FRAGMENTER, DÉFRAGMENTER UN FICHIER par Chatbour

 Sources en rapport avec celle ci

Source avec Zip JAVA SERVER PAGE par pasteure
Source avec Zip Source avec une capture IHM CONFIGURABLE POUR FICHIER PROPERTIES par benmor
ENREGISTRER L'ARBORESCENCE D'UN JTREE DANS UN XML AVEC JDOM par coltman
XSL:FO API FOP par lolofx
CREER UNE PAGE HTML GRACE A UNE FEUILLE DE STYLE XSL, UN FIC... par lolofx

Commentaires et avis

Commentaire de alex1er le 27/06/2003 11:36:39

Salut
J'ai entendu parler de FOP et ton code à l'air bien.
Pourrais tu m'envoyer par mail en fichier XML et XSL pour voir la tete qu'ils ont et pour tester ton programme.

MErci pour ta source

Commentaire de Dobel le 24/10/2003 18:29:53

Euh tiens, il me semble avoir déjà vu ce code quelque part...
ah oui mais il y avait une license au début si je m'en rappelle bien...
fichier ExampleXML2PDF.java dans les exemples de l'API FOP
;-((

l'original :


/*
* $Id$
* ============================================================================
*                    The Apache Software License, Version 1.1
* ============================================================================
*
* Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
*    this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
*    this list of conditions and the following disclaimer in the documentation
*    and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
*    include the following acknowledgment: "This product includes software
*    developed by the Apache Software Foundation (http://www.apache.org/)."
*    Alternately, this acknowledgment may appear in the software itself, if
*    and wherever such third-party acknowledgments normally appear.
*
* 4. The names "FOP" and "Apache Software Foundation" must not be used to
*    endorse or promote products derived from this software without prior
*    written permission. For written permission, please contact
*    apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache", nor may
*    "Apache" appear in their name, without prior written permission of the
*    Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
* DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Apache Software Foundation and was originally created by
* James Tauber &lt;jtauber@jtauber.com&gt;. For more information on the Apache
* Software Foundation, please see &lt;http://www.apache.org/&gt;.
*/
package embedding;

//Java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;

//Avalon
import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;

//FOP
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;

/**
* This class demonstrates the conversion of an XML file to PDF using
* JAXP (XSLT) and FOP (XSL:FO).
*/
public class ExampleXML2PDF {

    public void convertXML2PDF(File xml, File xslt, File pdf)
                throws IOException, FOPException, TransformerException {
        //Construct driver
        Driver driver = new Driver();
        
        //Setup logger
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
        driver.setLogger(logger);
        MessageHandler.setScreenLogger(logger);

        //Setup Renderer (output format)        
        driver.setRenderer(Driver.RENDER_PDF);
        
        //Setup output
        OutputStream out = new java.io.FileOutputStream(pdf);
        try {
            driver.setOutputStream(out);

            //Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xslt));
        
            //Setup input for XSLT transformation
            Source src = new StreamSource(xml);
        
            //Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(driver.getContentHandler());

            //Start XSLT transformation and FOP processing
            transformer.transform(src, res);
        } finally {
            out.close();
        }
    }


    public static void main(String[] args) {
        try {
            System.out.println("FOP ExampleXML2PDF
");
            System.out.println("Preparing...");

            //Setup directories
            File baseDir = new File(".");
            File outDir = new File(baseDir, "out");
            outDir.mkdirs();

            //Setup input and output files            
            File xmlfile = new File(baseDir, "xml/xml/projectteam.xml");
            File xsltfile = new File(baseDir, "xml/xslt/projectteam2FO.xsl");
            File pdffile = new File(outDir, "ResultXML2PDF.pdf");

            System.out.println("Input: XML (" + xmlfile + ")");
            System.out.println("Stylesheet: " + xsltfile);
            System.out.println("Output: PDF (" + pdffile + ")");
            System.out.println();
            System.out.println("Transforming...");
            
            ExampleXML2PDF app = new ExampleXML2PDF();
            app.convertXML2PDF(xmlfile, xsltfile, pdffile);
            
            System.out.println("Success!");
        } catch (Exception e) {
            System.err.println(ExceptionUtil.printStackTrace(e));
            System.exit(-1);
        }
    }
}


Commentaire de alex1er le 27/10/2003 15:18:06

Merci

Commentaire de Pasqwal le 02/12/2003 01:42:24

rhalala, c'est honteux de faire ça.
Les gens de l'OpenSource méritent notre reconnaissance.
Et ça c'est un sale coup. Et se faire mousser grâce au travail d'un autre, c'est pitoyable, vraiment aucune fièrté.
Et du coup, tu prends les habitués de ce sites pour des idiots.
he ben, ça doit être beau le reste de "tes" sources.

Commentaire de lolofx le 02/12/2003 13:15:20

voila, chose faite, g mis la license, je savais pas qu"il y en avait une.
Pr monsieur ki crois que g fais ca pr me faire mousser, non, désolé, pr moi ces sites, sont des sites d'entraides, ayant eu d difficultés pr faire mon pdf, je trouver bien de le mettre sur le site voila c tout.
je mets pas d sources et montrer que je c développer.
Mais si toi c ton but de montrer ce que tu c faire ben tant mieux.

enfin c rectifier, g mis la license.
et j'espere que comme pr moi, ce code aidera ceux ki en ont besoin sans chercher pdt des heures.

et merci a dobel de m'avoir dit k'il y avait une license

Commentaire de Pasqwal le 02/12/2003 16:33:40

Je te présente mes excuses, manifestement j'ai eu une réaction trop hative. C'est juste que j'ai vu rouge en voyant cela, mais apparement tu ne fais pas partie de cette catégorie de pseudo-développeurs. Honte sur moi.

Tu as raison sur le but du site, il ne s'agit pas de montrer que l'on sait développer mais bien de s'entraider. Et au nom de cette entraide, j'aimerais que tu n'enlèves pas le tout. Beaucoup de gens pourrait profiter de tes recherches.

Encore une fois lolofx, je te renouvelle mes plus plates excuses.

Amicalement,
Pasqwal.

Commentaire de dmothes le 10/02/2004 11:51:23

merci!, c'est juste ce que jecherchais!!!

Commentaire de eddie2070 le 14/05/2004 15:38:55

J utilise actuellement ce source, mais j aurai voulu savoir comment récuperer mon fichier xml et xsl directement dans le buffer, et non en donnant son $chemin d'accès.

Par exemple j ai converti les infos d'un écran(une page d'adresses par exemple) dans mon xml, mais celui-ci n est pas sur disque, et j aimerai le convertir en pdf, donc en le recuperant ds le buffer ou autre, et non en accedant a un fichier ( hou j me répéte là ^^ )
Merci

eddie2070

Commentaire de annalou le 05/07/2004 13:50:07

salut.

j'utilise ce programme mais je voudrais savoir comment faire pour ne pas afficher les messages suivants

[ERROR] Logger not set
[INFO] building formatting object tree
[WARNING] Screen logger not set - Using ConsoleLogger.
[INFO] setting up fonts
[INFO] [1]
[INFO] [2]
[INFO] [3]
[INFO] [4]
[INFO] [5]
[INFO] [6]
[INFO] [7]
[INFO] [8]
[INFO] [9]
[INFO] Parsing of document complete, stopping renderer

Merci

Commentaire de obigero le 14/04/2005 11:16:22

comment on transforme un fichier texte en ficheir xml ? c possible ? en gros je dois faire un traitement de texte en java et utiliser FOP ... et je sais pas si je dois programmer en jaja et transformer en xml apres ou directeement travailler en xml. les 2 sont possibles ?

Commentaire de posset le 29/04/2005 11:29:32

Bonjour,

je suis utilisateur de fop mais pour l'exploiter complètement je recherche la javadoc mais je la trouve pas.

Est ce que quelqu'un sait où je peux la télécharger?

Merci par avance

Commentaire de sebdijon le 15/01/2006 20:42:09

Pour la version 0.91 il n'y a plus de import org.apache.fop.apps.Driver;

Alors voilà l'exemple que j'ai trouvé :


/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* $Id: ExampleXML2PDF.java 332791 2005-11-12 15:58:07Z jeremias $ */

package embedding;

//Java
import java.io.File;
import java.io.OutputStream;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;

//FOP
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.MimeConstants;

/**
* This class demonstrates the conversion of an XML file to PDF using
* JAXP (XSLT) and FOP (XSL-FO).
*/
public class ExampleXML2PDF {

    /**
     * Main method.
     * @param args command-line arguments
     */
    public static void main(String[] args) {
        try {
            System.out.println("FOP ExampleXML2PDF\n");
            System.out.println("Preparing...");

            // Setup directories
            File baseDir = new File(".");
            File outDir = new File(baseDir, "out");
            outDir.mkdirs();

            // Setup input and output files            
            File xmlfile = new File(baseDir, "xml/xml/projectteam.xml");
            File xsltfile = new File(baseDir, "xml/xslt/projectteam2fo.xsl");
            File pdffile = new File(outDir, "ResultXML2PDF.pdf");

            System.out.println("Input: XML (" + xmlfile + ")");
            System.out.println("Stylesheet: " + xsltfile);
            System.out.println("Output: PDF (" + pdffile + ")");
            System.out.println();
            System.out.println("Transforming...");
            
            // Construct fop with desired output format
            Fop fop = new Fop(MimeConstants.MIME_PDF);
            
            // Setup output
            OutputStream out = new java.io.FileOutputStream(pdffile);
            out = new java.io.BufferedOutputStream(out);
            
            try {
                fop.setOutputStream(out);
    
                // Setup XSLT
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
                
                // Set the value of a <param> in the stylesheet
                transformer.setParameter("versionParam", "2.0");
            
                // Setup input for XSLT transformation
                Source src = new StreamSource(xmlfile);
            
                // Resulting SAX events (the generated FO) must be piped through to FOP
                Result res = new SAXResult(fop.getDefaultHandler());
    
                // Start XSLT transformation and FOP processing
                transformer.transform(src, res);
            } finally {
                out.close();
            }
            
            System.out.println("Success!");
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
}

Commentaire de Asnidren le 14/09/2006 11:18:05

Voici le site de FOP
http://xmlgraphics.apache.org/fop/

Commentaire de bwwilly le 22/06/2007 12:31:40

salut
quelcun à essayer l'exemple ? :)
pour moi il me génère des fautes et surtous au niveau de cette ligne :
Fop fop = new Fop(MimeConstants.MIME_PDF);
j'utilise java 6
et fop 0.2.5
que dois-je faire
merciiii

Commentaire de Uddasa le 01/08/2007 09:55:09

J'ai le même problème, voici le message:

Note: C:\Documents and Settings\STAGIAIRE\TestPDF\src\testpdf\ExampleXML2PDF.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

java.lang.NoClassDefFoundError: testpdf/ExampleXML2PDF

J'ai 2 avertissements: à l'instanciation de Fop et lors de son utilisation. Dans la FAQ il est demandé de vérifier le classpath, mais je ne sais pas trop quoi vérifier...

Commentaire de legastu le 30/06/2009 18:04:48

Bonjour,

J'ai un problème pour ces 2 imports :

import org.apache.fop.apps.Fop;
import org.apache.fop.apps.MimeConstants;

Apparemment ils n'existent pas...

Commentaire de vaytess le 28/07/2009 14:10:10

salut UDDASA.. le message "Recompile -Xlint:deprecation for details." signifie que le code source n'est plus valide. c'est comme si tu as lancer un logiciel démo dont la période d'évaluation est dépassée. Ceci est aussi exprimé par "The Apache Software License".
Bon si qlq1 d'autre a réussi l'exécution de l'application, ça sera gentil de nous informé :))
Bonne Boss

Commentaire de vaytess le 03/08/2009 18:53:34

salut à tous..j me suis arrivé à compiler et exécuter l'application mais je n sais pas pourquoi ça m généré des erreurs lors de l'exécution.!!! Est ce que qlq1 a tester un exemple.. j'ai vraiment besoin d'aide..

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

xml + fop -> pdf [ par dmothes ] ben j'ai essayé la source pour créer un fichier pdf à partir d'un fichier xml et d'un xsl-fohttp://www.javafr.com/code.aspx?ID=15611mais j'obtien tjs convertir XML --> PDF! [ par Jaguar2005 ] Salam amigo,je suis content d'&#234;tre parmi vous!!&nbsp;&nbsp;&nbsp;bon je suis entrain de r&#233;aliser un code en java qui permet de g&#233;nerer Probleme de driver de XML a PDF [ par cedzed ] Bonjour,j'ai eu un code ou on peut transformer un XML vers un PDF en utilisant un XSL.Jusqu'a l&#224; &#231;a va mais on me demande un DRIVER avec org JSP vers PDF [ par cedzed ] Bonjour,Je ne suis qu'au stade d'analyse et je voudrai savoir tout d'abord s'il est possible d'avoir un format PDF d'une page affich&#233;e en JSP?J'a transformer xml en pdf [ par minou2005 ] bonjourj'ai besoin d'aide pour transformer un document xml en autre pdf, je sais qu'il faut passer par xsl,fop mais je veux des exemples pr&#233;cis.m GENERATION DE PDF A PARTIR DE XML [ par AS_DE_TREFLE ] je voudrais generer du PDF à partir d'un fichier XML qui lui reprend toutes les enregistrements d'une table. Comment devrais procedre.Un exemple sera GENERATION DE PDF A PARTIR DE XML [ par AS_DE_TREFLE ] JE VEUX GENERER DU PDF A PARTIR DU XML. EN EFFET J'OBTIENS A PARTIR D'UNE SERVLET LE FICHIER XML SVT:&lt;?XML &gt; &lt;LISTE-CLIENTS&gt; &lt GENERATION DE PDF A PARTIR DE XML [ par AS_DE_TREFLE ] J'ai effectivement reçu votre mail et je vous remercie de la promptitude avec laquelle vous m'avez repondu. le seul hic est ke qd je lance ma servlet Génération d'un fichier XML [ par nourlhouda ] salut, je veux générer dynamiquement un fichier xml contenant des données sur des pages provenant de different moteur de recherche (ex overture, googl création d'un fichier XML à partir d'un DTD [ par hamdinoura2005 ] je dois créer un fichier XML à partir d'un DTD, je sais pas comment le faire !Y a-t-il un parseur pour DTD ?


Nos sponsors


Sondage...

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,718 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales