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

Documents Java Discussion :

Conversion fichier word ou PPT en PDF avec Java Uno open office API


Sujet :

Documents Java

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Novembre 2006
    Messages
    67
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2006
    Messages : 67
    Points : 40
    Points
    40
    Par défaut Conversion fichier word ou PPT en PDF avec Java Uno open office API
    Bonjour.

    Mon but est de convertir à partir d'un programme java un fichier word ou power point au format pdf.

    Je suis donc aller voir du coté la doc d'open office :

    http://codesnippets.services.openoff...Documents.snip

    j'y ai trouvé des codes sources très interessant mais meme en m'inspirant de ces codes, je n'ai pas pu faire ce que je voulais.

    J'ai un peu de mal à manipuler cette api que je trouve un peu lourde.

    Si quelqu'un peut m'aider à ce sujet, quelqu'un qui a deja reussi avec cette api à arriver à faire ce que je veux ce serait sympa qu'il m'aide.

    Sinon j'ai une autre question et mes recherches ne m'ont pas vraiment aider.

    Est-il possible de faire par exemple la conversion word ou ppt vers pdf en ligne de commande avec open office, que le tout s'execute en tache de fond.

    Car si c'est le cas je n'aurais plus forcemment besoin de passer par l'api java uno.

    Merci d'avance.

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Novembre 2006
    Messages
    67
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2006
    Messages : 67
    Points : 40
    Points
    40
    Par défaut
    Voici mon code inspiré du lien mis précédemment :

    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
     
    package org.test.javaUno ;
     
    import java.net.MalformedURLException;
     
    import com.sun.star.beans.PropertyValue;
    import com.sun.star.comp.helper.Bootstrap;
    import com.sun.star.comp.helper.BootstrapException;
    import com.sun.star.frame.XComponentLoader;
    import com.sun.star.frame.XStorable;
    import com.sun.star.io.IOException;
    import com.sun.star.lang.XMultiComponentFactory;
    import com.sun.star.uno.UnoRuntime;
    import com.sun.star.uno.XComponentContext;
     
    /**
     * This method converts documents to other formats.
     * See http://www.openoffice.org/files/documents/25/3042/filter_list_ooo_2_0.html
     * 
     * @param targetFilename Name of the file, which is the target of the export.
     * @param conversionFilter Contains the conversion filter (see link above).
     */
     
    public class TestJavaConvert {
     
    	public TestJavaConvert () {
     
    	}
     
    	public void convert(String targetFilename, String conversionFilter)
    	{
     
    		XComponentContext xRemoteContext = null;
    		try
    		{
    			// Connect or start a OpenOffice instance
    			xRemoteContext = Bootstrap.bootstrap();
    		}
    		catch (BootstrapException e) {
    		}
     
    		//get OO desktop
    		XMultiComponentFactory xRemoteServiceManager = 
    				xRemoteContext.getServiceManager();
     
    		Object desktop = null;
    		try	{
    			desktop = xRemoteServiceManager.createInstanceWithContext(
    					"com.sun.star.frame.Desktop", xRemoteContext
    			);
    		}
    		catch (Exception e)	{
    		}
     
    		XComponentLoader xComponent = (XComponentLoader)
    		UnoRuntime.queryInterface(XComponentLoader.class, desktop);
     
    		// How to get the XComponent, see ../Office/Office.OpenDocumentFromURL.snip
    		XStorable xStorable = (XStorable)
    		UnoRuntime.queryInterface(XStorable.class, xComponent);
     
    		// Set properties for conversions
    		PropertyValue[] conversionProperties = new PropertyValue[2];
     
    		conversionProperties[0] = new PropertyValue();
    		conversionProperties[0].Name = "Overwrite";
    		conversionProperties[0].Value = new Boolean(true);
     
    		conversionProperties[1] = new PropertyValue();
    		conversionProperties[1].Name = "FilterName";
    		conversionProperties[1].Value = conversionFilter;
     
     
    		//String filelocation  = "";
     
    		java.io.File newfile = new java.io.File(targetFilename);
            java.net.URL before = null;
     
            try
            {
                before = newfile.toURL();
            }
            catch (MalformedURLException e) {
                System.out.println(e);
            }
            // Create a URL, which can be used by UNO
            String myUNOFileURL =  com.sun.star.uri.ExternalUriReferenceTranslator
              .create(xRemoteContext).translateToInternal(before.toExternalForm());
     
            if (myUNOFileURL.length() == 0 && targetFilename.length() > 0)
            {
                System.out.println("File URL conversion faild. Filelocation " +
                        "contains illegal characters: " + targetFilename);
            }
     
     
    		// Convert
    		try {
    			// See ../Office/Office.CreateUNOCompatibleURL.snip for method createUNOFileURL(targetFilename);
    			xStorable.storeToURL(myUNOFileURL,
    					conversionProperties);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    Mon main :
    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
     
    package org.test.javaUno;
     
    public class MainConvert {
     
    	public static void main(String[] args) {
     
    		TestJavaConvert convertPdf = new TestJavaConvert () ;
     
    		String cheminSource = "C:\\Documents and Settings\\mazlum\\Bureau\\testConversion\\plan.doc" ;
     
    		//String cheminConvert = "C:\\Documents and Settings\\mazlum\\Bureau\\OOConverter" ;
     
    		String conversionFilter = "writer_pdf_Export" ;   
     
    		convertPdf.convert(cheminSource, conversionFilter) ;
     
    	}
     
    }

    Voici mon erreur elle intervient au niveau de xRemoteContext.getServiceManager() :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    Exception in thread "main" java.lang.NullPointerException
    	at org.test.javaUno.TestJavaConvert.convert(TestJavaConvert.java:43)
    	at org.test.javaUno.MainConvert.main(MainConvert.java:15)
    Merci d'avance a ceux à ceux qui pourront s'interesser a mon probleme.

  3. #3
    Candidat au Club
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 2
    Points : 2
    Points
    2
    Par défaut Conversion Excel en PDF
    Tu as sans doutes l'erreur au niveau de xRemoteContext.getServiceManager() parce que tu n'as pas démarré Open Office.

  4. #4
    Membre à l'essai
    Profil pro
    Inscrit en
    Mai 2007
    Messages
    15
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2007
    Messages : 15
    Points : 17
    Points
    17
    Par défaut conversion
    Execute ton code en mode debug tu verras mieux pourquoi tu as un nulll pointer exception Mr Tosun

  5. #5
    Membre habitué Avatar de sewatech
    Inscrit en
    Février 2007
    Messages
    141
    Détails du profil
    Informations personnelles :
    Âge : 54

    Informations forums :
    Inscription : Février 2007
    Messages : 141
    Points : 166
    Points
    166
    Par défaut
    Bonjour,

    Je peux te proposer une classe qui fait la même chose, basée sur les mêmes exemples :

    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
     
    package fr.sewatech.sewatoool.pdf;
     
    import java.io.File;
    import java.net.MalformedURLException;
     
    import com.sun.star.beans.PropertyValue;
    import com.sun.star.comp.helper.Bootstrap;
    import com.sun.star.frame.XComponentLoader;
    import com.sun.star.frame.XStorable;
    import com.sun.star.io.IOException;
    import com.sun.star.lang.IllegalArgumentException;
    import com.sun.star.lang.XMultiComponentFactory;
    import com.sun.star.uno.UnoRuntime;
    import com.sun.star.uno.XComponentContext;
    import com.sun.star.uri.ExternalUriReferenceTranslator;
     
    public class PdfConverter {
     
    	public static void main(String[] args) {
    		try {
    			new PdfConverter().convert("D:\\Temp\\tmp.doc");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			System.exit(0);
    		}
    	}
     
    	private XComponentContext xContext;
    	private Object component;
    	private Object desktop;
     
    	/**
             * Convertit un fichier en PDF
             * 
             * @param filename
             * @throws Exception
             */
    	public void convert(String filename) throws Exception {
     
    		startOpenOffice();
    		String unoUrl = loadDocument(filename);
    		generatePdf(unoUrl);
    	}
     
    	private void generatePdf(String unoUrl) throws IOException {
    		XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
    				XStorable.class, component);
     
    		// Set properties for conversions
    		PropertyValue[] convertProperties = new PropertyValue[2];
     
    		convertProperties[0] = new PropertyValue();
    		convertProperties[0].Name = "Overwrite";
    		convertProperties[0].Value = true;
     
    		convertProperties[1] = new PropertyValue();
    		convertProperties[1].Name = "FilterName";
    		convertProperties[1].Value = "writer_pdf_Export";
     
    		xStorable.storeToURL(unoUrl.substring(0, unoUrl.lastIndexOf('.')) + ".pdf", convertProperties);
    	}
     
    	/**
             * Chargement d'un fichier OpenOffice
             * 
             * @param filename
             * @return
             * @throws MalformedURLException
             * @throws IOException
             * @throws IllegalArgumentException
             */
    	private String loadDocument(String filename)
    			throws MalformedURLException, IOException, IllegalArgumentException {
    		XComponentLoader loader = (XComponentLoader) UnoRuntime.queryInterface(
    				XComponentLoader.class, desktop);
     
    		String unoUrl = formatUnoUrl(filename);
     
    		// Value=true => pas d'interface graphique
    		PropertyValue[] loadProperties = new PropertyValue[1];
    		loadProperties[0] = new PropertyValue();
    		loadProperties[0].Name = "Hidden";
    		loadProperties[0].Value = true;
     
    		component = loader.loadComponentFromURL(unoUrl, "_blank", 0,
    				loadProperties);
    		return unoUrl;
    	}
     
    	/**
             * Démarrage d'OpenOffice
             * 
             * @return Instance d'OOo avec contexte
             * @throws Exception
             */
    	private Object startOpenOffice() throws Exception {
    		xContext = Bootstrap.bootstrap();
    		XMultiComponentFactory xMCF = xContext.getServiceManager();
     
    		desktop = xMCF.createInstanceWithContext(
    				"com.sun.star.frame.Desktop", xContext);
    		return desktop;
    	}
     
    	/**
             * Formatte un chemin traditionnel en chemin compatible UNO 
             * 
             * @param filename Chemin du fichier, au format traditionnel
             * @return Chemin du fichier, au format UNO
             * @throws MalformedURLException 
             */
    	private String formatUnoUrl(String filename)
    			throws MalformedURLException {
    		String unoUrl = ExternalUriReferenceTranslator.create(xContext)
    				.translateToInternal(new File(filename).toURL().toExternalForm());
    		return unoUrl;
    	}
     
    }

Discussions similaires

  1. [WD-2010] conversion fichier word vers pdf
    Par trc085 dans le forum Word
    Réponses: 2
    Dernier message: 28/01/2014, 18h18
  2. [PPT-2007] Export ppt vers pdf avec animations conservées
    Par homeprodukt dans le forum Powerpoint
    Réponses: 1
    Dernier message: 29/10/2011, 05h53
  3. Télécharger fichier Word à partir d'un lien avec IE8
    Par Totoye dans le forum Balisage (X)HTML et validation W3C
    Réponses: 4
    Dernier message: 16/09/2010, 09h41
  4. Convertir fichier word ou ppt en pdf
    Par aya02 dans le forum Documents
    Réponses: 13
    Dernier message: 25/05/2009, 13h51
  5. [VB]Générer un fichier Postscript à partir d'un pdf avec VB
    Par Vince dans le forum VB 6 et antérieur
    Réponses: 7
    Dernier message: 20/09/2005, 19h00

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