From 3656a486c7106b4caf74e68ffbf5a40f250ca255 Mon Sep 17 00:00:00 2001 From: Mathieu Mack Date: Mon, 3 Jul 2023 00:06:21 +0200 Subject: [PATCH] Update openTemplate to support file stream --- src/OpenXMLSDK.Engine/Word/WordManager.cs | 48 ++++++++++++++--------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/src/OpenXMLSDK.Engine/Word/WordManager.cs b/src/OpenXMLSDK.Engine/Word/WordManager.cs index ca9389f..e4b45ad 100644 --- a/src/OpenXMLSDK.Engine/Word/WordManager.cs +++ b/src/OpenXMLSDK.Engine/Word/WordManager.cs @@ -17,8 +17,6 @@ public class WordManager : IDisposable { #region Fields - private MemoryStream streamFile; - private string filePath; /// @@ -123,19 +121,6 @@ wdDoc.MainDocumentPart.Document.Body.LastChild.FirstChild is ParagraphProperties } } - /// - /// Permet de renvoyer le MemoryStream associé au document en cours - /// - /// MemoryStream en cours, null sinon - public MemoryStream GetMemoryStream() - { - var memoryStream = new MemoryStream(); - streamFile.Position = 0; - streamFile.CopyTo(memoryStream); - memoryStream.Position = 0; - return memoryStream; - } - #endregion #region Settings @@ -229,8 +214,35 @@ public bool OpenDoc(Stream streamFile, bool isEditable) /// /// Ouverture d'un document depuis un template dotx /// - /// Chemin et nom complet du template - /// Chemin et nom complet du fichier qui sera sauvegardé + /// Chemin et nom complet du template + /// True si le document a bien été ouvert + public bool OpenDocFromTemplate(Stream templateFileStream) + { + if (templateFileStream is null || templateFileStream == Stream.Null) + throw new ArgumentNullException(nameof(templateFileStream), "templateFilePath must not be null"); + + try + { + wdDoc = WordprocessingDocument.Open(templateFileStream, true); + + // Change the document type to Document + wdDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); + + wdMainDocumentPart = wdDoc.MainDocumentPart; + + return true; + } + catch + { + wdDoc = null; + return false; + } + } + + /// + /// Ouverture d'un document depuis un template dotx + /// + /// Chemin et nom complet du template /// True si le document a bien été ouvert public bool OpenDocFromTemplate(string templateFilePath) { @@ -239,7 +251,7 @@ public bool OpenDocFromTemplate(string templateFilePath) if (!File.Exists(templateFilePath)) throw new FileNotFoundException("file not found"); - streamFile = new MemoryStream(); + using var streamFile = new MemoryStream(); try { byte[] byteArray = File.ReadAllBytes(templateFilePath);