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

C# Discussion :

Insérer une image (OpenXml v.2)


Sujet :

C#

  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    20
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 20
    Par défaut Insérer une image (OpenXml v.2)
    Bonjour,

    Je souhaite créer un document Word 2007 (WordProcessing) grace à OpenXml v.2.
    Dans ce document j'ai plusieurs images mais je ne sais pas comment les insérer.

    Pour l'instant j'ai réussi à les intégrer au fichier (dans la part : ImagePart).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    MainDocumentPart mainPart = documentWord.MainDocumentPart;
    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Emf);
     
    using (FileStream stream = new FileStream(nomFichier, FileMode.Open))
    {
        imagePart.FeedData(stream);
    }
    Je n'ai rien trouvé pour intégrer ces images à mon document Word (document.xml).

    Grace à DocumentReflector, j'ai pu voir le code à insérer pour une image. Mais celui-ci me parait énorme

    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
    using DocumentFormat.OpenXml.Wordprocessing;
    using DocumentFormat.OpenXml;
    using wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
    using a = DocumentFormat.OpenXml.Drawing;
    using pic = DocumentFormat.OpenXml.Drawing.Pictures;
     
    namespace GeneratedCode
    {
        public class GeneratedClass
        {
            public static Document GenerateDocument()
            {
                var element = 
                    new Document(
                        new Body(
                            new Paragraph(
                                new Run(
                                    new RunProperties(
                                        new NoProof(),
                                        new Languages(){ EastAsia = "fr-FR" }),
                                    new Drawing(
                                        new wp.Inline(
                                            new wp.Extent(){ Cx = 2038350L, Cy = 3238500L },
                                            new wp.EffectExtent(){ LeftEdge = 19050L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                                            new wp.DocProperties(){ Id = (UInt32Value)1U, Name = "Image 0", Description = "bb409621_structureOpenXML_fig01(fr-fr).jpg" },
                                            new wp.NonVisualGraphicFrameDrawingProperties(
                                                new a.GraphicFrameLocks(){ NoChangeAspect = true }),
                                            new a.Graphic(
                                                new a.GraphicData(
                                                    new pic.Picture(
                                                        new pic.NonVisualPictureProperties(
                                                            new pic.NonVisualDrawingProperties(){ Id = (UInt32Value)0U, Name = "bb409621_structureOpenXML_fig01(fr-fr).jpg" },
                                                            new pic.NonVisualPictureDrawingProperties()),
                                                        new pic.BlipFill(
                                                            new a.Blip(){ Embed = "rId4", CompressionState = a.BlipCompressionValues.Print },
                                                            new a.Stretch(
                                                                new a.FillRectangle())),
                                                        new pic.ShapeProperties(
                                                            new a.Transform2D(
                                                                new a.Offset(){ X = 0L, Y = 0L },
                                                                new a.Extents(){ Cx = 2038350L, Cy = 3238500L }),
                                                            new a.PresetGeometry(
                                                                new a.AdjustValueList()
                                                            ){ Preset = a.ShapeTypeValues.Rectangle }))
                                                ){ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                                        ){ DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U }))
                            ){ RsidParagraphAddition = new HexBinaryValue() { Value = "00AE0910"}, RsidRunAdditionDefault = new HexBinaryValue() { Value = "005D1B73"} },
                            new SectionProperties(
                                new PageSize(){ Width = (UInt32Value)11906U, Height = (UInt32Value)16838U },
                                new PageMargin(){ Top = 1417, Right = (UInt32Value)1417U, Bottom = 1417, Left = (UInt32Value)1417U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U },
                                new Columns(){ Space = (UInt32Value)708U },
                                new DocGrid(){ LinePitch = 360 }
                            ){ RsidR = new HexBinaryValue() { Value = "00AE0910"}, RsidSect = new HexBinaryValue() { Value = "00AE0910"} }));
                return element;
            }
     
        }
    }
    A vrai dire je suis un peu perdu dans tout ça.
    J'ai pu récupérer l'ID de mes images.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    mainPart.GetIdOfPart(imagePart)
    De plus, j'ai pu voir qu'on indiquait la taille de l'image. Comment peut-on la récupérer ?

    N'existe-t'il pas une méthode plus simplifiée pour insérer une image ?


    Par avance je vous remercie.

  2. #2
    Membre confirmé
    Profil pro
    Inscrit en
    Août 2005
    Messages
    150
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2005
    Messages : 150
    Par défaut
    Salut,

    Si tu n'as pas de contrainte particulière, tu peux utiliser les dlls Interop d'Office (oblige à avoir Microsoft Office 2007 d'installé pour que le code marche).

    Ensuite, tu crée des ContentControl de type Image ettu peux les modifier facilement via les Interop.

    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
     
    private void InsertPicInWord(Word._Document document, Word.ContentControl cc, string imgFileName)
            {
                if (string.IsNullOrEmpty(imgFileName) || !File.Exists(imgFileName))
                    return;
     
                Bitmap img = new Bitmap(imgFileName, true);
                MemoryStream ms = new MemoryStream();
                img.Save(ms, ImageFormat.Bmp);
                string ImageText = System.Convert.ToBase64String(ms.ToArray());
     
                XmlDocument doc = new XmlDocument();
                XmlNode declarationNode = doc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);
                doc.AppendChild(declarationNode);
                XmlElement imageElement = doc.CreateElement("Image");
                XmlText imageElementValue = doc.CreateTextNode(ImageText);
                doc.AppendChild(imageElement);
                doc.LastChild.AppendChild(imageElementValue);
                CustomXMLPart customXmlPart = document.CustomXMLParts.Add(doc.InnerXml, System.Type.Missing);
     
                cc.XMLMapping.SetMapping("/Image", String.Empty, customXmlPart);
            }
    Et si ton utilisateur final ne possède pas Word ou que tu veux pas utiliser cette méthode, bonne chance car moi aussi je suis bloquer, j'arrive à modifier l'image voulue dans le docx (dossier word/media/monimage) mais c'est toujours l'ancienne qui s'affiche quand je l'ouvre sous Word.

    Donc si tu trouve comment faire avec Open XML je suis preneur même si j'utilise System.IO.Packaging au lieu du SDK open XML.

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    20
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 20
    Par défaut
    Merci pour tes informations.

    Vu que je dois générer des documents sans l'application, je ne pourrai pas.

    Mais j'ai pu résoudre mon problème.

    Si ça peut t'aider voici ce que j'ai pu faire :

    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
    MainDocumentPart mainPart = documentWord.MainDocumentPart;
     
     
                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Emf);
     
     
     
                using (FileStream stream = new FileStream(nomFichier, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }
     
                Bitmap bitmap = new Bitmap(nomFichier);
                int bitmapHeight = bitmap.Height;
                int bitmapWidth = bitmap.Width;
     
     
                this.elementOpenXml.Append(new wp.Inline(
                    new wp.Extent() { Cx = Convert.ToInt64(bitmapWidth) * 9525, Cy = Convert.ToInt64(bitmapHeight) * 9525 },
                    new wp.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                    new wp.DocProperties() { Id = (UInt32Value)1U, Name = Path.GetFileNameWithoutExtension(imagePart.Uri.ToString()), Description = nomFichier },
                    new wp.NonVisualGraphicFrameDrawingProperties(
                        new a.GraphicFrameLocks() { NoChangeAspect = true }),
                        new a.Graphic(
                            new a.GraphicData(
                                new pic.Picture(
                                    new pic.NonVisualPictureProperties(
                                        new pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = nomFichier },
                                        new pic.NonVisualPictureDrawingProperties()),
                                    new pic.BlipFill(
                                        new a.Blip() { Embed = mainPart.GetIdOfPart(imagePart), CompressionState = a.BlipCompressionValues.Print },
                                        new a.Stretch(
                                            new a.FillRectangle())),
                                    new pic.ShapeProperties(
                                        new a.Transform2D(
                                            new a.Offset() { X = 0L, Y = 0L },
                                            new a.Extents() { Cx = Convert.ToInt64(bitmapWidth) * 9525, Cy = Convert.ToInt64(bitmapHeight) * 9525/*Cx = 1285875L, Cy = 428625L*/ }),
                                        new a.PresetGeometry(
                                            new a.AdjustValueList())
                                        { Preset = a.ShapeTypeValues.Rectangle })))
                            { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }))
                    );
    Donc mes images s'affichent correctement.

    Dommage, qu'il n'y ai pas plus d'informations sur le SDK OpenXml v2.
    Et à priori peu de monde l'utilisant.

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Août 2005
    Messages
    150
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2005
    Messages : 150
    Par défaut
    Merci pour ton code je suis en train de l'essayer mais j'ai quelques questions.

    1. C'est quoi le type de ton "this.elementOpenXml" ?
    2. Ta variable wp c'est "using wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
      " ?
    3. Idem pour la variable a ?


    Merci pour ton code

  5. #5
    Membre averti
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    20
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 20
    Par défaut
    Voici mes espaces de noms :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    using DocumentFormat.OpenXml.Wordprocessing;
    using DocumentFormat.OpenXml.Packaging;
    using wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
    using a = DocumentFormat.OpenXml.Drawing;
    using pic = DocumentFormat.OpenXml.Drawing.Pictures;
    Concernant mon elementOpenXml il s'agit d'un OpenXmlCompositeElement. J'ai pas testé avec un OpenXmlElement.

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

Discussions similaires

  1. Réponses: 2
    Dernier message: 19/11/2004, 08h54
  2. [CR] insérer une image paramétrer dans une étiquette
    Par yoyothebest dans le forum SAP Crystal Reports
    Réponses: 6
    Dernier message: 22/08/2004, 11h58
  3. [GNU Pascal] [GRX] Insérer une image
    Par the_guitariste dans le forum Autres IDE
    Réponses: 5
    Dernier message: 28/04/2004, 18h24
  4. [Crystal Reports 9] comment insérer une image dans Détails
    Par VVE dans le forum SAP Crystal Reports
    Réponses: 2
    Dernier message: 22/10/2003, 17h06
  5. [CR7] Insérer une image dynamiquement
    Par yoloosis dans le forum SAP Crystal Reports
    Réponses: 12
    Dernier message: 28/07/2003, 09h54

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