public override void Save(string path) { MainDocumentPart mainPart = document.MainDocumentPart; DocumentSettingsPart documentSettingsPart1 = mainPart.DocumentSettingsPart; #if templates_old AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" }; documentSettingsPart1.Settings.Append(attachedTemplate1); // На заметку: узнать подробнее про External Relationships в структуре OpenXML. // Пэ Эс: можно (и даже нужно) заполнять фигней. Если подставлять реальный URI, может повесить ворд. documentSettingsPart1.AddExternalRelationship( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(@"c:\foo\bar", UriKind.Absolute), "relationId1"); #endif mainPart.Document.Save(); document.Close(); using (FileStream fs = new FileStream(path, FileMode.Create)) { memory.WriteTo(fs); } memory.Close(); IsDisposed = true; }
public override void SaveToDocument(string destination, string documentName) { MainDocumentPart mainPart = document.MainDocumentPart; DocumentSettingsPart documentSettingsPart1 = mainPart.DocumentSettingsPart; // AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" }; documentSettingsPart1.Settings.Append(attachedTemplate1); documentSettingsPart1.AddExternalRelationship( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(TemplatePath, UriKind.Absolute), "relationId1"); mainPart.Document.Save(); document.Close(); using (FileStream fs = new FileStream(Path.Combine(destination, documentName), FileMode.Create)) { #warning См. комментарий // Цитата со StackOverflow: // Use CopyTo instead, there is a bug in WriteTo which makes it fail to write the entire content of the buffer when the target stream does not support writing everything in one go. memory.WriteTo(fs); } memory.Close(); IsDisposed = true; }
void SetMailMergeSetting(WordprocessingDocument doc, DocumentSettingsPart settingPart, string udlPath, string query, string connectionString) { int mailmergecount = doc.MainDocumentPart.DocumentSettingsPart.Settings.Elements <XOPEN.Wordprocessing.MailMerge>().Count(); if (mailmergecount != 1) { throw new ArgumentException("mailmergecount is not 1"); } // Get the Document Settings Part var newUri = new Uri(udlPath); var mymerge = settingPart.Settings.Elements <XOPEN.Wordprocessing.MailMerge>().First(); var myDataSourceReference = mymerge.DataSourceReference; if (myDataSourceReference != null) { var myOldRelationship = settingPart.GetExternalRelationship(myDataSourceReference.Id); if (myOldRelationship != null) { settingPart.DeleteExternalRelationship(myOldRelationship); settingPart.AddExternalRelationship(myOldRelationship.RelationshipType, newUri, myDataSourceReference.Id); } } if (mymerge.DataSourceObject != null && mymerge.DataSourceObject.SourceReference != null) { var myOldRelationship2 = settingPart.GetExternalRelationship(mymerge.DataSourceObject.SourceReference.Id); if (myOldRelationship2 != null) { settingPart.DeleteExternalRelationship(myOldRelationship2); settingPart.AddExternalRelationship(myOldRelationship2.RelationshipType, newUri, mymerge.DataSourceObject.SourceReference.Id); } if (mymerge.DataSourceObject.UdlConnectionString != null) { mymerge.DataSourceObject.UdlConnectionString.Val = connectionString; } } mymerge.ConnectString.Val = connectionString; mymerge.Query.Val = query; }
public static void InsertTemplateURI(this WordprocessingDocument document, string url) { MainDocumentPart mainPart = document.MainDocumentPart; var uri = new Uri(url); DocumentSettingsPart documentSettingsPart = mainPart.DocumentSettingsPart; ExternalRelationship relationship = documentSettingsPart.AddExternalRelationship( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", uri); documentSettingsPart.Settings.Append( new DocumentFormat.OpenXml.Wordprocessing.AttachedTemplate() { Id = relationship.Id }); }
void SetMacroPath(WordprocessingDocument doc, DocumentSettingsPart settingPart, string macroTemplatePath) { if (!String.IsNullOrEmpty(macroTemplatePath)) { var hasMacros = doc.MainDocumentPart.DocumentSettingsPart.Settings.Elements <XOPEN.Wordprocessing.AttachedTemplate>().Count(); var newUriMacr = new Uri(macroTemplatePath); if (hasMacros > 0) { AttachedTemplate attachTemplate = doc.MainDocumentPart.DocumentSettingsPart.Settings.Elements <XOPEN.Wordprocessing.AttachedTemplate>().First(); var attachTemplateRelationship = settingPart.GetExternalRelationship(attachTemplate.Id); // attachTemplateRelationship.Uri= new Uri(macroTemplatePath, UriKind.Absolute); if (attachTemplateRelationship != null) { settingPart.DeleteExternalRelationship(attachTemplateRelationship); settingPart.AddExternalRelationship(attachTemplateRelationship.RelationshipType, newUriMacr, attachTemplate.Id); } } } }
public void CreateMSWordDocument(Guid identifier) { var myResume = _resumeManagerRepository.Get(m => m.Guid.Equals(identifier)).First().Resume; string projPath = HttpContext.Current.Server.MapPath("~/Content/"); string outFilePath = Path.Combine(projPath, "doc", myResume.ResumeManager.Link); byte[] templateBytes = System.IO.File.ReadAllBytes(projPath + "MSWordTemplates\\template4.dotx"); using (MemoryStream templateStream = new MemoryStream()) { templateStream.Write(templateBytes, 0, (int)templateBytes.Length); using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true)) { doc.ChangeDocumentType(WordprocessingDocumentType.Document); var mainPart = doc.MainDocumentPart; // Get the Document Settings Part DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart; // 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(projPath + "MSWordTemplates\\template4.dotx", UriKind.Absolute), "relationId1"); string fullname = string.Format("{0} {1}", myResume.FirstName, myResume.LastName); SetCCText(mainPart, "FullName", fullname); SetCCText(mainPart, "Goal", myResume.Goal); SetCCText(mainPart, "Location", myResume.CurrentLocation); string email = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("EMail")).Data; SetCCText(mainPart, "Email", email); string phone = myResume.Contacts.First(c => c.ContactTitle.Title.Equals("Phone")).Data; SetCCText(mainPart, "Phone", phone); RemoveCCChild(mainPart, "OtherContacts"); foreach (var contact in myResume.Contacts.Where(c => !c.ContactTitle.Title.Equals("EMail") && !c.ContactTitle.Title.Equals("Phone"))) { AppendCCText(mainPart, "OtherContacts", string.Format("{0}: {1}", contact.ContactTitle.Title, contact.Data)); } // ОБРАЗОВАНИЕ if (myResume.Education.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single(); Table theTable = contentControl.Descendants <Table>().Single(); TableRow defaultRow = theTable.Elements <TableRow>().Last(); foreach (var institution in myResume.Education) { TableRow rowCopy = (TableRow)defaultRow.CloneNode(true); // период учебы var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>(); periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", institution.From.Format()); periodRun.Append(new Break()); periodRun.Append(new Text(institution.To.Format())); // описание уч. заведениия: // название и город TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1); SetCCText(secondColumn, "InstitutionName", string.Format("{0}, г. {1}", institution.Name, institution.City)); // кафедра if (string.IsNullOrEmpty(institution.Department)) { secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "InstitutionDepartment").Single().Parent.Remove(); } else { SetCCText(secondColumn, "InstitutionDepartment", institution.Department); } // специальность SetCCText(secondColumn, "InstitutionSpeciality", institution.Specialty); secondColumn.Elements <Paragraph>().Last().Append(new Run(new Break())); theTable.AppendChild(rowCopy); } theTable.RemoveChild(defaultRow); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Education").Single().Remove(); } // ОПЫТ РАБОТЫ if (myResume.WorkExp.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single(); Table theTable = contentControl.Descendants <Table>().Single(); TableRow defaultRow = theTable.Elements <TableRow>().Last(); foreach (var workPlace in myResume.WorkExp) { TableRow rowCopy = (TableRow)defaultRow.CloneNode(true); // период в который работали var periodRun = rowCopy.Descendants <TableCell>().ElementAt(0).GetFirstChild <Paragraph>().GetFirstChild <Run>(); periodRun.GetFirstChild <Text>().Text = string.Format("{0} –", workPlace.From.Format()); periodRun.Append(new Break()); periodRun.Append(new Text(workPlace.To.Format())); // описание работы: // название работы и город TableCell secondColumn = rowCopy.Descendants <TableCell>().ElementAt(1); SetCCText(secondColumn, "WorkplaceName", string.Format("{0}, г. {1}", workPlace.Name, workPlace.City)); // должность SetCCText(secondColumn, "WorkplacePosition", workPlace.Position); // обязанности if (workPlace.Duties.Count > 0) { RemoveCCChild(secondColumn, "WorkplaceDuties"); foreach (var duty in workPlace.Duties) { AppendCCText(secondColumn, "WorkplaceDuties", string.Format("– {0}", duty.Name)); } } else { secondColumn.Descendants <SdtRun>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "WorkplaceDuties").Single().Parent.Remove(); } //secondColumn.Elements<Paragraph>().Last().Append(new Run(new Break())); theTable.AppendChild(rowCopy); } theTable.RemoveChild(defaultRow); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Experience").Single().Remove(); } // СЕРТИФИКАТЫ if (myResume.CertificatesAndTrainings.Count > 0) { RemoveCCChild(mainPart, "Certificates"); foreach (var certificate in myResume.CertificatesAndTrainings) { AppendCCText(mainPart, "Certificates", string.Format("{0} – {1}{2}", certificate.Date.Year, certificate.Name, certificate.Location != null ? string.Format(", г. {0}", certificate.Location) : "")); } } else { RemoveCC(mainPart, "Section_Certificates"); } // ЯЗЫКИ if (myResume.Languages.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Languages").Single(); SdtContentBlock contentRun = contentControl.GetFirstChild <SdtContentBlock>(); Paragraph defaultLi = contentRun.GetFirstChild <Paragraph>(); foreach (var language in myResume.Languages) { Paragraph copy = (Paragraph)defaultLi.CloneNode(true); copy.Descendants <Text>().Where(t => t.Text == "lang").Single().Text = language.Name; copy.Descendants <Text>().Where(t => t.Text == "level").Single().Text = language.Level; contentRun.Append(copy); } contentRun.RemoveChild(defaultLi); } else { RemoveCC(mainPart, "Section_Languages"); } // ЛИЧНЫЕ КАЧЕСТВА if (myResume.PersonalQualities.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "PersonalQualities").Single(); SdtContentBlock contentRun = contentControl.GetFirstChild <SdtContentBlock>(); Paragraph defaultLi = contentRun.GetFirstChild <Paragraph>(); foreach (var quality in myResume.PersonalQualities) { Paragraph copy = (Paragraph)defaultLi.CloneNode(true); copy.Descendants <Text>().Where(t => t.Text == "quality").Single().Text = quality.Name; contentRun.Append(copy); } contentRun.RemoveChild(defaultLi); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_PersonalQualities").Single().Remove(); } // НАВЫКИ if (myResume.Skills.Count > 0) { SdtBlock contentControl = mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Skills").Single(); SdtContentBlock contentRun = contentControl.GetFirstChild <SdtContentBlock>(); Paragraph defaultLi = contentRun.GetFirstChild <Paragraph>(); foreach (var skill in myResume.Skills) { Paragraph copy = (Paragraph)defaultLi.CloneNode(true); copy.Descendants <Text>().Where(t => t.Text == "skill").Single().Text = skill.Name; contentRun.Append(copy); } contentRun.RemoveChild(defaultLi); } else { mainPart.Document.Body.Descendants <SdtBlock>().Where(r => r.SdtProperties.GetFirstChild <Tag>().Val == "Section_Skills").Single().Remove(); } mainPart.Document.Save(); } File.WriteAllBytes(outFilePath, templateStream.ToArray()); } }