private void cmdCreateNew_Click(object sender, EventArgs e) { var sourceFileTemplate = txtFile.Text; if (txtFile.Text.Trim() == "") { MessageBox.Show(@"Please select DOCX file", "DOCX", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var desFile = @"C:\Dev\DestinationFile.docx"; File.Copy(sourceFileTemplate, desFile, true); using (WordprocessingDocument destinationDocument = WordprocessingDocument.Open(desFile, true)) { // Change the document type to Document destinationDocument.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); // Get the MainPart of the document MainDocumentPart mainPart = destinationDocument.MainDocumentPart; using (WordprocessingDocument sourceDocument = WordprocessingDocument.Open(sourceFileTemplate, true)) { CopyTableStyles(sourceDocument, destinationDocument); //The Style not found in the template document var table = GenerateTable(); mainPart.Document.Body.Append(table); } } MessageBox.Show(@"Table created successfully., Please check word document", @"C# and OpenXML", MessageBoxButtons.OK, MessageBoxIcon.Information); }
/// <summary> /// Ouverture d'un document depuis un template dotx /// </summary> /// <param name="streamTemplateFile">Chemin et nom complet du template</param> /// <param name="newFilePath">Chemin et nom complet du fichier qui sera sauvegardé</param> /// <returns>True si le document a bien été ouvert</returns> public bool OpenDocFromTemplate(string templateFilePath) { if (string.IsNullOrWhiteSpace(templateFilePath)) { throw new ArgumentNullException(nameof(templateFilePath), "templateFilePath must be not null or white spaces"); } if (!File.Exists(templateFilePath)) { throw new FileNotFoundException("file not found"); } streamFile = new MemoryStream(); try { byte[] byteArray = File.ReadAllBytes(templateFilePath); streamFile.Write(byteArray, 0, byteArray.Length); wdDoc = WordprocessingDocument.Open(streamFile, true); // Change the document type to Document wdDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); wdMainDocumentPart = wdDoc.MainDocumentPart; return(true); } catch { wdDoc = null; return(false); } }
private byte[] SetContentInPlaceholders() { byte[] output = null; using (MemoryStream ms = new MemoryStream()) { ms.Write(this.generationInfo.TemplateData, 0, this.generationInfo.TemplateData.Length); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(ms, true)) { wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document); MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart; Document document = mainDocumentPart.Document; if (this.generationInfo.Metadata != null) { SetDocumentProperties(mainDocumentPart, this.generationInfo.Metadata); } if (this.generationInfo.IsDataBoundControls) { SaveDataToDataBoundControlsDataStore(mainDocumentPart); } foreach (HeaderPart part in mainDocumentPart.HeaderParts) { this.SetContentInPlaceholders(new OpenXmlElementDataContext() { Element = part.Header, DataContext = this.generationInfo.DataContext }); part.Header.Save(); } foreach (FooterPart part in mainDocumentPart.FooterParts) { this.SetContentInPlaceholders(new OpenXmlElementDataContext() { Element = part.Footer, DataContext = this.generationInfo.DataContext }); part.Footer.Save(); } this.SetContentInPlaceholders(new OpenXmlElementDataContext() { Element = document, DataContext = this.generationInfo.DataContext }); this.openXmlHelper.EnsureUniqueContentControlIdsForMainDocumentPart(mainDocumentPart); document.Save(); } ms.Position = 0; output = new byte[ms.Length]; ms.Read(output, 0, output.Length); } return(output); }
/// <summary> /// Merges the text to field in main document part. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="substituteText">The substitute text.</param> public void MergeTextToFieldInMainDocumentPart(string fieldName, string substituteText) { using (WordprocessingDocument template = WordprocessingDocument.Open(this.MemoryStream, true)) { template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); ReplaceTextInMainDocumentPart(template.MainDocumentPart, $"«{fieldName}»", substituteText); } }
public byte[] GetWordReplacedTextUsingPlaintext(string templatePath, List <WordReplacement> items) { var pathdir = ConfigurationManager.AppSettings["doctemplate"].ToString(); if (pathdir.StartsWith("~")) { pathdir = HttpContext.Current.Server.MapPath(pathdir); } var path = Path.Combine(pathdir, templatePath); FileStream fileStream = new FileStream(path, FileMode.Open); using (MemoryStream templateStream = new MemoryStream()) { //templateStream.Write(templateBytes, 0, (int)templateBytes.Length); fileStream.CopyStream(templateStream); fileStream.Close(); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templateStream, true)) { wordDoc.ChangeDocumentType(WordprocessingDocumentType.Document); SimplifyMarkupSettings settings = new SimplifyMarkupSettings { RemoveProof = true, RemoveRsidInfo = true, NormalizeXml = true, //RemoveContentControls = true, //RemoveMarkupForDocumentComparison = true }; MarkupSimplifier.SimplifyMarkup(wordDoc, settings); string docText = null; using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); } foreach (var item in items) { if (!string.IsNullOrEmpty(item.TextToReplace)) { Regex regexText = new Regex(item.TextToReplace); docText = regexText.Replace(docText, item.ReplacementText ?? ""); } } using (StreamWriter sw = new StreamWriter(templateStream)) { sw.Write(docText); return(templateStream.ToArray()); } } } }
public static WordprocessingDocument CreateDocument(string pModel, string pNewDocument) { System.IO.File.Copy(pModel, pNewDocument, true); WordprocessingDocument document = WordprocessingDocument.Open(pNewDocument, true); document.ChangeDocumentType(WordprocessingDocumentType.Document); MainDocumentPart mainPart = document.MainDocumentPart; return(document); }
private static byte[] CreateWordDocument(FileInfo file, List <Tuple <string, string> > strings) { FileInfo template = file; //var template = @"~/docs/tmc.dotx"; byte[] templateBytes = File.ReadAllBytes(template.FullName); using (var templateStream = new MemoryStream()) { templateStream.Write(templateBytes, 0, templateBytes.Length); using (WordprocessingDocument document = WordprocessingDocument.Open(templateStream, true)) { // Change the document type to Document document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); // Get the MainPart of the document MainDocumentPart mainPart = document.MainDocumentPart; // Get the Document Settings Part DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart; foreach (var str in strings) { try { ReplaceBookmarkParagraphs(document, str.Item1, str.Item2); } catch (InvalidOperationException) { // ignore } } // Create a new attachedTemplate and specify a relationship ID //AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" }; // Append the attached template to the DocumentSettingsPart //documentSettingPart1.Settings.Append(attachedTemplate1); // Add an ExternalRelationShip of type AttachedTemplate. // Specify the path of template and the relationship ID //documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(template.FullName, UriKind.Absolute), "relationId1"); // Save the document mainPart.Document.Save(); } templateStream.Position = 0; var result = templateStream.ToArray(); templateStream.Flush(); return(result); } }
public static WordprocessingDocument CreateDoc(string sourceFile, out MemoryStream stream) { byte[] byteArray = File.ReadAllBytes(sourceFile); stream = new MemoryStream(); stream.Write(byteArray, 0, byteArray.Length); WordprocessingDocument document = WordprocessingDocument.Open(stream, true); // If your sourceFile is a different type (e.g., .DOTX), you will need to change the target type like so: document.ChangeDocumentType(WordprocessingDocumentType.Document); // Get the MainPart of the document return(document); }
private void OpenInMemory(byte[] bytes) { memory = new MemoryStream(); memory.Write(bytes, 0, (int)bytes.Length); try { document = WordprocessingDocument.Open(memory, true); document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); } catch (Exception ex) { throw new ArgumentException("Файл поврежден или не является документом Word(2007-10)", ex); } AttachPlaceholders(); }
protected void FillMergeFieldsOfDocumentAndSaveDoc(string filedocpath, Dictionary <string, string> data) { using (WordprocessingDocument document = WordprocessingDocument.Open(filedocpath, true)) { document.ChangeDocumentType(WordprocessingDocumentType.Document); MainDocumentPart mainPart = document.MainDocumentPart; var mergeFields = mainPart.RootElement.Descendants <FieldCode>(); foreach (var a in data) { var mergeFieldName = a.Key; var replacementText = a.Value; ReplaceMergeFieldWithText(mergeFields, mergeFieldName, replacementText); } mainPart.Document.Save(); } }
// // // // // // 3rd test // // // // // // public static void CreateFileUsingNormalTemplate() // make new docx using system's Normal.dotm -- DOESN'T SEEM TO BE WORKING, NEEDS A CLOSER LOOK! { string outputFileNameAndPath = Path.Combine(Program.outputFilePath, Guid.NewGuid().ToString() + "_create_from_normal_templete_nostyle" + ".docx"); string templateFilePath = "C:\\Users\\helpdesk\\AppData\\Roaming\\Microsoft\\Templates\\Normal.dotm"; //Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Templates).ToString(), "Normal.dotm"); //File.Open(Path.ChangeExtension(outputFilePath, ".docx"), FileMode.CreateNew); // create a copy of the template and open the copy File.Copy(templateFilePath, outputFileNameAndPath, true); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(outputFileNameAndPath, true)) { wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document); var mainPart = wordDocument.MainDocumentPart; var settings = mainPart.DocumentSettingsPart; var templateRelationship = new AttachedTemplate { Id = "relationId1" }; settings.Settings.Append(templateRelationship); var templateUri = new Uri("C:\\Users\\helpdesk\\AppData\\Roaming\\Microsoft\\Templates\\Normal.dotm", UriKind.Absolute); // put any path you like and the document styles still work settings.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", templateUri, templateRelationship.Id); // using Title as it would appear in Microsoft Word var paragraphProps = new ParagraphProperties(); paragraphProps.ParagraphStyleId = new ParagraphStyleId { Val = "Title" }; // add some text with the "Title" style from the "Default" style set supplied by Microsoft Word var run = new Run(); run.AppendChild(new Text("Created WordprocessingDocument with preserved defaults in Normal.dotm")); var para = new Paragraph(); para.Append(paragraphProps); para.Append(run); mainPart.Document.Body.Append(para); mainPart.Document.Save(); } Console.WriteLine(string.Format("{0}:{1}{2}{1}{3}", "3. File created based on the Normal.dotm with Text and no styles explicitly added", Environment.NewLine, outputFileNameAndPath, new string('-', 80))); }
// Given a .docm file (with macro storage), remove the VBA // project, reset the document type, and save the document with a new name. public static void ConvertDOCMtoDOCX(string fileName) { bool fileChanged = false; using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { // Access the main document part. var docPart = document.MainDocumentPart; // Look for the vbaProject part. If it is there, delete it. var vbaPart = docPart.VbaProjectPart; if (vbaPart != null) { // Delete the vbaProject part and then save the document. docPart.DeletePart(vbaPart); docPart.Document.Save(); // Change the document type to // not macro-enabled. document.ChangeDocumentType( WordprocessingDocumentType.Document); // Track that the document has been changed. fileChanged = true; } } // If anything goes wrong in this file handling, // the code will raise an exception back to the caller. if (fileChanged) { // Create the new .docx filename. var newFileName = Path.ChangeExtension(fileName, ".docx"); // If it already exists, it will be deleted! if (File.Exists(newFileName)) { File.Delete(newFileName); } // Rename the file. File.Move(fileName, newFileName); } }
protected void ButtonDotFileCreate_Click(object sender, EventArgs e) { Dictionary <string, string> AddElementsDictionary = Item.GetItems()[ReportsList.SelectedIndex]; string sourceFile = "~/App_Data/DocTemplate.dotx"; string targetFile = "~/App_Data/" + "ArchiveFile_" + AddElementsDictionary.Values.ElementAt(0) + "_" + AddElementsDictionary.Values.ElementAt(1) + ".docx"; if (File.Exists(Server.MapPath(targetFile))) { File.SetAttributes(Server.MapPath(targetFile), FileAttributes.Normal); File.Delete(Server.MapPath(targetFile)); } File.Copy(Server.MapPath(sourceFile), Server.MapPath(targetFile), true); File.SetAttributes(Server.MapPath(targetFile), FileAttributes.Normal); using (WordprocessingDocument document = WordprocessingDocument.Open(Server.MapPath(targetFile), true)) { document.ChangeDocumentType(WordprocessingDocumentType.Document); MainDocumentPart mainPart = document.MainDocumentPart; int CurrentBookMarkId = 0; foreach (BookmarkStart bookmarkStart in mainPart.RootElement.Descendants <BookmarkStart>()) { if (AddElementsDictionary.ContainsKey(bookmarkStart.Name)) { RunProperties rPr = new RunProperties( new RunFonts() { Ascii = "Arial" }, new Bold(), new Color() { Val = "green" } ); Run InsertToBookmarkOperation = new Run(new Text(AddElementsDictionary.ElementAt(CurrentBookMarkId).Value)); InsertToBookmarkOperation.PrependChild <RunProperties>(rPr); bookmarkStart.Parent.InsertAfter(InsertToBookmarkOperation, bookmarkStart); CurrentBookMarkId++; } } mainPart.Document.Save(); } }
public WordDocument(byte[] document, bool openAsTemplate = false) : base(DocFormat.Word, document) { if (document != null) { Document = WordprocessingDocument.Open(DocumentStream, true, new OpenSettings { AutoSave = true }); } else { var doc = WordprocessingDocument.Create(DocumentStream, WordprocessingDocumentType.Document, true); var mainDocumentPart = doc.AddMainDocumentPart(); mainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); mainDocumentPart.Document.Save(); Document = doc; } WordprocessingDocument.ChangeDocumentType(openAsTemplate ? WordprocessingDocumentType.Template : WordprocessingDocumentType.Document); }
public static void AppendText(WordprocessingDocument document) { document.ChangeDocumentType(WordprocessingDocumentType.Document); MainDocumentPart mainPart = document.MainDocumentPart; var mergeFields = mainPart.RootElement.Descendants <FieldCode>(); //Pega todos os MergeFields do corpo do documento Body body = document.MainDocumentPart.Document.Body; Paragraph p = new Paragraph(); Run r = new Run(); string t = "TextoAppend"; //Passar texto por parametro Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(t)); mainPart.Document.Save(); }
internal static SPFile AddDocument2Collection(SPFile _template, SPFileCollection _dstCollection, string _fileName) { SPFile _docFile = default(SPFile); using (Stream _tmpStrm = _template.OpenBinaryStream()) using (MemoryStream _docStrm = new MemoryStream()) { byte[] _buff = new byte[_tmpStrm.Length + 200]; int _leng = _tmpStrm.Read(_buff, 0, (int)_tmpStrm.Length); _docStrm.Write(_buff, 0, _leng); _docStrm.Position = 0; WordprocessingDocument _doc = WordprocessingDocument.Open(_docStrm, true); _doc.ChangeDocumentType(WordprocessingDocumentType.Document); _doc.Close(); _docFile = _dstCollection.Add(_fileName, _docStrm, true); _docStrm.Flush(); _docStrm.Close(); } return(_docFile); }
public static void MergeWithTextReplace(string templateName, string documentName, MergeData mergeData) { var mergedDocumentName = string.Empty; var templateDirectory = ConfigurationManager.AppSettings["TemplateFolder"] ?? String.Format("{0}\\Temp\\", System.AppDomain.CurrentDomain.BaseDirectory); var templatePath = String.Format("{0}{1}", templateDirectory, templateName); var documentPath = String.Format("{0}{1}", String.Format("{0}\\Temp\\", AppDomain.CurrentDomain.BaseDirectory), documentName); File.Copy(templatePath, documentPath, true); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(documentPath, true)) { wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document); // Make document readonly var docSett = wordDocument.MainDocumentPart.DocumentSettingsPart; docSett.RootElement.Append(new DocumentProtection { Edit = DocumentProtectionValues.ReadOnly }); docSett.RootElement.Save(); var body = wordDocument.MainDocumentPart.Document.Body; foreach (var mergeElement in mergeData.MergeElements) { foreach (var run in body.Descendants <Run>()) { foreach (var text in run.Descendants <Text>()) { var search = String.Format("*{0}*", mergeElement.MergeField); if (text.Text.Contains(search)) { text.Text = text.Text.Replace(search, mergeElement.MergeValue); } } } } wordDocument.Close(); } }
private WordTemplateModel GenerateDataMappingOxml(string TemplateFileLocation, WordTemplateModel model) { try { using (WordprocessingDocument document = WordprocessingDocument.Open(TemplateFileLocation, true)) { // Change the document type to Document document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); // Get the MainPart of the document MainDocumentPart mainPart = document.MainDocumentPart; // Get the Document Settings Part DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart; OpenXmlElement[] Enumerate = mainPart.ContentControls().ToArray(); List <ModelField> dataMapping = new List <ModelField>(); for (int i = 0; i < Enumerate.Count(); i++) { OpenXmlElement cc = Enumerate[i]; SdtProperties props = cc.Elements <SdtProperties>().FirstOrDefault(); Tag tag = props.Elements <Tag>().FirstOrDefault(); SdtAlias alias = props.Elements <SdtAlias>().FirstOrDefault(); string title = ((DocumentFormat.OpenXml.Wordprocessing.StringType)(alias)).Val; string tagName = tag.Val; dataMapping.Add(new ModelField() { Key = title }); } model.DataMapping = dataMapping; } } catch (Exception ex) { throw; } return(model); }
/// <summary> /// Append a list of SubDocuments at end of current doc /// </summary> /// <param name="filePath">Destination file path</param> /// <param name="filesToInsert">Documents to insert</param> /// <param name="insertPageBreaks">Indicate if a page break must be added before each document</param> public void AppendSubDocumentsList(string filePath, IList <MemoryStream> filesToInsert, bool withPageBreak) { wdDoc = WordprocessingDocument.Open(filePath, true); // Change the document type to Document wdDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); wdMainDocumentPart = wdDoc.MainDocumentPart; SaveDoc(); CloseDocNoSave(); //Append documents OpenDoc(filePath, true); foreach (var file in filesToInsert) { file.Position = 0; AppendSubDocument(file, withPageBreak); } SaveDoc(); CloseDocNoSave(); }
private MemoryStream GetStreamFromTemplate(string inputPath) { MemoryStream documentStream; using (Stream stream = File.OpenRead(inputPath)) { documentStream = new MemoryStream((int)stream.Length); stream.CopyTo(documentStream); documentStream.Position = 0L; } using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true)) { template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); MainDocumentPart mainPart = template.MainDocumentPart; // mainPart.DocumentSettingsPart.AddExternalRelationship( // "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", // new Uri(inputPath, UriKind.Absolute)); mainPart.Document.Save(); } return(documentStream); }
/// <summary> /// Converts the DOTX to DOCX /// </summary> /// <returns>True or False (with an exception) if successful in converting the document</returns> private TemplateGenerationResult ConvertTemplate() { try { MemoryStream msFile = null; using (Stream sTemplate = File.Open(_templateFileName, FileMode.Open, FileAccess.Read)) { msFile = new MemoryStream((int)sTemplate.Length); sTemplate.CopyTo(msFile); msFile.Position = 0L; } using (WordprocessingDocument wpdFile = WordprocessingDocument.Open(msFile, true)) { wpdFile.ChangeDocumentType(WordprocessingDocumentType.Document); MainDocumentPart docPart = wpdFile.MainDocumentPart; docPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(_templateFileName, UriKind.RelativeOrAbsolute)); docPart.Document.Save(); } // Flush the MemoryStream to the file File.WriteAllBytes(_targetFileName, msFile.ToArray()); msFile.Close(); return(new TemplateGenerationResult { Value = true }); } catch (Exception ex) { _log.Error(ex.Message.ToString(CultureInfo.InvariantCulture), ex.GetBaseException()); //System.IO.File.AppendAllText(@"c:\temp\errors.txt", "In DocumentGeneration::convertTemplate(): " + ex.Message.ToString(CultureInfo.InvariantCulture)); return(new TemplateGenerationResult { Value = false, Exception = "DocumentGeneration::convertTemplate() - " + ex.ToString() }); } }
public void ConvertFromDocmToDocxFeature() { bool fileChanged = false; using (WordprocessingDocument document = WordprocessingDocument.Open(MyDir + "Convert from docm to docx.docm", true)) { var docPart = document.MainDocumentPart; // Look for the vbaProject part. If it is there, delete it. var vbaPart = docPart.VbaProjectPart; if (vbaPart != null) { // Delete the vbaProject part and then save the document. docPart.DeletePart(vbaPart); docPart.Document.Save(); // Change the document type to not macro-enabled. document.ChangeDocumentType( WordprocessingDocumentType.Document); fileChanged = true; } } // If anything goes wrong in this file handling, // the code will raise an exception back to the caller. if (fileChanged) { if (File.Exists(ArtifactsDir + "Convert from docm to docx - OpenXML.docm")) { File.Delete(ArtifactsDir + "Convert from docm to docx - OpenXML.docm"); } File.Move(MyDir + "Convert from docm to docx.docm", ArtifactsDir + "Convert from docm to docx - OpenXML.docm"); } }
public WordTemplate(string templatePath) { this.TemplatePath = templatePath; _bookmarks = new Dictionary <string, BookmarkStart>(); byte[] docArray; // try { docArray = File.ReadAllBytes(templatePath); } catch (Exception ex) { this.Dispose(); throw new Exception(ex.Message); } memory = new MemoryStream(); memory.Write(docArray, 0, (int)docArray.Length); document = WordprocessingDocument.Open(memory, true); document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); }
private string GetImagingReport(ImagingReportPrintVM report) { try { var memStream = new MemoryStream(); var returnMemStream = new MemoryStream(); string dateTimeNow = DateTime.Now.ToString("dd-MM-yyyy_hh_mm_ss tt"); //given the file location ...Template dotx file is saved in wwwroot\fileuploads folder and Tests results in result folder string templateFileName = this._hostingEnvironment.WebRootPath + "\\" + this.labTemplateFolder + @"Radiology\Templates\ReportTemplate.dotx"; string fileName = this._hostingEnvironment.WebRootPath + "\\" + this.labTemplateFolder + @"Radiology\Templates\Result.docx"; Dictionary <string, string> patInfo = new Dictionary <string, string>(); patInfo.Add("PatientName", report.PatientName + "(" + report.PatientCode + ")"); patInfo.Add("ReferredBy", report.ProviderName); patInfo.Add("ReportText", report.ReportText); patInfo.Add("Date", report.CreatedOn.ToString("dd-MM-yyyy hh:mm:ss tt")); patInfo.Add("Age", report.Age); patInfo.Add("Sex", report.Gender); patInfo.Add("RequestId", report.RequisitionNo.ToString()); System.IO.File.Copy(templateFileName, fileName, true); using (WordprocessingDocument newdoc = WordprocessingDocument.Open(fileName, true)) { // Change document type (dotx->docx) newdoc.ChangeDocumentType(WordprocessingDocumentType.Document); SetDocumentKeyValues(newdoc, patInfo); newdoc.MainDocumentPart.GetStream().CopyTo(returnMemStream); return(fileName); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Ouverture d'un document depuis un template dotx /// </summary> /// <param name="templateFilePath">Chemin et nom complet du template</param> /// <param name="newFilePath">Chemin et nom complet du fichier qui sera sauvegardé</param> /// <param name="isEditable">Indique si le fichier doit être ouvert en mode éditable (Read/Write)</param> /// <returns>True si le document a bien été ouvert</returns> public bool OpenDocFromTemplate(string templateFilePath, string newFilePath, bool isEditable) { if (string.IsNullOrWhiteSpace(templateFilePath)) { throw new ArgumentNullException("templateFilePath must be not null or white spaces"); } if (!File.Exists(templateFilePath)) { throw new FileNotFoundException("file not found"); } this.isEditable = isEditable; filePath = newFilePath; try { System.IO.File.Copy(templateFilePath, newFilePath, true); wdDoc = WordprocessingDocument.Open(filePath, isEditable); // Change the document type to Document wdDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); wdMainDocumentPart = wdDoc.MainDocumentPart; SaveDoc(); CloseDocNoSave(); return(OpenDoc(newFilePath, isEditable)); } catch (Exception ex) { wdDoc = null; return(false); } }
public static void CopyFile(string templatefile, string resultfilename) { MemoryStream documentStream; String templatePath = templatefile; using (Stream tplStream = File.OpenRead(templatePath)) { documentStream = new MemoryStream((int)tplStream.Length); CopyStream(tplStream, documentStream); documentStream.Position = 0L; } using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true)) { template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); MainDocumentPart mainPart = template.MainDocumentPart; mainPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(templatePath, UriKind.Absolute)); mainPart.Document.Save(); } string path = resultfilename; File.WriteAllBytes(path, documentStream.ToArray()); }
// Given a DOCM file (with macro storage), remove the VBA // project, reset the document type, and save the document with a new name. public static void WDConvertDOCMtoDOCX(string fileName) { bool fileChanged = false; using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { var docPart = document.MainDocumentPart; // Look for the VBA part. If it's there, delete it. var vbaPart = docPart.VbaProjectPart; if (vbaPart != null) { docPart.DeletePart(vbaPart); docPart.Document.Save(); // Change the document type so that it no // longer thinks it is macro-enabled. document.ChangeDocumentType( WordprocessingDocumentType.Document); // Track that the document has been changed. fileChanged = true; } } // If anything goes wrong in this file handling, // the code will raise an exception back to the caller. if (fileChanged) { var newFileName = Path.ChangeExtension(fileName, ".docx"); if (File.Exists(newFileName)) { File.Delete(newFileName); } File.Move(fileName, newFileName); } }
public void MergeDocument() { // Create a copy of the template file and open the copy File.Copy(_sourcePath, _targetpath, true); using (WordprocessingDocument document = WordprocessingDocument.Open(_targetpath, true)) { document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); MainDocumentPart mainPart = document.MainDocumentPart; var fields = mainPart.Document.Body.Descendants <FormFieldData>(); foreach (var field in fields) { string fieldType = field.LastChild.GetType().Name; switch (fieldType) { case "DropDownListFormField": if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("Dropdown2")) { DropDownListFormField dropdownList = field.Descendants <DropDownListFormField>().First(); if (dropdownList != null) { int index = -1; var dropdownOptions = dropdownList.ToList(); if (dropdownOptions != null) { index = dropdownOptions.FindIndex(child => (child as ListEntryFormField).Val == "Test 3"); if (index > -1) { DefaultDropDownListItemIndex defaultDropDownListItemIndex1; defaultDropDownListItemIndex1 = new DefaultDropDownListItemIndex(); defaultDropDownListItemIndex1.Val = index; dropdownList.DefaultDropDownListItemIndex = defaultDropDownListItemIndex1; } } } } break; case "TextInput": if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("ClientNameFL")) { TextInput text = field.Descendants <TextInput>().First(); SetFormFieldValue(text, "Saddm Husain"); } if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("CurrentDate")) { TextInput text = field.Descendants <TextInput>().First(); SetFormFieldValue(text, DateTime.Now.ToString()); } break; case "CheckBox": if (((FormFieldName)field.FirstChild).Val.InnerText.Equals("Check3")) { CheckBox checkBox = field.Descendants <CheckBox>().First(); var Value = "Y"; var checkBoxValue = checkBox.ChildElements.LastOrDefault(); if (checkBoxValue != null) { (checkBoxValue as OnOffType).Val = Value == "Y" ? true : false; } } break; } } document.Save(); } }
public void Create(Stream output, GroupReport report) { #if f if (output == null) { throw new ArgumentNullException("output", Message.Get("Common.NullArgument", "output")); } if (report == null) { throw new ArgumentNullException("report", Message.Get("Common.NullArgument", "report")); } #endif // Открываем содержимое в памяти. var content = report.Template.Content; using (var memory = new MemoryStream()) { memory.Write(content, 0, (int)content.Length); try { Document = WordprocessingDocument.Open(memory, true); Document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); } #warning TODO Посмотреть актуальные исключения на операции. catch (Exception ex) { throw new InvalidOperationException("Возникла ошибка при чтении тела шаблона.\n", ex.InnerException); } var properties = report.Instances.First().TelefReprotProperties; var baseProperties = report.Instances.First().OwnProperties; bool useBaseProperties = baseProperties != null; // Получаем список закладок... var placeholders = Document.ContentControls(); if (placeholders.Count() == 0) { Document.Close(); throw new InvalidOperationException("В теле шаблона не найдено Structured Document Tag элементов."); } foreach (var placeholder in placeholders) { var placeholderId = placeholder.GetSdtTagText(); object entityId, hashedAttributeId, formatId; var uid = new UniqueIDCreator(); uid.Split(placeholderId, out entityId, out hashedAttributeId, out formatId); // В случае отсутствия value - оставлять элемент с оригинальным текстом, но выделять красным шрифтом. if (!useBaseProperties) { if (properties.First(x => x.Field.Attribute.ID.ToString() == hashedAttributeId.ToString()).Value == null) { (placeholder as SdtElement).SetSdtTextColor("FF0000"); } else { // Заполняем try { var value = properties .Where( x => (x.Field.Attribute.ID.ToString() == hashedAttributeId.ToString()) && (x.Field.Format.ID.ToString() == formatId.ToString()) ) .First().Value; var element = placeholder as SdtElement; element.SetSdtText(value.ToString()); element.SetSdtTextColor("000000"); } catch (InvalidOperationException ex) { Document.Close(); throw new InvalidOperationException(String.Format("Не удалось найти атрибут.\n{0}.", ex.Message)); } } } else { var property = baseProperties.SingleOrDefault(x => x.Attribute.ID.ToString() == hashedAttributeId.ToString()); if (property == null || property.Value == null || property.Value is DBNull) { (placeholder as SdtElement).SetSdtTextColor("FF0000"); } else { try { var element = placeholder as SdtElement; var format = property.Attribute.Type.GetAdmissableFormats(). First(o => o.ID.ToString() == formatId.ToString()); element.SetSdtText(string.Format(format.Provider, format.FormatString, property.Value)); element.SetSdtTextColor("000000"); } catch (InvalidOperationException ex) { Document.Close(); throw new InvalidOperationException(String.Format("Не удалось найти атрибут.\n{0}.", ex.Message)); } } } #warning Неплохо бы выводить сведения о хеше. } Document.Close(); // Результат - пишем в поток. try { memory.Seek(0, SeekOrigin.Begin); memory.CopyTo(output); } catch (NotSupportedException ex) { throw new InvalidOperationException(String.Format("Поток назначения не поддерживает запись:\n{0}.", ex.Message)); } catch (ObjectDisposedException ex) { throw new InvalidOperationException(String.Format("Поток назначения был преждевременно закрыт:\n{0}.", ex.Message)); } catch (IOException ex) { throw new InvalidOperationException(String.Format("Возникла общая ошибка ввода-вывода:\n{0}.", ex.Message)); } } }
static void Main(string[] args) { Random random = new Random(); List <TestResult> results = new List <TestResult>(); for (int i = 0; i < 21; i++) { double r = random.NextDouble() * 6 - 3; results.Add(new TestResult() { RelatedTest = new Test() { Name = "LD" + i.ToString() }, ZScore = (int)(random.NextDouble() * 6 - 3), Percentile = (int)(random.NextDouble() * 100) }); } List <TestResultGroup> resultGroups = new List <TestResultGroup>(new TestResultGroup[] { new TestResultGroup() { TestGroupInfo = new TestGroup() { Name = "Symptom Checklist - 90 - Revised" }, Tests = results } }); Patient johnDoe = new Patient() { Name = "John Doe", PreferredName = "Johnny", DateOfBirth = new DateTime(628243894905389400), DateOfTesting = new DateTime(628243894905389400), MedicalRecordNumber = 123456, ResultGroups = resultGroups }; Patient patient = johnDoe; Console.WriteLine(patient.DateOfBirth); string templatePath = @"Reports\ReportTemplate\Report_Template.dotx"; string newfilePath = @"Reports\GeneratedReports\" + patient.Name + ".docx"; string vizPath = @"Reports\GeneratedReports\Visualization.docx"; string imagePath = @"Reports\GeneratedReports\renderedVisualization2.png"; if (File.Exists(newfilePath)) { File.Delete(newfilePath); } File.Copy(templatePath, newfilePath); var entries = new List <Entry>(); int[] green = new int[] { 0, 255, 0 }; int[] yellow = new int[] { 255, 255, 0 }; int[] red = new int[] { 255, 0, 0 }; double interp; string hexcol; int percentile; using (WordprocessingDocument myDoc = WordprocessingDocument.Open(newfilePath, true)){ myDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); var wordAPI = new WordAPI(myDoc); wordAPI.InsertPatientData(patient); foreach (TestResultGroup testResultGroup in patient.ResultGroups) { wordAPI.DisplayTestGroup(testResultGroup); foreach (TestResult result in testResultGroup.Tests) { interp = 2 * Math.Abs(0.01 * (double)result.Percentile - 0.5); if (interp < 0.5) { hexcol = ColToHex(ColorInterpolation(green, yellow, 2 * interp)); } else { hexcol = ColToHex(ColorInterpolation(yellow, red, 2 * (interp - 0.5))); } if (result.Percentile == 0) { percentile = 1; } else { percentile = result.Percentile; } entries.Add(new Entry(percentile) { Label = result.RelatedTest.Name, ValueLabel = result.Percentile.ToString(), Color = SKColor.Parse(hexcol) }); } } wordAPI.PageBreak(); //InsertPicturePng(myDoc, imagePath,7,1.2); //JoinFile(myDoc,vizPath); } var chart = new BarChart() { Entries = entries, MaxValue = 100, MinValue = 0, LabelOrientation = Microcharts.Orientation.Vertical }; int width = 800; int height = 300; SKImageInfo info = new SKImageInfo(width, height); SKSurface surface = SKSurface.Create(info); SKCanvas canvas = surface.Canvas; chart.Draw(canvas, width, height); // create an image and then get the PNG (or any other) encoded data using (var data = surface.Snapshot().Encode(SKEncodedImageFormat.Png, 80)) { // save the data to a stream using (var stream = File.OpenWrite("one.png")) { data.SaveTo(stream); } } using (WordprocessingDocument myDoc = WordprocessingDocument.Open(newfilePath, true)){ var wordAPI = new WordAPI(myDoc); wordAPI.InsertPicturePng("one.png", 6, 3); } //Console.WriteLine("Modified"); }