//gavdcodeend 12 //gavdcodebegin 13 public static void WordOpenXmlRemoveHeadersAndFooters() { using (WordprocessingDocument myWordDoc = WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true)) { MainDocumentPart docMainPart = myWordDoc.MainDocumentPart; if (docMainPart.HeaderParts.Count() > 0 || docMainPart.FooterParts.Count() > 0) { docMainPart.DeleteParts(docMainPart.HeaderParts); docMainPart.DeleteParts(docMainPart.FooterParts); Document myDocument = docMainPart.Document; var myHeaders = myDocument.Descendants <HeaderReference>().ToList(); foreach (HeaderReference oneHeader in myHeaders) { oneHeader.Remove(); } var myFooters = myDocument.Descendants <FooterReference>().ToList(); foreach (FooterReference oneFooter in myFooters) { oneFooter.Remove(); } myDocument.Save(); } } //gavdcodeend 13 }
/// <summary> /// Removes the custom XML parts. /// </summary> /// <param name="mainPart">The main document part.</param> public static void RemoveCustomXmlParts(this MainDocumentPart mainPart) { if (mainPart.CustomXmlParts.Count() > 0) { mainPart.DeleteParts(mainPart.CustomXmlParts); } }
private void btnGenerate_Click(object sender, EventArgs e) { string outFile = @"C:\Users\Christopher\Desktop\BookData\TestReportBetaEND.docx"; OpenFileDialog OFD = new OpenFileDialog(); OFD.Multiselect = false; OFD.Title = "Open Word Document"; OFD.Filter = "Word Document|*.docx;*.domx"; OFD.ShowDialog(); string docPath = OFD.FileName; OFD.Title = "Opne Xml Document"; OFD.Filter = "Xml Document|*.xml"; OFD.ShowDialog(); string xmlPath = OFD.FileName; // convert template to document File.Copy(docPath, outFile); using (WordprocessingDocument doc = WordprocessingDocument.Open(outFile, true)) { MainDocumentPart mdp = doc.MainDocumentPart; if (mdp.CustomXmlParts != null) { mdp.DeleteParts <CustomXmlPart>(mdp.CustomXmlParts); } CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml); FileStream fs = new FileStream(xmlPath, FileMode.Open); cxp.FeedData(fs); mdp.Document.Save(); } }
//gavdcodeend 11 //gavdcodebegin 12 public static void WordOpenXmlCreateFooter() { using (WordprocessingDocument myWordDoc = WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true)) { MainDocumentPart docMainPart = myWordDoc.MainDocumentPart; docMainPart.DeleteParts(docMainPart.FooterParts); FooterPart defaultFooterPart = docMainPart.AddNewPart <FooterPart>(); GenerateFooterPartContent(defaultFooterPart); string defaultFooterPartId = docMainPart.GetIdOfPart(defaultFooterPart); IEnumerable <SectionProperties> allSections = docMainPart.Document.Body.Elements <SectionProperties>(); foreach (var oneSection in allSections) { oneSection.RemoveAllChildren <FooterReference>(); oneSection.RemoveAllChildren <TitlePage>(); oneSection.PrependChild <FooterReference>(new FooterReference() { Id = defaultFooterPartId, Type = HeaderFooterValues.Default }); oneSection.PrependChild <TitlePage>(new TitlePage()); } docMainPart.Document.Save(); } }
private void ImagenHeader(string imgRuta, MainDocumentPart documento, WordprocessingDocument documentoWord) { if (!documento.HeaderParts.Any()) { documento.DeleteParts(documento.HeaderParts); var newHeaderPart = documento.AddNewPart <HeaderPart>(); var imgPart = newHeaderPart.AddImagePart(ImagePartType.Jpeg, "rId999"); var imagePartID = newHeaderPart.GetIdOfPart(imgPart); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { imgPart.FeedData(fs); } var rId = documento.GetIdOfPart(newHeaderPart); var headerRef = new HeaderReference { Id = rId }; var sectionProps = documentoWord.MainDocumentPart.Document.Body.Elements <SectionProperties>().LastOrDefault(); if (sectionProps == null) { sectionProps = new SectionProperties(); documentoWord.MainDocumentPart.Document.Body.Append(sectionProps); } sectionProps.RemoveAllChildren <HeaderReference>(); sectionProps.Append(headerRef); newHeaderPart.Header = GenerarImagenHeaeder(imagePartID); newHeaderPart.Header.Save(); } }
public static void ChangeHeader(String documentPath) { // Replace header in target document with header of source document. using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true)) { // Get the main document part MainDocumentPart mainDocumentPart = document.MainDocumentPart; // Delete the existing header and footer parts mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts); mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts); // Create a new header and footer part HeaderPart headerPart = mainDocumentPart.AddNewPart <HeaderPart>(); FooterPart footerPart = mainDocumentPart.AddNewPart <FooterPart>(); // Get Id of the headerPart and footer parts string headerPartId = mainDocumentPart.GetIdOfPart(headerPart); string footerPartId = mainDocumentPart.GetIdOfPart(footerPart); GenerateHeaderPartContent(headerPart); GenerateFooterPartContent(footerPart); // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id IEnumerable <SectionProperties> sections = mainDocumentPart.Document.Body.Elements <SectionProperties>(); foreach (var section in sections) { // Delete existing references to headers and footers section.RemoveAllChildren <HeaderReference>(); section.RemoveAllChildren <FooterReference>(); // Create the new header and footer reference node section.PrependChild <HeaderReference>(new HeaderReference() { Id = headerPartId }); section.PrependChild <FooterReference>(new FooterReference() { Id = footerPartId }); } } }
public void ChangeOrReplaceHeaderAndFooterFeature() { // Replace a header in the target document with a header from the source document. using (WordprocessingDocument document = WordprocessingDocument.Create( ArtifactsDir + "Change or replace header and footer - OpenXML.docx", WordprocessingDocumentType.Document)) { MainDocumentPart mainDocumentPart = document.MainDocumentPart; mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts); mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts); HeaderPart headerPart = mainDocumentPart.AddNewPart <HeaderPart>(); FooterPart footerPart = mainDocumentPart.AddNewPart <FooterPart>(); string headerPartId = mainDocumentPart.GetIdOfPart(headerPart); string footerPartId = mainDocumentPart.GetIdOfPart(footerPart); GenerateHeaderPartContent(headerPart); GenerateFooterPartContent(footerPart); // Give the HeaderReference and FooterReference of each section property the new Id. IEnumerable <SectionProperties> sections = mainDocumentPart.Document.Body.Elements <SectionProperties>(); foreach (var section in sections) { section.RemoveAllChildren <HeaderReference>(); section.RemoveAllChildren <FooterReference>(); section.PrependChild(new HeaderReference { Id = headerPartId }); section.PrependChild(new FooterReference { Id = footerPartId }); } } }
public static void ClearHeaderFooter(MainDocumentPart mdp) { mdp.DeleteParts(mdp.HeaderParts); mdp.DeleteParts(mdp.FooterParts); var hp = mdp.AddNewPart <HeaderPart>(); var fp = mdp.AddNewPart <FooterPart>(); hp.Header = new Header(); fp.Footer = new Footer(); foreach (var sps in mdp.Document.Body.Elements <SectionProperties>()) { sps.RemoveAllChildren <HeaderReference>(); sps.RemoveAllChildren <FooterReference>(); sps.PrependChild(new HeaderReference { Id = mdp.GetIdOfPart(hp) }); sps.PrependChild(new FooterReference { Id = mdp.GetIdOfPart(fp) }); } }
private static void RemoveHeaderAndFooter(MainDocumentPart docPart) { // Count the header and footer parts and continue if there are any. if (docPart.HeaderParts.Count() > 0 || docPart.FooterParts.Count() > 0) { // Remove the header and footer parts. docPart.DeleteParts(docPart.HeaderParts); docPart.DeleteParts(docPart.FooterParts); // Remove all references to the headers and footers. var headers = docPart.Document.Descendants <HeaderReference>().ToList(); foreach (var header in headers) { header.Remove(); } var footers = docPart.Document.Descendants <FooterReference>().ToList(); foreach (var footer in footers) { footer.Remove(); } } }
public void AddHeaderFromTo(string filepathFrom, string filepathTo) { // Replace header in target document with header of source document. using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filepathTo, true)) { MainDocumentPart mainPart = wdDoc.MainDocumentPart; // Delete the existing header part. mainPart.DeleteParts(mainPart.HeaderParts); // Create a new header part. DocumentFormat.OpenXml.Packaging.HeaderPart headerPart = mainPart.AddNewPart <HeaderPart>(); // Get Id of the headerPart. string rId = mainPart.GetIdOfPart(headerPart); // Feed target headerPart with source headerPart. using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(filepathFrom, true)) { DocumentFormat.OpenXml.Packaging.HeaderPart firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); if (firstHeader != null) { headerPart.FeedData(firstHeader.GetStream()); } } // Get SectionProperties and Replace HeaderReference with new Id. IEnumerable <SectionProperties> sectPrs = mainPart.Document.Body.Elements <SectionProperties>(); foreach (var sectPr in sectPrs) { // Delete existing references to headers. sectPr.RemoveAllChildren <HeaderReference>(); // Create the new header reference node. sectPr.PrependChild <HeaderReference>(new HeaderReference() { Id = rId }); } } }
protected void ReplaceCustomXML(string fileName, string customXML) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; mainPart.DeleteParts <CustomXmlPart>(mainPart.CustomXmlParts); //Add a new customXML part and then add content CustomXmlPart customXmlPart = mainPart.AddNewPart <CustomXmlPart>(); //copy the XML into the new part... using (StreamWriter ts = new StreamWriter(customXmlPart.GetStream())) ts.Write(customXML); } }
//..................................................................... /// <summary> /// /// </summary> /// <param name="doc"></param> private static void AddFooter(WordprocessingDocument doc) { // Declare a string for the header text. string newFooterText = "New footer via Open XML Format SDK 2.0 classes"; // Get the main document part. MainDocumentPart mainDocPart = doc.MainDocumentPart; // Delete the existing footer parts. mainDocPart.DeleteParts(mainDocPart.FooterParts); // Create a new footer part and get its relationship id. FooterPart newFooterPart = mainDocPart.AddNewPart <FooterPart>( ); string rId = mainDocPart.GetIdOfPart(newFooterPart); // Call the GeneratePageFooterPart helper method, passing in // the footer text, to create the footer markup and then save // that markup to the footer part. GeneratePageFooterPart(newFooterText).Save(newFooterPart); // Loop through all section properties in the document // which is where footer references are defined. foreach (SectionProperties sectProperties in mainDocPart.Document.Descendants <SectionProperties>( )) { // Delete any existing references to footers. foreach (FooterReference footerReference in sectProperties.Descendants <FooterReference>( )) { sectProperties.RemoveChild(footerReference); } // Create a new footer reference that points to the new // footer part and add it to the section properties. FooterReference newFooterReference = new FooterReference( ) { Id = rId, Type = HeaderFooterValues.Default }; sectProperties.Append(newFooterReference); } // Save the changes to the main document part. mainDocPart.Document.Save( ); }
public async Task <byte[]> Convert <T>(T model) where T : IGeneratable { string templateSource = model.TemplateFile; string outputPath = _docxConverterConfig.Value.OutputDirectory; string outputFile = Path.Combine( outputPath, model.FileName); #region Option #1 - File.Copy() // Create a new output folder. // If directory already exists, this method does nothing Directory.CreateDirectory(outputPath); // Make a copy of templateSource then populate with new data (overwrite any existing file) File.Copy(templateSource, outputFile, true); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(outputFile, true)) { // Get the main part of the document which contains CustomXMLParts MainDocumentPart mainPart = wordDoc.MainDocumentPart; // Delete all CustomXMLParts in the document. If needed, only specific CustomXMLParts can be deleted using the CustomXmlParts IEnumerable mainPart.DeleteParts <CustomXmlPart>(mainPart.CustomXmlParts); // Add new CustomXMLPart with data from new XML CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); using (var stream = SerializeXml(model)) { myXmlPart.FeedData(stream); wordDoc.Save(); } } byte[] byteArray = File.ReadAllBytes(outputFile); // Delete the file on disk File.Delete(outputFile); return(byteArray); #endregion }
public static void GenerateDocument(string xmlData, string template, string output) { if (File.Exists(output)) { File.Delete(output); } File.Copy(template, output); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(output, true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; mainPart.DeleteParts(mainPart.CustomXmlParts); CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); using (FileStream stream = new FileStream(xmlData, FileMode.Open)) { myXmlPart.FeedData(stream); } } MessageBox.Show("Document successfully generated.", "Complete"); }
//static void Main(string[] args) //{ // //CreateWordDoc("C:/Users/Trevor/Documents/test.docx", "This is Text, ya ya ya."); // // AddSignatureFooter("C:/Users/Trevor/Documents/test.docx", "-by Nelson Mandela"); // //Test statistics // Console.Write(BasicStats("C:/Users/Trevor/Documents/testGAO.docx")); // Console.ReadLine(); //} //Add footer with string signature to existing document public static void AddSignatureFooter(string filepath, string signature) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filepath, true)) { MainDocumentPart mainDocPart = doc.MainDocumentPart; if (mainDocPart.Document == null) { mainDocPart.Document = new Document(); } mainDocPart.DeleteParts(mainDocPart.FooterParts); FooterPart footerPart1 = mainDocPart.AddNewPart <FooterPart>("r98"); Footer footer1 = new Footer(); Paragraph paragraph1 = new Paragraph(); Run run1 = new Run(); Text text1 = new Text { Text = signature }; run1.Append(text1); paragraph1.Append(run1); footer1.Append(paragraph1); footerPart1.Footer = footer1; SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault(); if (sectionProperties1 == null) { sectionProperties1 = new SectionProperties(); mainDocPart.Document.Body.Append(sectionProperties1); } FooterReference footerReference1 = new FooterReference { Type = HeaderFooterValues.Default, Id = "r98" }; sectionProperties1.InsertAt(footerReference1, 0); } }
public static void AddHeader(MainDocumentPart mainDocPart, ReportImage reportImge) { // Delete the existing header parts. mainDocPart.DeleteParts(mainDocPart.HeaderParts); // Create a new header part and get its relationship id. HeaderPart newHeaderPart = mainDocPart.AddNewPart <HeaderPart>(); string rId = mainDocPart.GetIdOfPart(newHeaderPart); ImagePart imagepart = newHeaderPart.AddImagePart(ImagePartType.Jpeg); FileInfo newImg = new FileInfo(reportImge.Value); using (FileStream stream = newImg.OpenRead()) { imagepart.FeedData(stream); } string imageRID = newHeaderPart.GetIdOfPart(imagepart); reportImge.RId = imageRID; Header header = GeneratePageHeaderPart(reportImge); header.Save(newHeaderPart); foreach (SectionProperties sectProperties in mainDocPart.Document.Descendants <SectionProperties>()) { // Delete any existing references to headers. foreach (HeaderReference headerReference in sectProperties.Descendants <HeaderReference>()) { sectProperties.RemoveChild(headerReference); } HeaderReference newHeaderReference = new HeaderReference() { Id = rId, Type = HeaderFooterValues.Default }; sectProperties.Append(newHeaderReference); } header.Save(); }
static void Main(string[] args) { string template = @"C:\Users\Christopher\Desktop\BookData\TestReportBeta.docx"; string outFile = @"C:\Users\Christopher\Desktop\BookData\TestReportBetaEND.docx"; string xmlPath = @"C:\Users\Christopher\Desktop\BookData\TestReport.xml"; // convert template to document File.Copy(template, outFile); using (WordprocessingDocument doc = WordprocessingDocument.Open(outFile, true)) { MainDocumentPart mdp = doc.MainDocumentPart; if (mdp.CustomXmlParts != null) { mdp.DeleteParts <CustomXmlPart>(mdp.CustomXmlParts); } CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml); FileStream fs = new FileStream(xmlPath, FileMode.Open); cxp.FeedData(fs); mdp.Document.Save(); } }
//gavdcodeend 21 //gavdcodebegin 22 public static void WordOpenXmlDeleteAllPicturesFromDocument() { using (WordprocessingDocument myWordDoc = WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true)) { MainDocumentPart docMainPart = myWordDoc.MainDocumentPart; IEnumerable <ImagePart> docImageParts = docMainPart.ImageParts; List <ImagePart> listImageParts = new List <ImagePart>(); List <Drawing> listDrwParts = new List <Drawing>(docMainPart.RootElement. Descendants <Drawing>()); List <Drawing> listDrwdDeleteParts = new List <Drawing>(); foreach (ImagePart oneImage in docImageParts) { listImageParts.Add(oneImage); IEnumerable <Drawing> allDrawings = listDrwParts.Where(dp => dp.Descendants <DocumentFormat.OpenXml.Drawing.Pictures.Picture>(). Any(pc => pc.BlipFill.Blip.Embed == docMainPart. GetIdOfPart(oneImage))); foreach (Drawing oneDrawing in allDrawings) { if (oneDrawing != null && !listDrwdDeleteParts.Contains( oneDrawing)) { listDrwdDeleteParts.Add(oneDrawing); } } } foreach (Drawing oneDrwdDeletePart in listDrwdDeleteParts) { oneDrwdDeletePart.Remove(); } docMainPart.DeleteParts(listImageParts); } }
private static void InsertCustomWatermark(WordprocessingDocument package, string p) { SetWaterMarkPicture(p); MainDocumentPart mainDocumentPart1 = package.MainDocumentPart; if (mainDocumentPart1 != null) { mainDocumentPart1.DeleteParts(mainDocumentPart1.HeaderParts); HeaderPart headPart1 = mainDocumentPart1.AddNewPart <HeaderPart>(); GenerateHeaderPart1Content(headPart1); string rId = mainDocumentPart1.GetIdOfPart(headPart1); ImagePart image = headPart1.AddNewPart <ImagePart>("image/jpeg", "rId999"); GenerateImagePart1Content(image); IEnumerable <SectionProperties> sectPrs = mainDocumentPart1.Document.Body.Elements <SectionProperties>(); foreach (var sectPr in sectPrs) { sectPr.RemoveAllChildren <HeaderReference>(); sectPr.PrependChild <HeaderReference>(new HeaderReference() { Id = rId }); } } }
static void GenerateDocument() { string rootPath = @"C:\OfficeDocs"; string xmlDataFile = @"test.xml"; string templateDocument = @"temp.docx"; string outputDocument = rootPath + @"\MyGeneratedDocument.docx"; File.Copy(templateDocument, outputDocument); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(outputDocument, true)) { //get the main part of the document which contains CustomXMLParts MainDocumentPart mainPart = wordDoc.MainDocumentPart; //delete all CustomXMLParts in the document. If needed only specific CustomXMLParts can be deleted using the CustomXmlParts IEnumerable mainPart.DeleteParts <CustomXmlPart>(mainPart.CustomXmlParts); //add new CustomXMLPart with data from new XML file CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); using (FileStream stream = new FileStream(xmlDataFile, FileMode.Open)) { myXmlPart.FeedData(stream); } } }