begin process at 2008 05 12 10:01:37
1 170 178 membres
82 nouveaux aujourd'hui
13 956 membres club

Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum.
Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

CREER UN PDF AVEC XML ET FOP


Information sur la source

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 : 28 946

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

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (15)
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);
        }
    }
}
  • signaler à un administrateur
    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

  • signaler à un administrateur
    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);
            }
        }
    }


  • signaler à un administrateur
    Commentaire de alex1er le 27/10/2003 15:18:06

    Merci

  • signaler à un administrateur
    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.

  • signaler à un administrateur
    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

  • signaler à un administrateur
    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.

  • signaler à un administrateur
    Commentaire de dmothes le 10/02/2004 11:51:23

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

  • signaler à un administrateur
    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

  • signaler à un administrateur
    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

  • signaler à un administrateur
    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 ?

  • signaler à un administrateur
    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

  • signaler à un administrateur
    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);
            }
        }
    }

  • signaler à un administrateur
    Commentaire de Asnidren le 14/09/2006 11:18:05

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

  • signaler à un administrateur
    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

  • signaler à un administrateur
    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...

Ajouter un commentaire

Discussions en rapport avec ce code source

Appels d'offres

Pub



CalendriCode

Mai 2008
LMMJVSD
   1234
567891011
12131415161718
19202122232425
262728293031 

Téléchargements

Logiciels à télécharger sur le même thème :

Boutique

Boutique de goodies CodeS-SourceS