// 05/12/2011 Add ability to append chunks. // http://blogs.msdn.com/b/ericwhite/archive/2008/10/27/how-to-use-altchunk-for-document-assembly.aspx public static void AppendAltChunk(WordprocessingDocument docx, int nID, byte[] byChunk) { string altChunkId = "AltChunkId" + nID.ToString(); MainDocumentPart mainPart = docx.MainDocumentPart; if ( mainPart == null ) { mainPart = docx.AddMainDocumentPart(); mainPart.AddNewPart<WebSettingsPart>("rId3"); mainPart.AddNewPart<DocumentSettingsPart>("rId2"); mainPart.AddNewPart<StyleDefinitionsPart>("rId1"); mainPart.AddNewPart<ThemePart>("rId5"); mainPart.AddNewPart<FontTablePart>("rId4"); mainPart.Document = new Document(); mainPart.Document.Body = new Body(); } AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); using ( MemoryStream stmChunk = new MemoryStream() ) { stmChunk.Write(byChunk, 0, byChunk.Length); stmChunk.Seek(0, SeekOrigin.Begin); chunk.FeedData(stmChunk); } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document.Body.InsertAt<AltChunk>(altChunk, mainPart.Document.Body.Elements().Count()); //mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last()); }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId8"); GenerateFontTablePart1Content(fontTablePart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId3"); GenerateWebSettingsPart1Content(webSettingsPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId2"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId1"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId9"); GenerateThemePart1Content(themePart1); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("mailto:[email protected]", System.UriKind.Absolute), true, "rId7"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://www.shivam.com", System.UriKind.Absolute), true, "rId6"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("mailto:[email protected]", System.UriKind.Absolute), true, "rId5"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://www.google.com", System.UriKind.Absolute), true, "rId4"); SetPackageProperties(document); }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId3"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId2"); GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId1"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId6"); GenerateThemePart1Content(themePart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId5"); GenerateFontTablePart1Content(fontTablePart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId4"); GenerateWebSettingsPart1Content(webSettingsPart1); }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId3"); GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId7"); GenerateThemePart1Content(themePart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId2"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId1"); GenerateCustomXmlPart1Content(customXmlPart1); CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId6"); GenerateFontTablePart1Content(fontTablePart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId5"); GenerateWebSettingsPart1Content(webSettingsPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId4"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); documentSettingsPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new System.Uri("file:///D:\\Downloads\\FamilyMergeDoc%20(2).dotx", System.UriKind.Absolute), "rId1"); }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId3"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId2"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId1"); GenerateCustomXmlPart1Content(customXmlPart1); CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId6"); GenerateThemePart1Content(themePart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId5"); GenerateFontTablePart1Content(fontTablePart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId4"); GenerateWebSettingsPart1Content(webSettingsPart1); SetPackageProperties(document); }
internal WordprocessingDocument CreateDocument(String fileName) { docxFile = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document); mainPart = docxFile.AddMainDocumentPart(); docxFile.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()); body = docxFile.MainDocumentPart.Document.Body; return docxFile; }
public static void CreateDocX(string md, string docName) { package = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document); package.AddMainDocumentPart(); package.MainDocumentPart.Document = new Document(); Body body = MarkdownToDocBody(md); SaveDocX(body, docName); }
///<summary> /// Creates new instance of DocxDocument from scratch ///</summary> public DocxDocument() { _documentStream = new MemoryStream(); _wordDocument = WordprocessingDocument.Create(_documentStream, WordprocessingDocumentType.Document, true); _wordDocument.AddMainDocumentPart(); _wordDocument.MainDocumentPart.Document = new Document(new Body()); var sdtElements = _wordDocument.MainDocumentPart.Document.Body.Descendants<SdtElement>(); _fields = new FieldsCollection(sdtElements); }
public DocxParser(ContentFile file) { parsedFile = file; path = Path.GetTempPath() + Path.DirectorySeparatorChar + "tmp-" + DateTime.Now.Ticks.ToString(); doc = WordprocessingDocument.Create(path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document); var mainPart = doc.AddMainDocumentPart(); var paragraph = new Paragraph(new Run(new Text(file.contentText))); SetMetadata(MetadataType.Author, file.Metadata[MetadataType.Author]); SetMetadata(MetadataType.Description, file.Metadata[MetadataType.Author]); SetMetadata(MetadataType.Language, file.Metadata[MetadataType.Author]); SetMetadata(MetadataType.Subject, file.Metadata[MetadataType.Author]); SetMetadata(MetadataType.Title, file.Metadata[MetadataType.Author]); SetMetadata(MetadataType.Type, file.Metadata[MetadataType.Author]); }
public DocumentBuilder(WordprocessingDocument document, bool isEmptyDocument) { this.document = document; if (isEmptyDocument) { main = document.AddMainDocumentPart(); main.Document = new Document(); body = main.Document.AppendChild(new Body()); InsertParagraph(); } else { throw new Exception("Manipulating existing documents is not supported."); } }
public Docments(string path) { if (!File.Exists(path)) { doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document); mainPart = doc.AddMainDocumentPart(); mainPart.Document = new Document(); body = mainPart.Document.AppendChild(new Body()); } else { doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document); //doc = WordprocessingDocument.Open(path, true); if (doc.MainDocumentPart == null) { mainPart = doc.AddMainDocumentPart(); } else { mainPart = doc.MainDocumentPart; } if (mainPart.Document == null) { mainPart.Document = new Document(); } else { mainPart.Document = new Document(); } if (mainPart.Document.Body == null) { body = mainPart.Document.AppendChild(new Body()); } else { body = mainPart.Document.Body; } } }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document, objPatientContract obj) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1, obj); FooterPart footerPart1 = mainDocumentPart1.AddNewPart<FooterPart>("rId8"); GenerateFooterPart1Content(footerPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId3"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); HeaderPart headerPart1 = mainDocumentPart1.AddNewPart<HeaderPart>("rId7"); GenerateHeaderPart1Content(headerPart1); StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId2"); GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId1"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart<EndnotesPart>("rId6"); GenerateEndnotesPart1Content(endnotesPart1); FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart<FootnotesPart>("rId5"); GenerateFootnotesPart1Content(footnotesPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId10"); GenerateThemePart1Content(themePart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId4"); GenerateWebSettingsPart1Content(webSettingsPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId9"); GenerateFontTablePart1Content(fontTablePart1); SetPackageProperties(document); }
/// <summary> /// Agrega contenido al documento en la posición especificada. /// Si el documento no existe, se crea automáticamente. /// </summary> /// <param name="content"></param> /// <param name="position"></param> public void AddContent(IContent content, DocumentPosition position = DocumentPosition.BOTTOM) { WordprocessingDocument wordDocument = null; try { Body docBody; if (File.Exists(this.path)) { wordDocument = WordprocessingDocument.Open( this.path, true ); docBody = wordDocument.MainDocumentPart.Document.Body; } else { wordDocument = WordprocessingDocument.Create( this.path, WordprocessingDocumentType.Document, true ); MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); docBody = new Body(); mainPart.Document.Body = docBody; } content.Add(docBody, position); } finally { if (wordDocument != null) { wordDocument.Dispose(); } } }
public void Bug718314() { string testFile = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx"); using (WordprocessingDocument doc = WordprocessingDocument.Create(testFile, WordprocessingDocumentType.Document)) { var mpart = doc.AddMainDocumentPart(); mpart.Document = new Document(); mpart.Document.Body = new Body(); mpart.Document.Body.Append(new AlternateContent()); } OpenSettings s = new OpenSettings(); s.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007); using (var doc = WordprocessingDocument.Open(testFile, true, s)) { Assert.Null(doc.MainDocumentPart.Document.Body.FirstChild); } System.IO.File.Delete(testFile); }
private static MemoryStream CreateWordprocessingDocument() { var stream = new MemoryStream(); const WordprocessingDocumentType type = WordprocessingDocumentType.Document; using WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, type); MainDocumentPart mainDocumentPart = wordDocument.AddMainDocumentPart(); mainDocumentPart.Document = new Document( new Body( new Paragraph( new Run( new Text(ToReplace))), new Paragraph( new Run( new Text("to-")), new Run( new Text("replace"))))); return(stream); }
static void Main(string[] args) { var path = Path.Combine( "C:\\Users\\ksowul\\Desktop\\docxTesting\\", DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString() + " " + DateTime.Now.Minute.ToString() + " " + DateTime.Now.Second.ToString() + " lol.docx"); using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document, true)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); string headerPath = "C:\\Users\\ksowul\\Desktop\\docxTesting\\image1.jpeg"; // Create the document structure and add some text. mainPart.Document = new Document(); mainPart.Document.Body = new Body(); Paragraph paragraph = new Paragraph(); mainPart.Document.Body.AppendChild(paragraph); Run run = paragraph.AppendChild(new Run()); var Header = GetHeader(headerPath, mainPart); run.AppendChild(Header); wordDocument.Close(); } }
public static void CreateWordprocessingDocument(string filepath, List <User.RootObject> users) { // Create a document by supplying the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); foreach (User.RootObject u in users) { Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Name: " + u.name)); run.AppendChild(new Break()); run.AppendChild(new Text("Username: "******"Email: " + u.email)); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); using (FileStream stream = new FileStream(Constants.LOCAL.ImageDest, FileMode.Open)) { imagePart.FeedData(stream); } //AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart)); Drawing element = getImage(mainPart.GetIdOfPart(imagePart)); run.AppendChild(new Break()); run.AppendChild(new Break()); run.AppendChild(element); Paragraph lineBreak = new Paragraph(new Run(new Break() { Type = BreakValues.Page })); run.AppendChild(lineBreak); } } }
public void createInvoiceWordDoc(string pathName) { string fileName = "Invoice " + invoiceID + ".docx"; using (WordprocessingDocument package = WordprocessingDocument.Create(pathName + fileName, WordprocessingDocumentType.Document)) { package.AddMainDocumentPart(); package.MainDocumentPart.Document = new Document( new Body( new Paragraph( new Run( new Text("P2SO - " + invoiceID) ) ) ) ); package.MainDocumentPart.Document.Save(); package.Close(); } }
{/// <summary> /// Создание документа /// </summary> /// <param name="info"></param> public static void CreateDoc(WordInfo info) { using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); Body docBody = mainPart.Document.AppendChild(new Body()); docBody.AppendChild(CreateParagraph(new WordParagraph { Texts = new List <string> { info.Title }, TextProperties = new WordParagraphProperties { Bold = true, Size = "24", JustificationValues = JustificationValues.Center } })); foreach (var component in info.Komlects) { docBody.AppendChild(CreateParagraph(new WordParagraph { Texts = new List <string> { component.KomlectName + " - " + component.Price.ToString() + " р." }, TextProperties = new WordParagraphProperties { Bold = true, Size = "24", JustificationValues = JustificationValues.Both } })); } docBody.AppendChild(CreateSectionProperties()); wordDocument.MainDocumentPart.Document.Save(); } }
public static byte[] SaveText(string text) { MemoryStream ms = new MemoryStream(); using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); if (text == null) { throw new Exception("Текст не может быть пустым!"); } run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(text)); wordDocument.Close(); byte[] arr = ms.ToArray(); return(arr); } }
private static void AddParts(WordprocessingDocument parent, string embeddedDocumentPath) { var mainDocumentPart = parent.AddMainDocumentPart(); GenerateMainDocumentPart().Save(mainDocumentPart); var embeddedPackagePart = mainDocumentPart.AddNewPart <EmbeddedPackagePart>( "application/vnd.openxmlformats-" + "officedocument.spreadsheetml.sheet", "rId1"); GenerateEmbeddedPackagePart(embeddedPackagePart, embeddedDocumentPath); var imagePart = mainDocumentPart.AddNewPart <ImagePart>( "image/x-emf", "rId2"); GenerateImagePart(imagePart); }
public void can_convert_html_to_openxml_document() { var doc = File.ReadAllText("./data/letter.html"); using (MemoryStream generatedDocument = new MemoryStream()) { using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new Document(new Body()).Save(mainPart); } HtmlConverter converter = new HtmlConverter(mainPart); converter.ParseHtml(doc); mainPart.Document.Save(); } // visually test this. File.WriteAllBytes(@"./test.docx", generatedDocument.ToArray()); } }
public void CanDataBindBlockLevelSdtToCustomXmlWithoutNsPrefixIfNsPrefixInPrefixMapping() { // The following root element has an implicitly created attribute // xmlns='http://example.com': // // <Root xmlns="http://example.com"> // <Node>VALUE1</Node> // </Root> // var customXmlRootElement = new XElement(Ns + "Root", new XElement(Ns + "Node", "VALUE1")); using WordprocessingDocument wordDocument = WordprocessingDocument.Create("SdtBlock_DefaultNs_WithNsPrefixInMapping.docx", Type); MainDocumentPart mainDocumentPart = wordDocument.AddMainDocumentPart(); string storeItemId = CreateCustomXmlPart(mainDocumentPart, customXmlRootElement); mainDocumentPart.PutXDocument(new XDocument( new XElement(W.document, new XAttribute(XNamespace.Xmlns + "w", W.w.NamespaceName), new XElement(W.body, new XElement(W.sdt, new XElement(W.sdtPr, new XElement(W.dataBinding, // Note the w:prefixMapping attribute WITH a namespace // prefix and the corresponding w:xpath atttibute. new XAttribute(W.prefixMappings, $"xmlns:{NsPrefix}='{NsName}'"), new XAttribute(W.xpath, $"{NsPrefix}:Root[1]/{NsPrefix}:Node[1]"), new XAttribute(W.storeItemID, storeItemId))), new XElement(W.sdtContent, new XElement(W.p))))))); // Note that we just added an empty w:p to the w:sdtContent element. // However, if you open the Word document created by the above code // in Microsoft Word, you should see a single paragraph saying // "VALUE1". }
public void AddNewPart_NewMainDocumentPart_SuccessfullyAdded() { const string path = "Document.docx"; const WordprocessingDocumentType type = WordprocessingDocumentType.Document; using WordprocessingDocument wordDocument = WordprocessingDocument.Create(path, type); // Create minimum main document part. MainDocumentPart mainDocumentPart = wordDocument.AddMainDocumentPart(); mainDocumentPart.Document = new Document(new Body(new Paragraph())); // Create empty style definitions part. var styleDefinitionsPart = mainDocumentPart.AddNewPart <StyleDefinitionsPart>(); styleDefinitionsPart.Styles = new Styles(); // Create empty numbering definitions part. var numberingDefinitionsPart = mainDocumentPart.AddNewPart <NumberingDefinitionsPart>(); numberingDefinitionsPart.Numbering = new Numbering(); }
//-----Word /// <summary> /// 将html导出为Word /// </summary> /// <param name="html">必须以<html>包裹</param> /// <param name="vpath">保存路径</param> /// <returns></returns> public static string W_HtmlToWord(string html, string vpath) { if (string.IsNullOrEmpty(html)) { throw new Exception("未指定需要生成Word的内容"); } if (string.IsNullOrEmpty(vpath)) { throw new Exception("未指定Word保存路径"); } string ppath = function.VToP(vpath); string pdir = Path.GetDirectoryName(ppath); if (!Directory.Exists(pdir)) { Directory.CreateDirectory(pdir); } byte[] array = Encoding.UTF8.GetBytes(html); MemoryStream stream = new MemoryStream(array); using (WordprocessingDocument myDoc = WordprocessingDocument.Create(ppath, WordprocessingDocumentType.Document)) { string altChunkId = "AltChunkId"; MainDocumentPart mainPart = myDoc.AddMainDocumentPart(); mainPart.Document = new Document(); mainPart.Document.Body = new Body(); var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId); chunk.FeedData(stream); AltChunk altChunk = new AltChunk() { Id = altChunkId }; mainPart.Document.Append(altChunk); mainPart.Document.Save(); stream.Dispose(); } return(vpath); }
static void Main(string[] args) { //string path = "case.html"; string dir = "./toDelete/toDelete/FUNCTIONAL REQUIREMENTS/"; List <string> filearr = new List <string>(); List <string> htmlarr = new List <string>(); List <string> htmlarr1 = getPath(dir, filearr, htmlarr); List <string> headinglist = new List <string>(); foreach (string html in htmlarr1) { int count = SubstringCount("\\", html); string htmlstring = html + count.ToString(); headinglist.Add(htmlstring); } string path = "demo.html"; Program.ParseHtml(path); string savepath = "test.docx"; if (!File.Exists(savepath)) { WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Create(savepath, WordprocessingDocumentType.Document); MainDocumentPart m = wordprocessingDocument.AddMainDocumentPart(); m.Document = new Document(); //m.StyleDefinitionsPart = new StyleDefinitionsPart(); wordprocessingDocument.MainDocumentPart.AddNewPart <StyleDefinitionsPart>(); //StyleDefinitionsPart part = wordprocessingDocument.MainDocumentPart.StyleDefinitionsPart; Body b = m.Document.AppendChild(new Body()); ProcessTranslate(wordprocessingDocument, m); } else { WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(savepath, true); MainDocumentPart m = wordprocessingDocument.MainDocumentPart; ProcessTranslate(wordprocessingDocument, m); } }
public void GetDocxStatistics() { Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.docx", DateTime.Now.ToString("dd-MM-yyyy-HH-mm"))); using (MemoryStream ms = new MemoryStream()) { using (WordprocessingDocument package = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document)) { MainDocumentPart mainDocumentPart = package.AddMainDocumentPart(); mainDocumentPart.Document = new Document(); //------------------------------------------------------------------------------------------- Body documentBody = new Body(new SectionProperties( new FooterReference() { Type = HeaderFooterValues.Default, Id = "rId7" } )); mainDocumentPart.Document.Append(documentBody); //------------------------------------------------------------------------------------------- FillDocBody(documentBody, mainDocumentPart); mainDocumentPart.Document.Save(); //------------------------------------------------------------------------------------------- var oddPageFooterPart = mainDocumentPart.AddNewPart <FooterPart>("rId7"); WordHelper.GenerateFooter().Save(oddPageFooterPart); package.Close(); } byte[] arr = ms.ToArray(); Response.OutputStream.Write(arr, 0, arr.Length); } Response.Flush(); Response.Close(); }
static void Main(string[] args) { const string filename = "test.docx"; string html = File.ReadAllText("htmlFile.html"); if (File.Exists(filename)) { File.Delete(filename); } using (MemoryStream generatedDocument = new MemoryStream()) { using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new Document(new Body()).Save(mainPart); } HtmlConverter converter = new HtmlConverter(mainPart); Body body = mainPart.Document.Body; var paragraphs = converter.Parse(html); for (int i = 0; i < paragraphs.Count; i++) { body.Append(paragraphs[i]); } mainPart.Document.Save(); } File.WriteAllBytes(filename, generatedDocument.ToArray()); } System.Diagnostics.Process.Start(filename); }
public Stream WordDocument() { string guid = Guid.NewGuid().ToString(); string directory = Directory.GetCurrentDirectory(); string path = Path.Join(directory, "documents", $"{guid}.docx"); using (WordprocessingDocument package = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document)) { // Add a new main document part. package.AddMainDocumentPart(); // Create the Document DOM. var body = new Body( ExamTitleHeader(), EmptyParagraphSpace(), StudentInformationSection(), EmptyParagraphSpace() ); PrintExamSections(ref body); package.MainDocumentPart.Document = new Document( body ); MainDocumentPart mainDocumentPart = package.MainDocumentPart; // Save changes to the main document part. package.MainDocumentPart.Document.Save(); } StreamReader s = new StreamReader(path); return(s.BaseStream); }
static void Main(string[] args) { RunArgs runArgs = ParseArgs(args); // var markdown = Markdown.Parse(runArgs.MarkdonwPath); RuleJsonSerializer ruleJsonSerializer = new RuleJsonSerializer(); var rules = ruleJsonSerializer.ParseJson(System.IO.File.ReadAllText(runArgs.ConfigPath)); using WordprocessingDocument document = WordprocessingDocument.Create(runArgs.DocxPath, WordprocessingDocumentType.Document); MainDocumentPart mainPart = document.AddMainDocumentPart(); GenerateMainPart(mainPart, runArgs.MarkdonwPath); StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart <StyleDefinitionsPart>("Styles"); // TODO: latent config if needed GenerateStyleDefinitionsPartContent(styleDefinitionsPart, rules, true); FontTablePart fontTablePart1 = mainPart.AddNewPart <FontTablePart>("FontTable"); GeneratedCode.GenerateFontTablePartContent(fontTablePart1); SetPackageProperties(document); }
internal static void GenerateSummaryExport(string path, TECBid bid, TECEstimator estimate, bool openOnComplete = true) { using (WordprocessingDocument package = WordprocessingDocument.Create(path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { package.AddMainDocumentPart(); Document document = new Document(); Body body = new Body(); document.Append(body); package.MainDocumentPart.Document = document; body.Append(introParagraph(bid)); body.Append(laborSummary(estimate)); body.Append(costSummary(estimate)); body.Append(saleSummary(estimate)); package.MainDocumentPart.Document.Save(); } if (openOnComplete) { System.Diagnostics.Process.Start(path); } }
public static void Test_CreateWordDoc_02(string file, string msg) { SetDirectory(); using (WordprocessingDocument doc = WordprocessingDocument.Create(zPath.Combine(_directory, file), WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = doc.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); // String msg contains the text, "Hello, Word!" run.AppendChild(new Text(msg)); //DocumentFormat.OpenXml.OpenXmlElement.NamespaceDeclarations //mainPart.Document.NamespaceDeclarations mainPart.Document.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"); mainPart.Document.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"); } }
/// <summary> /// Generate a Word document /// </summary> /// <param name="number">Document number</param> public void GenerateDocument(long number) { // Evaluate final path string finalPath = this.DestFolder; for (int folder = 0; folder < _depth; folder++) { long n = (long)Math.Pow(this.NbFoldersPerFolder, _depth - folder - 1) * this.NbFoldersPerFolder; finalPath = Path.Combine(finalPath, "Folder" + (number / n).ToString()); } Directory.CreateDirectory(finalPath); string path = Path.Combine(finalPath, $"{GetRandomWord()} {GetRandomWord()} {GetRandomWord()} {number.ToString()}.docx"); // Writing in the word document using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true)) { MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); for (var numPara = 0; numPara < this.NbParagraphesPerDoc; numPara++) { Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); StringBuilder sb = new StringBuilder(); for (var numWord = 0; numWord < this.NbWordsPerParagraph; numWord++) { sb.Append(GetRandomWord() + " "); } run.AppendChild(new Text(sb.ToString())); } } // Raising the progress event _nbDocsGenerated++; OnProgress(_nbDocsGenerated, this.NbTotalDocs); }
// public string GetRawFileData() // { // using (WordprocessingDocument doc = WordprocessingDocument.Open(this.pathFile, false)) // { // string buf = doc.MainDocumentPart.Document.Body.InnerText; // data = buf; // return data; // } // } public void putDataToFile(string data) { // Create a document by supplying the filepath. // using (WordprocessingDocument wordDocument = // WordprocessingDocument.Create(Directory.GetCurrentDirectory() + "\\output.docx", WordprocessingDocumentType.Document)) // { // // Add a main document part. // MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // // // Create the document structure and add some text. // mainPart.Document = new Document(); // Body body = mainPart.Document.AppendChild(new Body()); // Paragraph para = body.AppendChild(new Paragraph()); // Run run = para.AppendChild(new Run()); // run.AppendChild(new Text(data)); // } using (WordprocessingDocument package = WordprocessingDocument.Create(Directory.GetCurrentDirectory() + "\\output.docx", WordprocessingDocumentType.Document)) { // Add a new main document part. package.AddMainDocumentPart(); var validXmlChars = data.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray(); string validData = new string(validXmlChars); // Create the Document DOM. package.MainDocumentPart.Document = new Document( new Body( new Paragraph( new Run( new Text(validData))))); // Save changes to the main document part. package.MainDocumentPart.Document.Save(); } }
public void GeneratePOC_Document(string inputPresentationFullPath, string slideImageDirectoryPath, string outputPOCFullPath) { using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(outputPOCFullPath, WordprocessingDocumentType.Document)) { #region Init Document wordDocument.AddMainDocumentPart(); wordDocument.MainDocumentPart.Document = new Document(); var body = wordDocument.MainDocumentPart.Document.AppendChild(new Body()); InitStylesFor(wordDocument); #endregion using (PresentationDocument inputPresentation = PresentationDocument.Open(inputPresentationFullPath, false)) { for (int currentSlide = 0; currentSlide < inputPresentation.PresentationPart.SlideParts.Count(); currentSlide++) { #region Read all Text from current slide string[] allTextFromCurrentSlide = GetAllTextFromSlide(GetSlide(inputPresentation, currentSlide)); if (allTextFromCurrentSlide == null) { continue; } #endregion InsertEachParagraphIntoWordDocument(wordDocument, allTextFromCurrentSlide, slideImageDirectoryPath, currentSlide); InsertNotesIntoWordDocument(wordDocument, inputPresentation, currentSlide); #region Insert PageBreak if Slide is not last if (currentSlide != inputPresentation.PresentationPart.SlideParts.Count() - 1) { body.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page }))); } #endregion } } } }
public void CreateWordDocument(String file_path, String rtfEncodedString) { using (WordprocessingDocument doc = WordprocessingDocument.Create(file_path, WordprocessingDocumentType.Document)) { // Create main document, add body and paragraph MainDocumentPart mainDocPart = doc.AddMainDocumentPart(); mainDocPart.Document = new Document(); Body body = new Body(); mainDocPart.Document.Append(body); String altChunkId = "Id1"; // Set alternative format RTF to import text AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.Rtf, altChunkId); // Convert rtf to chunk data using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString))) { chunk.FeedData(ms); } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainDocPart.Document.Body.InsertAt( altChunk, 0); // Save changes to the main document part. mainDocPart.Document.Save(); // Open word compatible aplication ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = file_path; Process.Start(startInfo); } }
public void HtmlToWord(string html, string destinationFileName) { using (MemoryStream memoryStream = new MemoryStream()) using (WordprocessingDocument wordDocument = WordprocessingDocument.Create( memoryStream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordDocument.MainDocumentPart; if (mainPart == null) { mainPart = wordDocument.AddMainDocumentPart(); new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart); } HtmlConverter converter = new HtmlConverter(mainPart); converter.ImageProcessing = ImageProcessing.AutomaticDownload; Body body = mainPart.Document.Body; IList <OpenXmlCompositeElement> paragraphs = converter.Parse(html); body.Append(paragraphs); mainPart.Document.Save(); File.WriteAllBytes(destinationFileName, memoryStream.ToArray()); } }
public static byte[] HtmlToWordMethod(String html) { const string filename = "test.docx"; if (File.Exists(filename)) { File.Delete(filename); } using (MemoryStream generatedDocument = new MemoryStream()) { using (WordprocessingDocument package = WordprocessingDocument.Create( generatedDocument, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new Document(new Body()).Save(mainPart); } HtmlConverter converter = new HtmlConverter(mainPart); Body body = mainPart.Document.Body; var paragraphs = converter.Parse(html); for (int i = 0; i < paragraphs.Count; i++) { body.Append(paragraphs[i]); } mainPart.Document.Save(); } return(generatedDocument.ToArray()); } }
public static void CreateWordprocessingDocument(string filepath, string myimage, List <Student> students) { // Create a document by supplying the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run1 = para.AppendChild(new Run()); run1.AppendChild(new Text("Here is a list of students from the ftp directory, with each student getting their own page: ")); foreach (var student in students) { Paragraph para2 = body.AppendChild(new Paragraph()); Run run2 = para2.AppendChild(new Run( new Break() { Type = BreakValues.Page })); run2.AppendChild(new Text(student.FirstName + " " + student.LastName)); if (student.MyRecord == true) { using (FileStream stream = new FileStream(Constants.Locations.imgpath, FileMode.Open)) { imagePart.FeedData(stream); } AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart)); } } } }
public void CanRemoveSmartTags() { XDocument partDocument = XDocument.Parse(SmartTagDocumentXmlString); Assert.True(partDocument.Descendants(W.smartTag).Any()); using (var stream = new MemoryStream()) using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, DocumentType)) { MainDocumentPart part = wordDocument.AddMainDocumentPart(); part.PutXDocument(partDocument); var settings = new SimplifyMarkupSettings { RemoveSmartTags = true }; MarkupSimplifier.SimplifyMarkup(wordDocument, settings); partDocument = part.GetXDocument(); XElement t = partDocument.Descendants(W.t).First(); Assert.False(partDocument.Descendants(W.smartTag).Any()); Assert.Equal(SmartTagDocumentTextValue, t.Value); } }
public void CanReplaceTextWithQuotationMarksAndAddTrackedChangesWhenReplacing() { XDocument partDocument = XDocument.Parse(QuotationMarksDocumentXmlString); XElement p = partDocument.Descendants(W.p).First(); string innerText = InnerText(p); Assert.Equal( "Text can be enclosed in “normal double quotes” and in «double angle quotation marks».", innerText); using (var stream = new MemoryStream()) using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, DocumentType)) { MainDocumentPart part = wordDocument.AddMainDocumentPart(); part.PutXDocument(partDocument); IEnumerable <XElement> content = partDocument.Descendants(W.p); var regex = new Regex(string.Format("{0}(?<words>{1}){2}", LeftDoubleQuotationMarks, Words, RightDoubleQuotationMarks)); int count = OpenXmlRegex.Replace(content, regex, "‘changed ${words}’", null, true, "John Doe"); p = partDocument.Descendants(W.p).First(); innerText = InnerText(p); Assert.Equal(2, count); Assert.Equal( "Text can be enclosed in ‘changed normal double quotes’ and in ‘changed double angle quotation marks’.", innerText); Assert.Contains(p.Elements(W.ins), e => InnerText(e) == "‘changed normal double quotes’"); Assert.Contains(p.Elements(W.ins), e => InnerText(e) == "‘changed double angle quotation marks’"); Assert.Contains(p.Elements(W.del), e => InnerDelText(e) == "“normal double quotes”"); Assert.Contains(p.Elements(W.del), e => InnerDelText(e) == "«double angle quotation marks»"); } }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId8"); GenerateWebSettingsPart1Content(webSettingsPart1); FooterPart footerPart1 = mainDocumentPart1.AddNewPart<FooterPart>("rId13"); GenerateFooterPart1Content(footerPart1); footerPart1.AddHyperlinkRelationship(new System.Uri("http://bjcis/sites/techservices/Informational%20Documents/Forms/AllItems.aspx", System.UriKind.Absolute), true, "rId2"); footerPart1.AddHyperlinkRelationship(new System.Uri("http://bjcis/sites/techservices/Informational%20Documents/BJC%20IS%20Tech%20Management%20Standards.pdf", System.UriKind.Absolute), true, "rId1"); CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId3"); GenerateCustomXmlPart1Content(customXmlPart1); CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId7"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); HeaderPart headerPart1 = mainDocumentPart1.AddNewPart<HeaderPart>("rId12"); GenerateHeaderPart1Content(headerPart1); ImagePart imagePart1 = headerPart1.AddNewPart<ImagePart>("image/png", "rId1"); GenerateImagePart1Content(imagePart1); CustomXmlPart customXmlPart2 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId2"); GenerateCustomXmlPart2Content(customXmlPart2); CustomXmlPropertiesPart customXmlPropertiesPart2 = customXmlPart2.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart2Content(customXmlPropertiesPart2); CustomXmlPart customXmlPart3 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId1"); GenerateCustomXmlPart3Content(customXmlPart3); CustomXmlPropertiesPart customXmlPropertiesPart3 = customXmlPart3.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart3Content(customXmlPropertiesPart3); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId6"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); ImagePart imagePart2 = mainDocumentPart1.AddNewPart<ImagePart>("image/x-emf", "rId11"); GenerateImagePart2Content(imagePart2); NumberingDefinitionsPart numberingDefinitionsPart1 = mainDocumentPart1.AddNewPart<NumberingDefinitionsPart>("rId5"); GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId15"); GenerateThemePart1Content(themePart1); EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart<EndnotesPart>("rId10"); GenerateEndnotesPart1Content(endnotesPart1); CustomXmlPart customXmlPart4 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId4"); GenerateCustomXmlPart4Content(customXmlPart4); CustomXmlPropertiesPart customXmlPropertiesPart4 = customXmlPart4.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart4Content(customXmlPropertiesPart4); FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart<FootnotesPart>("rId9"); GenerateFootnotesPart1Content(footnotesPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId14"); GenerateFontTablePart1Content(fontTablePart1); CustomFilePropertiesPart customFilePropertiesPart1 = document.AddNewPart<CustomFilePropertiesPart>("rId4"); GenerateCustomFilePropertiesPart1Content(customFilePropertiesPart1); SetPackageProperties(document); }
/// <summary> /// Populates the processing document and gets its body element. /// </summary> /// <returns>Body of the document that will hold the dictionary.</returns> private Body GetDocumentBody(WordprocessingDocument processingDocument) { // Create a MainDocumentPart instance MainDocumentPart mainDocPart = processingDocument.AddMainDocumentPart(); mainDocPart.Document = new Document(); // Create a Document instance Document document = mainDocPart.Document; // Create a Body instance Body body = document.AppendChild(new Body()); // Create 2 columns for page layout SectionProperties sectionProperties = new SectionProperties(); Columns columns = new Columns() { ColumnCount = 2 }; columns.Separator = OnOffValue.FromBoolean(true); sectionProperties.Append(columns); body.Append(sectionProperties); return body; }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document, int reportId) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); List<customSection> objArray = new DocxReportMaker().GenerateReport(mainDocumentPart1, reportId); int counter = 1; // Add external image link foreach (customSection item in objArray) { if (item.Image != null) { item.Image.Link = "image" + counter.ToString(); counter++; mainDocumentPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", new System.Uri(item.Image.Url, System.UriKind.Absolute), item.Image.Link); } } //mainDocumentPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", // new System.Uri("http://www.montereybayaquarium.org/storage/promotions/200x125/g_sfw_inthenews.gif", System.UriKind.Absolute), "image1"); // main document area GenerateMainDocumentPart1Content(mainDocumentPart1, objArray); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId3"); GenerateWebSettingsPart1Content(webSettingsPart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId2"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); //StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId1"); //GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId5"); GenerateThemePart1Content(themePart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId4"); GenerateFontTablePart1Content(fontTablePart1); SetPackageProperties(document); }
private static void BuildDocument(List<Source> sources, WordprocessingDocument output) { if (RelationshipMarkup == null) RelationshipMarkup = new Dictionary<XName,XName[]>() { //{ button, new [] { image }}, { A.blip, new [] { R.embed, R.link }}, { A.hlinkClick, new [] { R.id }}, { A.relIds, new [] { R.cs, R.dm, R.lo, R.qs }}, //{ a14:imgLayer, new [] { R.embed }}, //{ ax:ocx, new [] { R.id }}, { C.chart, new [] { R.id }}, { C.externalData, new [] { R.id }}, { C.userShapes, new [] { R.id }}, { DGM.relIds, new [] { R.cs, R.dm, R.lo, R.qs }}, { O.OLEObject, new [] { R.id }}, { VML.fill, new [] { R.id }}, { VML.imagedata, new [] { R.href, R.id, R.pict }}, { VML.stroke, new [] { R.id }}, { W.altChunk, new [] { R.id }}, { W.attachedTemplate, new [] { R.id }}, { W.control, new [] { R.id }}, { W.dataSource, new [] { R.id }}, { W.embedBold, new [] { R.id }}, { W.embedBoldItalic, new [] { R.id }}, { W.embedItalic, new [] { R.id }}, { W.embedRegular, new [] { R.id }}, { W.footerReference, new [] { R.id }}, { W.headerReference, new [] { R.id }}, { W.headerSource, new [] { R.id }}, { W.hyperlink, new [] { R.id }}, { W.printerSettings, new [] { R.id }}, { W.recipientData, new [] { R.id }}, // Mail merge, not required { W.saveThroughXslt, new [] { R.id }}, { W.sourceFileName, new [] { R.id }}, // Framesets, not required { W.src, new [] { R.id }}, // Mail merge, not required { W.subDoc, new [] { R.id }}, // Sub documents, not required //{ w14:contentPart, new [] { R.id }}, { WNE.toolbarData, new [] { R.id }}, }; // This list is used to eliminate duplicate images List<ImageData> images = new List<ImageData>(); output.AddMainDocumentPart(); XDocument mainPart = output.MainDocumentPart.GetXDocumentWithTracking(); mainPart.Declaration.Standalone = "yes"; mainPart.Declaration.Encoding = "UTF-8"; mainPart.Add( new XElement(W.document, NamespaceAttributes, new XElement(W.body))); if (sources.Count > 0) { using (WordprocessingDocument doc = sources[0].WmlDocument.GetWordprocessingDocument()) { CopyStartingParts(doc, output, images); } int sourceNum = 0; foreach (Source source in sources) { using (WordprocessingDocument doc = source.WmlDocument.GetWordprocessingDocument()) { #if TestForUnsupportedDocuments // throws exceptions if a document contains unsupported content TestForUnsupportedDocument(doc, sources.IndexOf(source)); #endif List<XElement> contents = doc.MainDocumentPart.GetXDocumentWithTracking() .Root .Element(W.body) .Elements() .Skip(source.Start) .Take(source.Count) .ToList(); try { AppendDocument(doc, output, contents, source.KeepSections, images); } catch (DocumentBuilderInternalException dbie) { if (dbie.Message.Contains("{0}")) throw new DocumentBuilderException(string.Format(dbie.Message, sourceNum)); else throw dbie; } } ++sourceNum; } if (!sources.Any(s => s.KeepSections)) { using (WordprocessingDocument doc = sources[0].WmlDocument.GetWordprocessingDocument()) { var sectPr = doc.MainDocumentPart.GetXDocumentWithTracking().Root.Element(W.body) .Elements().Last(); if (sectPr.Name == W.sectPr) { AddSectionAndDependencies(doc, output, sectPr, images); output.MainDocumentPart.GetXDocumentWithTracking().Root.Element(W.body).Add(sectPr); } } } else FixUpSectionProperties(output); } }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); object oMissing = System.Reflection.Missing.Value; MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); ChartPart chartPart1 = mainDocumentPart1.AddNewPart<ChartPart>("rId13"); GenerateChartPart1Content(chartPart1); EmbeddedPackagePart embeddedPackagePart1 = chartPart1.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId1"); GenerateEmbeddedPackagePart1Content(embeddedPackagePart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId3"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); ChartPart chartPart2 = mainDocumentPart1.AddNewPart<ChartPart>("rId7"); GenerateChartPart2Content(chartPart2); EmbeddedPackagePart embeddedPackagePart2 = chartPart2.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId1"); GenerateEmbeddedPackagePart2Content(embeddedPackagePart2); using (Stream str = embeddedPackagePart2.GetStream()) using (MemoryStream ms = new MemoryStream()) { CopyStream(str, ms); using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(ms, true)) { // Update data in spreadsheet // Find first worksheet ss.Sheet ws = (ss.Sheet)spreadsheetDoc.WorkbookPart .Workbook.Sheets .FirstOrDefault(); string sheetId = ws.Id; WorksheetPart wsp = (WorksheetPart)spreadsheetDoc .WorkbookPart .Parts .Where(pt => pt.RelationshipId == sheetId) .FirstOrDefault() .OpenXmlPart; ss.SheetData sd = wsp .Worksheet .Elements<ss.SheetData>() .FirstOrDefault(); foreach (ss.Row tsd in sd.Elements<ss.Row>()) { if (tsd.Elements<ss.Cell>().Count()> 1) { ss.Cell cell1 = tsd.Elements<ss.Cell>() .ElementAt(1); if (cell1 != null) { ss.CellValue cell1value = cell1.Elements<ss.CellValue>().FirstOrDefault(); System.Console.WriteLine(cell1value.InnerText+cell1value.Text); if (cell1value != null && !cell1value.InnerText.Equals("0")) { cell1value.Text = "25"; } } } } } // Write the modified memory stream back // into the embedded package part. System.Console.WriteLine(Getbase64String(ms)); if(!embeddedPackagePart2Data.Equals(Getbase64String(ms))) embeddedPackagePart2Data = Getbase64String(ms); ms.Close(); } GenerateEmbeddedPackagePart2Content(embeddedPackagePart2); StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId2"); GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId16"); GenerateThemePart1Content(themePart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId1"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart<EndnotesPart>("rId6"); GenerateEndnotesPart1Content(endnotesPart1); FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart<FootnotesPart>("rId5"); GenerateFootnotesPart1Content(footnotesPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId15"); GenerateFontTablePart1Content(fontTablePart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId4"); GenerateWebSettingsPart1Content(webSettingsPart1); HeaderPart headerPart1 = mainDocumentPart1.AddNewPart<HeaderPart>("rId14"); GenerateHeaderPart1Content(headerPart1); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://en.wikipedia.org/wiki/Million", System.UriKind.Absolute), true, "rId8"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://en.wikipedia.org/wiki/Quadrillion", System.UriKind.Absolute), true, "rId12"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://en.wikipedia.org/wiki/Trillion", System.UriKind.Absolute), true, "rId11"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://en.wikipedia.org/wiki/Billion", System.UriKind.Absolute), true, "rId10"); mainDocumentPart1.AddHyperlinkRelationship(new System.Uri("http://en.wikipedia.org/wiki/1,000,000,000", System.UriKind.Absolute), true, "rId9"); SetPackageProperties(document); }
// Body : BodyType : OpenXmlCompositeElement // Header : OpenXmlPartRootElement : OpenXmlCompositeElement private void _Create(string file, IEnumerable<OXmlElement> elements) { using (_document = WordprocessingDocument.Create(file, WordprocessingDocumentType.Document)) { _mainPart = _document.AddMainDocumentPart(); _mainPart.Document = new Document(); OXmlPicture.AddNamespaceDeclarations(_mainPart.Document); _body = _mainPart.Document.AppendChild(new Body()); foreach (OXmlElement element in elements) { switch (element.Type) { case OXmlElementType.Paragraph: AddParagraph((OXmlParagraphElement)element); break; case OXmlElementType.Text: AddText((OXmlTextElement)element); break; case OXmlElementType.Line: AddLine(); break; case OXmlElementType.TabStop: AddTabStop(); break; case OXmlElementType.SimpleField: AddSimpleField((OXmlSimpleFieldElement)element); break; case OXmlElementType.DocSection: //if (_headerFooter) if (_currentElement != OXmlDocElementType.Body) throw new PBException("DocSection cant be inside Header or Footer"); AddDocSection((OXmlDocSectionElement)element); break; //case OXmlElementType.DocDefaults: // if (_headerFooter) // throw new PBException("DocDefaults cant be inside Header or Footer"); // AddDocDefaults((OXmlDocDefaultsElement)element); // break; case OXmlElementType.DocDefaultsRunProperties: //if (_headerFooter) if (_currentElement != OXmlDocElementType.Body) throw new PBException("DocDefaultsRunProperties cant be inside Header or Footer"); AddRunPropertiesDefault((OXmlDocDefaultsRunPropertiesElement)element); break; case OXmlElementType.DocDefaultsParagraphProperties: //if (_headerFooter) if (_currentElement != OXmlDocElementType.Body) throw new PBException("DocDefaultsParagraphProperties cant be inside Header or Footer"); //AddParagraphPropertiesDefault((OXmlDocDefaultsParagraphPropertiesElement)element); AddParagraphPropertiesDefault(); break; //case OXmlElementType.OpenHeaderFooter: // OpenHeaderFooter((OXmlOpenHeaderFooter)element); // break; case OXmlElementType.OpenHeader: if (_currentElement != OXmlDocElementType.Body) throw new PBException("Open header cant be inside Header or Footer"); OpenHeader((OXmlOpenHeaderElement)element); break; case OXmlElementType.OpenFooter: if (_currentElement != OXmlDocElementType.Body) throw new PBException("Open footer cant be inside Header or Footer"); OpenFooter((OXmlOpenFooterElement)element); break; case OXmlElementType.CloseHeader: if (_currentElement != OXmlDocElementType.Header) throw new PBException("Close header without open header"); CloseHeaderFooter(); break; case OXmlElementType.CloseFooter: if (_currentElement != OXmlDocElementType.Footer) throw new PBException("Close footer without open footer"); CloseHeaderFooter(); break; case OXmlElementType.Style: //if (_headerFooter) if (_currentElement != OXmlDocElementType.Body) throw new PBException("Style cant be inside Header or Footer"); AddStyle((OXmlStyleElement)element); break; case OXmlElementType.Picture: AddPicture((OXmlPictureElement)element); break; default: throw new PBException($"unknow element type {element.Type}"); } } } }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedPart extendedPart1 = document.AddExtendedPart("http://schemas.openxmlformats.org/officedocument/2006/relationships/metadata/core-properties", "application/vnd.openxmlformats-package.core-properties+xml", "xml", "rId1"); GenerateExtendedPart1Content(extendedPart1); ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId2"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId1"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId2"); GenerateFontTablePart1Content(fontTablePart1); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId3"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); TableRow tet = GenTab(); // mainDocumentPart1.Document.Body.ChildElements.GetItem(1).Append(tet); mainDocumentPart1.Document.Body.ChildElements.GetItem(1).InsertAt(tet, 50); SetPackageProperties(document); }
public void Create(HtmlParser parser, Calculator calculator) { // Создание Wordprocessing документа try { myDoc = WordprocessingDocument.Create(MainWindow.Folder + Path.DirectorySeparatorChar + parser.ResultDirName + Path.DirectorySeparatorChar + parser.ResultFileNameWordTable, WordprocessingDocumentType.Document); } catch { // Укорачивание наименование файла в 2 раза, если превышает допустимое кол-во символов int halfLenghtWordFile = parser.ResultFileNameWordTable.Length / 2; string tmpWordStr = parser.ResultFileNameWordTable.Substring(0, halfLenghtWordFile); myDoc = WordprocessingDocument.Create(MainWindow.Folder + Path.DirectorySeparatorChar + parser.ResultDirName + Path.DirectorySeparatorChar + tmpWordStr + ".docx", WordprocessingDocumentType.Document); } // Добавление главной части документа MainDocumentPart mainPart = myDoc.AddMainDocumentPart(); // Создание дерева DOM для простого документа mainPart.Document = new Document(); Body body = new Body(); Table table = new Table(); TableProperties tblPr = new TableProperties(); TableBorders tblBorders = new TableBorders(); tblBorders.TopBorder = new TopBorder(); tblBorders.TopBorder.Val = new EnumValue<BorderValues>(BorderValues.Single); tblBorders.BottomBorder = new BottomBorder(); tblBorders.BottomBorder.Val = new EnumValue<BorderValues>(BorderValues.Single); tblBorders.LeftBorder = new LeftBorder(); tblBorders.LeftBorder.Val = new EnumValue<BorderValues>(BorderValues.Single); tblBorders.RightBorder = new RightBorder(); tblBorders.RightBorder.Val = new EnumValue<BorderValues>(BorderValues.Single); tblBorders.InsideHorizontalBorder = new InsideHorizontalBorder(); tblBorders.InsideHorizontalBorder.Val = BorderValues.Single; tblBorders.InsideVerticalBorder = new InsideVerticalBorder(); tblBorders.InsideVerticalBorder.Val = BorderValues.Single; tblPr.Append(tblBorders); table.Append(tblPr); // Первый ряд с наименованием файла TableRow tr; TableCell tc; tr = new TableRow(); tc = new TableCell(new Paragraph(new Run( new Text(parser.ResultFileNameWordTable.Replace(".docx", ""))))); TableCellProperties tcp = new TableCellProperties(); GridSpan gridSpan = new GridSpan(); gridSpan.Val = 5; tcp.Append(gridSpan); tc.Append(tcp); tr.Append(tc); table.Append(tr); // Последующие ряды tr = new TableRow(); tc = new TableCell(); for (int i = 1; i <= 5; i++) { switch (i) { case 1: tr.Append(new TableCell(new Paragraph(new Run(new Text("№"))))); break; case 2: tr.Append(new TableCell(new Paragraph(new Run(new Text("Показатель"))))); break; case 3: tr.Append(new TableCell(new Paragraph(new Run(new Text("Взвешенная оценка"))))); break; case 4: tr.Append(new TableCell(new Paragraph(new Run(new Text("Оценка"))))); break; case 5: tr.Append(new TableCell(new Paragraph(new Run(new Text("Вес показателя"))))); break; } } table.Append(tr); int tmpInt = 1; for (int i = 1; i <= 9; i++) { tr = new TableRow(); if (i <= 7) { tc = new TableCell(new Paragraph(new Run(new Text(i.ToString())))); } else { tc = new TableCell(new Paragraph(new Run(new Text("")))); } tr.Append(tc); for (int j = 1; j <= 4; j++) { switch (tmpInt) { case 1: tr.Append(new TableCell(new Paragraph(new Run(new Text("Изменение выручки"))))); break; case 2: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogIzmeneniyaViruchki.ToString()))))); break; case 3: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogIzmeneniyaViruchki.ToString()))))); break; case 4: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2"))))); break; case 5: tr.Append(new TableCell(new Paragraph(new Run(new Text("Коэффициент текущей ликвидности"))))); break; case 6: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogKoeficientaTekucsheyLikvidnosti.ToString()))))); break; case 7: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogKoeficientaTekucsheyLikvidnosti.ToString()))))); break; case 8: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2"))))); break; case 9: tr.Append(new TableCell(new Paragraph(new Run(new Text("Коэффициент финансовой независимости"))))); break; case 10: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogKoeficientaFinNezavisimosti.ToString()))))); break; case 11: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogKoeficientaFinNezavisimosti.ToString()))))); break; case 12: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2"))))); break; case 13: tr.Append(new TableCell(new Paragraph(new Run(new Text("Чистые активы"))))); break; case 14: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogChistihActivov.ToString()))))); break; case 15: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogChistihActivov.ToString()))))); break; case 16: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2"))))); break; case 17: tr.Append(new TableCell(new Paragraph(new Run(new Text("Рентабельность продаж"))))); break; case 18: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogRentabelnostiProdag.ToString()))))); break; case 19: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogRentabelnostiProdag.ToString()))))); break; case 20: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,05"))))); break; case 21: tr.Append(new TableCell(new Paragraph(new Run(new Text("Рентабельность деятельности"))))); break; case 22: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogRentabelnostiDeyatelnosti.ToString()))))); break; case 23: tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogRentabelnostiDeyatelnosti.ToString()))))); break; case 24: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,15"))))); break; case 25: tr.Append(new TableCell(new Paragraph(new Run(new Text("Коэффициент оборачиваемости (динамика)"))))); break; case 26: tr.Append(new TableCell(new Paragraph(new Run(new Text())))); break; case 27: tr.Append(new TableCell(new Paragraph(new Run(new Text())))); break; case 28: tr.Append(new TableCell(new Paragraph(new Run(new Text("0,1"))))); break; case 29: tr.Append(new TableCell(new Paragraph(new Run(new Text("Итого: "))))); break; case 30: tr.Append(new TableCell(new Paragraph(new Run(new Text())))); break; case 31: tr.Append(new TableCell(new Paragraph(new Run(new Text())))); break; case 32: tr.Append(new TableCell(new Paragraph(new Run(new Text())))); break; case 33: tr.Append(new TableCell(new Paragraph(new Run(new Text("Оценка финансового положения заемщика"))))); break; case 34: tc = new TableCell(new Paragraph(new Run( new Text("")))); tcp = new TableCellProperties(); gridSpan = new GridSpan(); gridSpan.Val = 3; tcp.Append(gridSpan); tc.Append(tcp); tr.Append(tc); break; } tmpInt++; } table.Append(tr); } // Добавления таблицы к основе body.Append(table); // Добавление основы к документу mainPart.Document.Append(body); // Сохрание изменений главной части документа mainPart.Document.Save(); myDoc.Dispose(); }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); NumberingDefinitionsPart numberingDefinitionsPart1 = mainDocumentPart1.AddNewPart<NumberingDefinitionsPart>("rId1"); GenerateMainDocumentPart1Content(mainDocumentPart1); ImagePart imagePart1 = mainDocumentPart1.AddNewPart<ImagePart>("image/gif", "rId8"); GenerateImagePart1Content(imagePart1); FooterPart footerPart1 = mainDocumentPart1.AddNewPart<FooterPart>("rId13"); GenerateFooterPart1Content(footerPart1); ImagePart imagePart2 = footerPart1.AddNewPart<ImagePart>("image/gif", "rId2"); GenerateImagePart2Content(imagePart2); ImagePart imagePart3 = footerPart1.AddNewPart<ImagePart>("image/gif", "rId1"); GenerateImagePart3Content(imagePart3); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId3"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); documentSettingsPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new System.Uri("file:///C:\\Documents%20and%20Settings\\ppelletier.RUSSELL\\Application%20Data\\Microsoft\\Templates\\RADAR%20Template.dot", System.UriKind.Absolute), "rId1"); ImagePart imagePartOverallEval1 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartOverallEval1"); GenerateImagePartOverallEvalContent(imagePartOverallEval1, imagePartOverallEval1Data); ImagePart imagePartOverallEval2 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartOverallEval2"); GenerateImagePartOverallEvalContent(imagePartOverallEval2, imagePartOverallEval2Data); ImagePart imagePartOverallEval3 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartOverallEval3"); GenerateImagePartOverallEvalContent(imagePartOverallEval3, imagePartOverallEval3Data); ImagePart imagePartOverallEval4 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartOverallEval4"); GenerateImagePartOverallEvalContent(imagePartOverallEval4, imagePartOverallEval4Data); HeaderPart headerPart1 = mainDocumentPart1.AddNewPart<HeaderPart>("rId12"); GenerateHeaderPart1Content(headerPart1); ImagePart imagePart5 = headerPart1.AddNewPart<ImagePart>("image/png", "rId1"); GenerateImagePart5Content(imagePart5); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId2"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1); EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart<EndnotesPart>("rId6"); GenerateEndnotesPart1Content(endnotesPart1); FooterPart footerPart2 = mainDocumentPart1.AddNewPart<FooterPart>("rId11"); GenerateFooterPart2Content(footerPart2); footerPart2.AddPart(imagePart2, "rId2"); footerPart2.AddPart(imagePart3, "rId1"); FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart<FootnotesPart>("rId5"); GenerateFootnotesPart1Content(footnotesPart1); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId15"); GenerateThemePart1Content(themePart1); HeaderPart headerPart2 = mainDocumentPart1.AddNewPart<HeaderPart>("rId10"); GenerateHeaderPart2Content(headerPart2); ImagePart imagePart6 = headerPart2.AddNewPart<ImagePart>("image/jpeg", "rId1"); GenerateImagePart6Content(imagePart6); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId4"); GenerateWebSettingsPart1Content(webSettingsPart1); ImagePart imagePartTopicRank1 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartTopicRank1"); GenerateImagePartTopicRankContent(imagePartTopicRank1, imagePartTopicRank1Data); ImagePart imagePartTopicRank2 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartTopicRank2"); GenerateImagePartTopicRankContent(imagePartTopicRank2, imagePartTopicRank2Data); ImagePart imagePartTopicRank3 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartTopicRank3"); GenerateImagePartTopicRankContent(imagePartTopicRank3, imagePartTopicRank3Data); ImagePart imagePartTopicRank4 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartTopicRank4"); GenerateImagePartTopicRankContent(imagePartTopicRank4, imagePartTopicRank4Data); ImagePart imagePartTopicRank5 = mainDocumentPart1.AddNewPart<ImagePart>("image/png", "rIdImgPartTopicRank5"); GenerateImagePartTopicRankContent(imagePartTopicRank5, imagePartTopicRank5Data); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId14"); GenerateFontTablePart1Content(fontTablePart1); SetPackageProperties(document); }
// Adds child parts and generates content of the specified part. private void CreateParts(WordprocessingDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart(); GenerateMainDocumentPart1Content(mainDocumentPart1); FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart<FontTablePart>("rId13"); GenerateFontTablePart1Content(fontTablePart1); StylesWithEffectsPart stylesWithEffectsPart1 = mainDocumentPart1.AddNewPart<StylesWithEffectsPart>("rId3"); GenerateStylesWithEffectsPart1Content(stylesWithEffectsPart1); EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart<EndnotesPart>("rId7"); GenerateEndnotesPart1Content(endnotesPart1); FooterPart footerPart1 = mainDocumentPart1.AddNewPart<FooterPart>("rId12"); GenerateFooterPart1Content(footerPart1); StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart<StyleDefinitionsPart>("rId2"); GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1); CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart<CustomXmlPart>("application/xml", "rId1"); GenerateCustomXmlPart1Content(customXmlPart1); CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart<CustomXmlPropertiesPart>("rId1"); GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1); FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart<FootnotesPart>("rId6"); GenerateFootnotesPart1Content(footnotesPart1); HeaderPart headerPart1 = mainDocumentPart1.AddNewPart<HeaderPart>("rId11"); GenerateHeaderPart1Content(headerPart1); WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart<WebSettingsPart>("rId5"); GenerateWebSettingsPart1Content(webSettingsPart1); FooterPart footerPart2 = mainDocumentPart1.AddNewPart<FooterPart>("rId10"); GenerateFooterPart2Content(footerPart2); DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart<DocumentSettingsPart>("rId4"); GenerateDocumentSettingsPart1Content(documentSettingsPart1); HeaderPart headerPart2 = mainDocumentPart1.AddNewPart<HeaderPart>("rId9"); GenerateHeaderPart2Content(headerPart2); ThemePart themePart1 = mainDocumentPart1.AddNewPart<ThemePart>("rId14"); GenerateThemePart1Content(themePart1); }
private static void BuildDocument(List<Source> sources, WordprocessingDocument output) { // This list is used to eliminate duplicate images List<ImageData> images = new List<ImageData>(); output.AddMainDocumentPart(); XDocument mainPart = output.MainDocumentPart.GetXDocument(); mainPart.Add(new XElement(ns + "document", ns_attrs, new XElement(ns + "body"))); if (sources.Count > 0) { output.CopyStartingParts(sources[0].Document, images); bool lastKeepSections = false; foreach (Source source in sources) { output.AppendDocument(source.Document, source.Contents, source.KeepSections, lastKeepSections, images); lastKeepSections = source.KeepSections; } } }
// Add footer public static bool AddFooter(WordprocessingDocument doc, string footerText) { try { // handler for doc main part var mainDocPart = doc.MainDocumentPart; if (doc == null) { mainDocPart = doc.AddMainDocumentPart(); } if (mainDocPart.Document == null) { mainDocPart.Document = new Document(); } // call for footer return ApplyFooter(doc, footerText); } catch (Exception) { return false; } }
/// <summary> /// Constructor for creating a new document. /// </summary> /// <param name="filePath">Path to where the new file should be created.</param> public OpenXmlHelper(string filePath) { _filePath = filePath; if (File.Exists(filePath)) { _package = WordprocessingDocument.Open(filePath, true); //TODO: ADD SEPERATOR TO OPENED DOCUMENT BEFORE APPENDING Debug.WriteLine("Opened existing file {0}", filePath); _document = _package.MainDocumentPart.Document; } else { _package = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document); if (File.Exists(_filePath)) { MainDocumentPart main = _package.AddMainDocumentPart(); main.Document = new Document(); Document document = main.Document; Body body = document.AppendChild(new Body()); _document = _package.MainDocumentPart.Document; _document.Save(); } else { Debug.WriteLine("Failed to create the file: {0}", filePath); } } }
public WordprocessingDocument CreateWordprocessingDocument(string path) { try { document = WordprocessingDocument.Create(path, DocumentFormat.OpenXml.WordprocessingDocumentType.Document); MainDocumentPart mainDocumentPart = document.AddMainDocumentPart(); mainDocumentPart.Document = new Wordprocessing.Document(); Wordprocessing.Body body = insertinform(); mainDocumentPart.Document.AppendChild(body); document.MainDocumentPart.Document.Save(); return document; } catch (System.IO.IOException) { Console.WriteLine("Файл используется"); return null; } }