Affichage de HTML dans PowerPoint

Mon objective: Vouloir afficher du HTML dans une diapositive que j’injecte de manière dynamic dans une présentation principale.

Ce que j’ai réalisé jusqu’à présent: converti le format HTML en OpenXML (ou en WordML pour être plus spécifique), puis incorporé un object Word dans PowerPoint, puis analysé la structure via l’Outil de productivité OpenXML SDK. Il a créé un dossier d’ embeddings contenant le document I ‘ Dans la vue que je vois lorsque j’ouvre la présentation, c’est une image qui se trouve dans /ppt/media/image.emf.

Maintenant, j’ai dynamicment remplacé le contenu de docx incorporé, mais comment puis-je générer son image afin de pouvoir également mettre à jour la vue?

Ou existe-t-il une solution sans douleur?

REMARQUE: pour WINFORMS C #

OK, je n’ai pas lu la description de la douleur que vous avez écrite dans votre question. Je crois que vous avez beaucoup transpiré pour que cela fonctionne. Je partage ici la solution sans douleur (du moins cela a fonctionné pour moi) et je le crois. devrait fonctionner pour vous aussi.

Créez une classe comme ci-dessous: (J’ai partiellement pris cette solution d’un autre SO, désolée de ne pas me souvenir de la source)

using System; using System.Text.RegularExpressions; using System.Windows.Forms; public class HtmlFragment { #region Read and decode from clipboard static public HtmlFragment FromClipboard() { ssortingng rawClipboardText = Clipboard.GetText(TextDataFormat.Html); HtmlFragment h = new HtmlFragment(rawClipboardText); return h; } ///  /// Create an HTML fragment decoder around raw HTML text from the clipboard. /// This text should have the header. ///  /// raw html text, with header. public HtmlFragment(ssortingng rawClipboardText) { // This decodes CF_HTML, which is an entirely text format using UTF-8. // Format of this header is described at: // http://msdn.microsoft.com/library/default.asp?url=/workshop/networking/clipboard/htmlclipboard.asp // Note the counters are byte counts in the original ssortingng, which may be Ansi. So byte counts // may be the same as character counts (since sizeof(char) == 1). // But System.Ssortingng is unicode, and so byte couns are no longer the same as character counts, // (since sizeof(wchar) == 2). int startHMTL = 0; int endHTML = 0; int startFragment = 0; int endFragment = 0; Regex r; Match m; r = new Regex("([a-zA-Z]+):(.+?)[\r\n]", RegexOptions.IgnoreCase | RegexOptions.Comstackd); for (m = r.Match(rawClipboardText); m.Success; m = m.NextMatch()) { ssortingng key = m.Groups[1].Value.ToLower(); ssortingng val = m.Groups[2].Value; switch(key) { // Version number of the clipboard. Starting version is 0.9. case "version": m_version = val; break; // Byte count from the beginning of the clipboard to the start of the context, or -1 if no context case "starthtml": if (startHMTL != 0) throw new FormatException("StartHtml is already declared"); startHMTL = int.Parse(val); break; // Byte count from the beginning of the clipboard to the end of the context, or -1 if no context. case "endhtml": if (startHMTL == 0) throw new FormatException("StartHTML must be declared before endHTML"); endHTML = int.Parse(val); m_fullText = rawClipboardText.Subssortingng(startHMTL, endHTML - startHMTL); break; // Byte count from the beginning of the clipboard to the start of the fragment. case "startfragment": if (startFragment != 0) throw new FormatException("StartFragment is already declared"); startFragment = int.Parse(val); break; // Byte count from the beginning of the clipboard to the end of the fragment. case "endfragment": if (startFragment == 0) throw new FormatException("StartFragment must be declared before EndFragment"); endFragment = int.Parse(val); m_fragment = rawClipboardText.Subssortingng(startFragment, endFragment - startFragment); break; // Optional Source URL, used for resolving relative links. case "sourceurl": m_source = new System.Uri(val); break; } } // end for if (m_fullText == null && m_fragment == null) { throw new FormatException("No data specified"); } } // Data. See properties for descriptions. ssortingng m_version; ssortingng m_fullText; ssortingng m_fragment; System.Uri m_source; ///  /// Get the Version of the html. Usually something like "1.0". ///  public ssortingng Version { get { return m_version; } } ///  /// Get the full text (context) of the HTML fragment. This includes tags that the HTML is enclosed in. /// May be null if context is not specified. ///  public ssortingng Context { get { return m_fullText; } } ///  /// Get just the fragment of HTML text. ///  public ssortingng Fragment { get { return m_fragment; } } ///  /// Get the Source URL of the HTML. May be null if no SourceUrl is specified. This is useful for resolving relative urls. ///  public System.Uri SourceUrl { get { return m_source; } } #endregion // Read and decode from clipboard #region Write to Clipboard // Helper to convert an integer into an 8 digit ssortingng. // Ssortingng must be 8 characters, because it will be used to replace an 8 character ssortingng within a larger ssortingng. static ssortingng To8DigitSsortingng(int x) { return Ssortingng.Format("{0,8}", x); } ///  /// Clears clipboard and copy a HTML fragment to the clipboard. This generates the header. ///  /// A html fragment. ///  /// HtmlFragment.CopyToClipboard("Hello!"); ///  public static void CopyToClipboard(ssortingng htmlFragment) { CopyToClipboard(htmlFragment, null, null); } ///  /// Clears clipboard and copy a HTML fragment to the clipboard, providing additional meta-information. ///  /// a html fragment /// optional title of the HTML document (can be null) /// optional Source URL of the HTML document, for resolving relative links (can be null) public static void CopyToClipboard(ssortingng htmlFragment, ssortingng title, Uri sourceUrl) { if (title == null) title = "From Clipboard"; System.Text.SsortingngBuilder sb = new System.Text.SsortingngBuilder(); // Builds the CF_HTML header. See format specification here: // http://msdn.microsoft.com/library/default.asp?url=/workshop/networking/clipboard/htmlclipboard.asp // The ssortingng contains index references to other spots in the ssortingng, so we need placeholders so we can compute the offsets. // The <<<<<<<_ strings are just placeholders. We'll backpatch them actual values afterwards. // The string layout (<<<) also ensures that it can't appear in the body of the html because the < // character must be escaped. string header = @"Format:HTML Format Version:1.0 StartHTML:<<<<<<<1 EndHTML:<<<<<<<2 StartFragment:<<<<<<<3 EndFragment:<<<<<<<4 StartSelection:<<<<<<<3 EndSelection:<<<<<<<3 "; string pre = @" " + title + @""; ssortingng post = @""; sb.Append(header); if (sourceUrl != null) { sb.AppendFormat("SourceURL:{0}", sourceUrl); } int startHTML = sb.Length; sb.Append(pre); int fragmentStart = sb.Length; sb.Append(htmlFragment); int fragmentEnd = sb.Length; sb.Append(post); int endHTML = sb.Length; // Backpatch offsets sb.Replace("<<<<<<<1", To8DigitString(startHTML)); sb.Replace("<<<<<<<2", To8DigitString(endHTML)); sb.Replace("<<<<<<<3", To8DigitString(fragmentStart)); sb.Replace("<<<<<<<4", To8DigitString(fragmentEnd)); // Finally copy to clipboard. string data = sb.ToString(); Clipboard.Clear(); Clipboard.SetText(data, TextDataFormat.Html); } #endregion // Write to Clipboard } 

Utilisation expliquée ci-dessous:

using PowerPoint = Microsoft.Office.Interop.PowerPoint;

 var oPowerPoint = new PowerPoint.Application(); oPowerPoint.Visible = Microsoft.Office.Core.MsoTriState.msoTrue; 

J'avais l'obligation de coller le contenu sur la diapositive active, j'ai donc utilisé le code ci-dessous. Votre logique pourrait être différente en fonction de vos besoins, vous pouvez ignorer la ligne de code ci-dessous.

  var activeSlide = (PowerPoint.Slide)oPowerPoint.ActiveWindow.View.Slide; 

Ajoutez votre contenu HTML à la méthode ci-dessous

 HtmlFragment.CopyToClipboard(HTML CONTENT WILL COME HERE); 

Le code ci-dessous va coller le code HTML dans la diapositive active

 oPowerPoint.ActiveWindow.View.PasteSpecial(); 

J’espère que vous avez réussi à trouver quelque chose à propos de votre problème.

Un peu tard, mais pour les futures personnes qui pourraient venir ici.

Ceci est pour la partie HTML -> PPT.

 PowerPoint.Presentation presentation; presentation = ppApp.Presentations.Open(configuration.PPTTExportedFile, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue); foreach (PowerPoint.Slide slide in presentation.Slides) { foreach (PowerPoint.Shape shape in slide.Shapes) { File.WriteAllText(temporaryFilePath, html); WebsiteToImage websiteToImage = new WebsiteToImage(temporaryFilePath, @"New picture path"); websiteToImage.Generate(); slide.Shapes.AddPicture(@"picture path", MsoTriState.msoTrue, MsoTriState.msoTrue, oldshapeleft, oldshapetop, oldshapewidth, oldshapeheight); fileToDelete.Add(temporaryFilePath); fileToDelete.Add(@""dont forget to remove tmp files"); } } 

Convertir une page Web en image depuis ASP.NET

Si vous souhaitez manipuler des objects dans Word / Excel / PowerPoint, je vous suggère de travailler avec

 Console.Write("AlternativeText: "); Console.WriteLine(shape.AlternativeText); 

Parce que si vous enregistrez dans votre fichier d’origine un AlternativeText dans votre object, vous pouvez y accéder rapidement et vous pouvez même changer le PATH en une simple variable.

Et si vous souhaitez par exemple exporter un tableau HTML, créez-en une image et modifiez le texte AlternativeText afin de pouvoir y accéder plus facilement ultérieurement, tout en lui atsortingbuant un nom approprié auquel vous pourrez accéder avec un troisième outil soutenir les balises HTML

Suivant pour faire:

 File.Copy(WordTemplateFile, WordExportedFile, true); 

Pourquoi voulez-vous changer l’original? Faites simplement une copie et conservez-la en tant que modèle que vous pouvez modifier à tout moment en créant une nouvelle version modifiée. (Bon pour les rapports)

AlternativeText est très utile si vous envisagez de travailler avec.

Pour votre remplacement, vous souhaiterez peut-être utiliser les bibliothèques NetOffice / Microsoft Office.

 foreach (NetOffice.WordApi.InlineShape s in docWord.InlineShapes) { if (s.Type==NetOffice.WordApi.Enums.WdInlineShapeType.wdInlineShapePicture && s.AlternativeText.Contains("any pattern you are looking for")) {  s.Range.InsertFile(); } } 

Vous parcourez tout votre fichier et vérifiez si quelque chose correspond à votre modèle.

Bonne chance.