public static TableRow CreateRow(MainDocumentPart mainPart, string[] c, bool bolds, bool italics, bool underlines, JustificationValues justifications, int cell) { TableRow tRow = new TableRow(); for (int j = 0; j < cell; j++) { AddStyle(mainPart, bolds, italics, underlines, $"0{j}", $"Table{j}"); TableCell tc = new TableCell(); Paragraph p = CreateParagraphWithStyle($"0{j}", justifications); AddTextToParagraph(p, c[j]); tc.Append(p); tRow.Append(tc); } return(tRow); }
/// <summary> ///Создание колонтитула /// </summary> /// <param name="mainDocument">Документ</param> /// <param name="isp">Шаблон</param> /// <param name="phone">Шаблон</param> public void FottersAddDocument(MainDocumentPart mainDocument, string isp, string phone) { var fotters = FotterGenerate.AddFotters(mainDocument); var paragraph = new RunGenerate(); Footer footer = new Footer(); var par1 = paragraph.RunParagraphGeneratorStandart(); par1.Append(FormulandFooters(isp)); var par2 = paragraph.RunParagraphGeneratorStandart(); par2.Append(FormulandFooters(phone)); footer.Append(par1); footer.Append(par2); fotters.Footer = footer; }
/// <summary> /// Constructor. /// </summary> /// <param name="mainPart">The mainDocumentPart of a document where to write the conversion to.</param> /// <remarks>We preload some configuration from inside the document such as style, bookmarks,...</remarks> public HtmlConverter(MainDocumentPart mainPart) { if (mainPart == null) { throw new ArgumentNullException("mainPart"); } this.mainPart = mainPart; this.RenderPreAsTable = true; this.ImageProcessing = ImageProcessing.AutomaticDownload; this.knownTags = InitKnownTags(); this.htmlStyles = new HtmlDocumentStyle(mainPart); this.knownImageParts = new Dictionary <Uri, CachedImagePart>(); this.WebProxy = new WebProxy(); }
public void CreateWord(WordprocessingDocument package, CardFaceUl template, object obj) { MainDocumentPart mainDocumentPart = package.AddMainDocumentPart(); DocumentFormat.OpenXml.Wordprocessing.Document document = new DocumentFormat.OpenXml.Wordprocessing.Document(); PageSetting settingPage = new PageSetting(); DocumentsPreChek documentInvoice = new DocumentsPreChek(); document.Append(settingPage.ParametrPageHorizontEditMargin(new PageMargin() { Top = 567, Right = 200, Bottom = 567, Left = 200 })); document.Append(documentInvoice.GenerateSalesBookReportNote(template, (int)obj)); mainDocumentPart.Document = document; }
public void CreateWord(WordprocessingDocument package, EfDatabase.Journal.AllJournal template, object obj) { MainDocumentPart mainDocumentPart = package.AddMainDocumentPart(); DocumentFormat.OpenXml.Wordprocessing.Document document = new DocumentFormat.OpenXml.Wordprocessing.Document(); PageSetting settingPage = new PageSetting(); DocumentsFull documentInvoice = new DocumentsFull(); document.Append(settingPage.ParametrPageHorizontEditMargin(new PageMargin() { Top = 1701, Right = 1134, Bottom = 850, Left = 1134 })); document.Append(documentInvoice.CreateJournal(template)); mainDocumentPart.Document = document; }
/// <summary> ///Создание колонтитула /// </summary> /// <param name="mainDocument">Документ</param> /// <param name="tamplate">Шаблон</param> public void FottersAddDocument(MainDocumentPart mainDocument, LibaryXMLAutoReports.FullTemplateSheme.Document tamplate) { var fotters = FotterGenerate.AddFotters(mainDocument); var paragraph = new RunGenerate(); Footer footer = new Footer(); var par1 = paragraph.RunParagraphGeneratorStandart(); par1.Append(FormulandFooters(tamplate.Templates.Stone.Stone4)); var par2 = paragraph.RunParagraphGeneratorStandart(); par2.Append(FormulandFooters(tamplate.Templates.Stone.Stone5)); footer.Append(par1); footer.Append(par2); fotters.Footer = footer; }
public static void CreateDoc(OperatorWordInfo 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, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
// For help with how to work with OpenXml documents: // https://docs.microsoft.com/en-us/office/open-xml/how-do-i public void Generate(SubmittedGeneralRegistrationForm Form, TimeZoneInfo TimeZone, string FileName) { if (File.Exists(FileName)) { File.Delete(FileName); } using (WordprocessingDocument document = WordprocessingDocument.Create(FileName, WordprocessingDocumentType.Document)) { // Create the main document part MainDocumentPart mainPart = document.AddMainDocumentPart(); LSSDDocumentStyles.AddStylesToDocument(document); mainPart.Document = GenerateBody(Form, TimeZone); } }
public static Drawing InsertAPicture(WordprocessingDocument doc, string fileName) { MainDocumentPart mainPart = doc.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); using (FileStream stream = new FileStream(fileName, FileMode.Open)) { imagePart.FeedData(stream); } Drawing dw = AddImageToBody(mainPart.GetIdOfPart(imagePart)); return(dw); }
public void CreateWord(WordprocessingDocument package, Otdel templateotdel, SenderUsers senders, object obj) { MainDocumentPart mainDocumentPart = package.AddMainDocumentPart(); DocumentFormat.OpenXml.Wordprocessing.Document document = new DocumentFormat.OpenXml.Wordprocessing.Document(); PageSetting settingpage = new PageSetting(); DocumentsFull documentInvoce = new DocumentsFull(); document.Append(settingpage.ParametrPageHorizontEditMargin(new PageMargin() { Top = 300, Right = 794, Bottom = 100, Left = 794, Header = 300, Footer = 700U, Gutter = 0U })); document.Append(documentInvoce.GenerateRuleUserTemplate(templateotdel, senders)); mainDocumentPart.Document = document; }
private Footer AddFooter(HeaderFooterValues type) { var part = MainDocumentPart.AddNewPart <FooterPart>(); var id = MainDocumentPart.GetIdOfPart(part); GenerateFooterPartContent(part); GetBodySectionProperty().PrependChild(new FooterReference() { Id = id, Type = type }); return(new Footer(part, this, type)); }
//private List<SdtBlock> GetSdtBlocks(MainDocumentPart mainPart) //{ // return mainPart.Document.Body.Descendants<SdtBlock>().ToList(); //} private List <DocumentFormat.OpenXml.Wordprocessing.Tag> GetAllTags(MainDocumentPart mainPart) { List <DocumentFormat.OpenXml.Wordprocessing.Tag> tags = new List <DocumentFormat.OpenXml.Wordprocessing.Tag>(); foreach (HeaderPart header in mainPart.HeaderParts.ToList()) { tags.AddRange(header.Header.Descendants <DocumentFormat.OpenXml.Wordprocessing.Tag>().ToList()); } foreach (FooterPart footer in mainPart.FooterParts.ToList()) { tags.AddRange(footer.Footer.Descendants <DocumentFormat.OpenXml.Wordprocessing.Tag>().ToList()); } tags.AddRange(mainPart.Document.Body.Descendants <DocumentFormat.OpenXml.Wordprocessing.Tag>().ToList()); return(tags); }
private void button2_Click(object sender, EventArgs e) { //AddHeaderFromTo(@"C:\Temp\Teste1.docx", @"C:\Temp\Teste2.docx"); using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Temp\Teste2.docx", true)) { string altChunkId = "AltChunkId5"; MainDocumentPart mainDocPart = doc.MainDocumentPart; AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf, altChunkId); string rtfEncodedString = richTextBox1.Rtf; using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString))) { chunk.FeedData(ms); } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; // Funciona adicionando na sequencia //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last()); //teste para adicionar no cabeçalho //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last()); // itera os elementos do documento //var paragraphs = doc.MainDocumentPart.Document.Body.Elements<Paragraph>(); // Iterate through paragraphs, runs, and text, finding the text we want and replacing it //foreach (Paragraph paragraph in paragraphs) //{ // foreach (Run run in paragraph.Elements<Run>()) // { // foreach (Text text in run.Elements<Text>()) // { // if (text.Text == "CABEÇALHO") // { // text.Text = "CABEÇALHO 2"; // } // } // } //} mainDocPart.Document.Save(); } }
public static void UpdateImageFromPath(this MainDocumentPart mainPart, SdtElement element, string imgPath) { var picture = element.Descendants<SdtContentPicture>().FirstOrDefault(); if (picture != null) { var dr = element.Descendants<Drawing>().FirstOrDefault(); if (dr != null) { var blip = dr.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault(); if (blip != null) { var embed = blip.Embed; if (embed != null) { IdPartPair idpp = mainPart.Parts .Where(pa => pa.RelationshipId == embed).FirstOrDefault(); ImagePart ip = (ImagePart)idpp.OpenXmlPart; using (FileStream fileStream = File.Open(imgPath, FileMode.Open)) ip.FeedData(fileStream); } else { ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); blip.Embed = mainPart.GetIdOfPart(imagePart); System.IO.Stream data = new System.IO.MemoryStream(File.ReadAllBytes(imgPath)); // using (FileStream stream = new FileStream(imgPath, FileMode.Open)) { imagePart.FeedData(data); data.Close(); } Console.WriteLine("test"); // element.InnerXml = "<w:rPr><w:noProof /></w:rPr><w:tag w:val=\"MyProvider:CoolImage\" /><w:id w:val=\"2083329445\" /><w:picture /></w:sdtPr><w:sdtEndPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" /><w:sdtContent xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:p w:rsidR=\"00646939\" w:rsidP=\"00646939\" w:rsidRDefault=\"00646939\"><w:pPr><w:rPr><w:noProof /></w:rPr></w:pPr><w:r w:rsidRPr=\"00646939\"><w:rPr><w:noProof /></w:rPr><w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\" wp14:anchorId=\"40D5DA71\" wp14:editId=\"48213C65\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"><wp:extent cx=\"4605338\" cy=\"3673658\" /><wp:effectExtent l=\"0\" t=\"0\" r=\"5080\" b=\"3175\" /><wp:docPr id=\"2\" name=\"Picture 2\" /><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" noChangeAspect=\"1\" /></wp:cNvGraphicFramePr><a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:nvPicPr><pic:cNvPr id=\"1\" name=\"\" /><pic:cNvPicPr /></pic:nvPicPr><pic:blipFill><a:blip r:embed=\"rId6\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" /><a:stretch><a:fillRect /></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\" /><a:ext cx=\"4613233\" cy=\"3679955\" /></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst /></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:sdtContent>"; // Console.WriteLine(element.InnerXml); // element.Parent.Remove(); // element.Remove(); // mainPart.Document.AppendChild(element); } } } } }
/// <summary> /// Create an OpenXml Word Document from the CML /// </summary> /// <param name="cml">Input Chemistry</param> /// <param name="guid">Bookmark to create</param> /// <param name="options"></param> /// <param name="telemetry"></param> /// <param name="topLeft"></param> /// <returns></returns> public static string CreateFromCml(string cml, string guid, Options options, IChem4WordTelemetry telemetry, Point topLeft) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; CMLConverter cc = new CMLConverter(); Model.Model m = cc.Import(cml); if (m.AllErrors.Count > 0 || m.AllWarnings.Count > 0) { if (m.AllErrors.Count > 0) { telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, m.AllErrors)); } if (m.AllWarnings.Count > 0) { telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, m.AllWarnings)); } } string fileName = Path.Combine(Path.GetTempPath(), $"Chem4Word-V3-{guid}.docx"); bool canRender = m.AllAtoms.Count > 0 && (m.MeanBondLength > Constants.BondLengthTolerance / 2 || m.AllBonds.Count == 0); if (canRender) { string bookmarkName = Constants.OoXmlBookmarkPrefix + guid; // Create a Wordprocessing document. using (WordprocessingDocument package = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { // Add a new main document part. MainDocumentPart mdp = package.AddMainDocumentPart(); mdp.Document = new Document(new Body()); Body docbody = package.MainDocumentPart.Document.Body; // This is for test //AddParagraph(docbody, "Hello World", bookmarkName); // This will be live AddPictureFromModel(docbody, m, bookmarkName, options, telemetry, topLeft); // Save changes to the main document part. package.MainDocumentPart.Document.Save(); } } return(fileName); }
private void btnSimpleWordTest_Click(object sender, EventArgs e) { try { string filepath = "test.docx"; string msg = "Hello World!"; using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.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()); // Define the styles addHeading1Style(mainPart); // Add heading Paragraph headingPar = createHeading("Testo semplice"); body.AppendChild(headingPar); // Add simple text Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); // String msg contains the text, "Hello, Word!" run.AppendChild(new Text(msg)); // Add heading headingPar = createHeading("Testo con stili"); body.AppendChild(headingPar); // Append a paragraph with styles Paragraph newPar = createParagraphWithStyles(); body.AppendChild(newPar); //Append a table Table myTable = createTable(); body.AppendChild(myTable); } MessageBox.Show("IL DOCUMENTO E' PRONTO"); } catch (Exception) { MessageBox.Show("SEI SCEMO"); } }
public void MustEndPowerToolsBlockToUseStronglyTypedClasses() { using var stream = new MemoryStream(); CreateEmptyWordprocessingDocument(stream); using WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true); MainDocumentPart part = wordDocument.MainDocumentPart ?? throw new InvalidOperationException(); // Add a paragraph through the SDK. Body body = part.Document.Body ?? throw new InvalidOperationException(); body.AppendChild(new Paragraph(new Run(new Text("Added through SDK")))); // Begin the PowerTools Block, which saves any changes made through the strongly // typed SDK classes to the parts of the WordprocessingDocument. // In this case, this could also be done by invoking the Save method on the // WordprocessingDocument, which will save all parts that had changes, or by // invoking part.RootElement.Save() for the one part that was changed. wordDocument.BeginPowerToolsBlock(); // Add a paragraph through the PowerTools. XDocument content = part.GetXDocument(); XElement bodyElement = content.Descendants(W.body).First(); bodyElement.Add(new XElement(W.p, new XElement(W.r, new XElement(W.t, "Added through PowerTools")))); part.PutXDocument(); // Get the part's content through the SDK. However, we will only see what we // added through the SDK, not what we added through the PowerTools functionality. body = part.Document.Body ?? throw new InvalidOperationException(); List <Paragraph> paragraphs = body.Elements <Paragraph>().ToList(); Assert.Single(paragraphs); Assert.Equal("Added through SDK", paragraphs[0].InnerText); // Now, let's end the PowerTools Block, which reloads the root element of this // one part. Reloading those root elements this way is fine if you know exactly // which parts had their content changed by the Open XML PowerTools. wordDocument.EndPowerToolsBlock(); // Get the part's content through the SDK. Having reloaded the root element, // we should now see both paragraphs. body = part.Document.Body ?? throw new ArgumentException(); paragraphs = body.Elements <Paragraph>().ToList(); Assert.Equal(2, paragraphs.Count); Assert.Equal("Added through SDK", paragraphs[0].InnerText); Assert.Equal("Added through PowerTools", paragraphs[1].InnerText); }
/// <summary> /// Header Style name will be "MyHeading1" /// </summary> /// <param name="mainPart"></param> public static void AddHeaderStylePart(ref MainDocumentPart mainPart) { StyleDefinitionsPart stylePart = mainPart.AddNewPart <StyleDefinitionsPart>(); // we have to set the properties RunProperties rPr = new RunProperties(); Color color = new Color() { Val = "black" }; // the color is red RunFonts rFont = new RunFonts(); rFont.Ascii = "Arial"; // the font is Arial rPr.Append(color); rPr.Append(rFont); rPr.Append(new Bold()); // it is Bold rPr.Append(new FontSize() { Val = "28" }); //font size (in 1/72 of an inch) //creation of a style Style style = new Style(); style.StyleId = "MyHeading1"; //this is the ID of the style style.Append(new Name() { Val = "My Heading 1" }); //this is name // our style based on Normal style style.Append(new BasedOn() { Val = "Heading1" }); // the next paragraph is Normal type style.Append(new NextParagraphStyle() { Val = "Normal" }); style.Append(rPr);//we are adding properties previously defined // we have to add style that we have created to the StylePart stylePart.Styles = new Styles(); stylePart.Styles.Append(style); stylePart.Styles.Save(); // we save the style part }
//gavdcodeend 09 //gavdcodebegin 10 public static void WordOpenXmlCreateAndApplyStyleParagraph() { using (WordprocessingDocument myWordDoc = WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true)) { MainDocumentPart docMainPart = myWordDoc.MainDocumentPart; StyleDefinitionsPart stylePart = docMainPart.StyleDefinitionsPart; Style myStyle = new Style { Type = StyleValues.Paragraph, CustomStyle = true, StyleId = "MyHeading1" }; RunProperties runProps = new RunProperties( new Name() { Val = "My Heading 1" }, new BasedOn() { Val = "Heading1" }, new NextParagraphStyle() { Val = "Normal" } ); stylePart.Styles = new Styles(); stylePart.Styles.Append(myStyle); stylePart.Styles.Save(); Body docBody = docMainPart.Document.Body; Paragraph docParagraph = docBody.AppendChild(new Paragraph()); ParagraphProperties paragraphProps = new ParagraphProperties(); paragraphProps.ParagraphStyleId = new ParagraphStyleId() { Val = "MyHeading1" }; docParagraph.Append(paragraphProps); Run docRun = docParagraph.AppendChild(new Run()); docRun.AppendChild(new Text("This is the Heading with style")); } }
static void Main(string[] args) { const string filename = "test.docx"; string html = ResourceHelper.GetString("Resources.CompleteRunTest.html"); if (File.Exists(filename)) { File.Delete(filename); } using (MemoryStream generatedDocument = new MemoryStream()) { // Uncomment and comment the second using() to open an existing template document // instead of creating it from scratch. using (var buffer = ResourceHelper.GetStream("Resources.template.docx")) buffer.CopyToAsync(generatedDocument); generatedDocument.Position = 0L; using (WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true)) //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.WebProxy.Credentials = new System.Net.NetworkCredential("nizeto", "****", "domain"); //converter.WebProxy.Proxy = new System.Net.WebProxy("proxy01:8080"); //comment the lines below to use absolute image URLs converter.ImageProcessing = ImageProcessing.ManualProvisioning; converter.ProvisionImage += OnProvisionImage; Body body = mainPart.Document.Body; converter.ParseHtml(html); mainPart.Document.Save(); AssertThatOpenXmlDocumentIsValid(package); } File.WriteAllBytes(filename, generatedDocument.ToArray()); } System.Diagnostics.Process.Start(filename); }
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 } })); if (info.RequestFlowers != null) { foreach (var rp in info.RequestFlowers) { foreach (var flower in rp.Flowers) { docBody.AppendChild(CreateParagraph(new WordParagraph { Texts = new List <string> { "В заявке «" + rp.RequestName, "» " + flower.Item2 + " цветков «" + flower.Item1 + "»" }, TextProperties = new WordParagraphProperties { Bold = false, Size = "24", JustificationValues = JustificationValues.Both } })); } } } docBody.AppendChild(CreateSectionProperties()); wordDocument.MainDocumentPart.Document.Save(); } }
private void SetHtml(MainDocumentPart mainDocumentPart, string sdtBlockTag, string value, OpenXmlElement elem) { string html = "<html><body><div>" + value + "</div></body></html>"; string altChunkId = sdtBlockTag; MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(html)); AlternativeFormatImportPart formatImportPart = mainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.Html, altChunkId); formatImportPart.FeedData(ms); ms.Close(); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; elem.Append(altChunk); }
static void Main(string[] args) { // Open a WordprocessingDocument for editing using the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create("/output/Hello world.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($"Hello world @ {DateTime.Now.ToLongTimeString()}")); } }
public static void InsertAPicture(string document, string fileName) { using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true)) { MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); using (FileStream stream = new FileStream(fileName, FileMode.Open)) { imagePart.FeedData(stream); } AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart)); } }
/// <summary> /// Refreshes the charts. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> protected override void RefreshCharts(MainDocumentPart mainDocumentPart) { if (mainDocumentPart != null) { foreach (ChartPart chartPart in mainDocumentPart.ChartParts) { Chart chart = chartPart.ChartSpace.Elements <Chart>().FirstOrDefault(); if (chart != null) { } chartPart.ChartSpace.Save(); } } }
public static void CreateWordDocument(string filepath, string text) { // 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()); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(text)); } }
// // // // // // 1st test // // // // // // public static void CreateBareFile() { string outputFileNameAndPath = Path.Combine(Program.outputFilePath, Guid.NewGuid().ToString() + "_barefile_nostyle" + ".docx"); using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(outputFileNameAndPath, WordprocessingDocumentType.Document, true)) { MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // add a main document part mainPart.Document = new Document(); // create the document and add body object Body body = new Body(); mainPart.Document.Append(body); } Console.WriteLine(string.Format("{0}:{1}{2}{1}{3}", "1. Bare file with no styles", Environment.NewLine, outputFileNameAndPath, new string('-', 80))); }
/// <summary> /// Generates and serialized the document. /// </summary> /// <returns></returns> public MemoryStream GenerateDocument() { var mem = new MemoryStream(); byte[] byteArray = _repository.Templates.FirstOrDefault(t => t.Name == "SmartAwardForm").DataStream; mem.Write(byteArray, 0, byteArray.Length); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(mem, true)) { MainDocumentPart mainPart = wordDocument.MainDocumentPart; SmartAwardMappedFieldSet fields = new SmartAwardMappedFieldSet(mainPart); fields.WriteXMLToFields(awardForm.FormDataXml); mainPart.Document.Save(); } mem.Seek(0, SeekOrigin.Begin); return(mem); }
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); } }
static void RemovePageBreaks(string filename) { using (WordprocessingDocument myDoc = WordprocessingDocument.Open(filename, true)) { MainDocumentPart mainPart = myDoc.MainDocumentPart; List <Break> breaks = mainPart.Document.Descendants <Break>().ToList(); foreach (Break b in breaks) { b.Remove(); } mainPart.Document.Save(); } }