Exemple #1
0
 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
             }
         }));
         Table           table   = new Table();
         TableProperties tblProp = new TableProperties(
             new TableBorders(
                 new TopBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new BottomBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new LeftBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new RightBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new InsideHorizontalBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new InsideVerticalBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         }
                 )
             );
         table.AppendChild <TableProperties>(tblProp);
         TableRow  headerRow       = new TableRow();
         TableCell headerNameCell  = new TableCell(new Paragraph(new Run(new Text(" Название заявки "))));
         TableCell headerDateCell  = new TableCell(new Paragraph(new Run(new Text(" Дата создания"))));
         TableCell headerSpareCell = new TableCell(new Paragraph(new Run(new Text(" Название детали"))));
         TableCell headerCountCell = new TableCell(new Paragraph(new Run(new Text(" Количество "))));
         headerRow.Append(headerNameCell);
         headerRow.Append(headerDateCell);
         headerRow.Append(headerSpareCell);
         headerRow.Append(headerCountCell);
         table.Append(headerRow);
         int    i    = 0;
         string name = "";
         foreach (var req in info.SpareRequests)
         {
             if (name != req.RequestName)
             {
                 if (i != 0)
                 {
                     TableRow  service3Row = new TableRow();
                     TableCell nul5Cell    = new TableCell(new Paragraph(new Run(new Text())));
                     service3Row.Append(nul5Cell);
                     TableCell nul6Cell = new TableCell(new Paragraph(new Run(new Text())));
                     service3Row.Append(nul6Cell);
                     TableCell itCell = new TableCell(new Paragraph(new Run(new Text(" Итоговое количество: "))));
                     TableCell coCell = new TableCell(new Paragraph(new Run(new Text(i.ToString()))));
                     service3Row.Append(itCell);
                     service3Row.Append(coCell);
                     table.Append(service3Row);
                     i = 0;
                 }
                 TableRow  serviceRow     = new TableRow();
                 TableCell nameCell       = new TableCell(new Paragraph(new Run(new Text(req.RequestName))));
                 TableCell dateCreateCell = new TableCell(new Paragraph(new Run(new Text(req.DateCreate.ToString()))));
                 serviceRow.Append(nameCell);
                 serviceRow.Append(dateCreateCell);
                 TableCell nul4Cell = new TableCell(new Paragraph(new Run(new Text())));
                 serviceRow.Append(nul4Cell);
                 TableCell nul3Cell = new TableCell(new Paragraph(new Run(new Text())));
                 serviceRow.Append(nul3Cell);
                 table.Append(serviceRow);
             }
             TableRow  service2Row = new TableRow();
             TableCell nulCell     = new TableCell(new Paragraph(new Run(new Text())));
             service2Row.Append(nulCell);
             TableCell nul2Cell = new TableCell(new Paragraph(new Run(new Text())));
             service2Row.Append(nul2Cell);
             TableCell SpareCell = new TableCell(new Paragraph(new Run(new Text(req.SpareName))));
             TableCell countCell = new TableCell(new Paragraph(new Run(new Text(req.Count.ToString()))));
             i += req.Count;
             service2Row.Append(SpareCell);
             service2Row.Append(countCell);
             table.Append(service2Row);
             name = req.RequestName;
         }
         TableRow  service4Row = new TableRow();
         TableCell nul7Cell    = new TableCell(new Paragraph(new Run(new Text())));
         service4Row.Append(nul7Cell);
         TableCell nul8Cell = new TableCell(new Paragraph(new Run(new Text())));
         service4Row.Append(nul8Cell);
         TableCell it2Cell = new TableCell(new Paragraph(new Run(new Text(" Итоговое количество: "))));
         TableCell co2Cell = new TableCell(new Paragraph(new Run(new Text(i.ToString()))));
         service4Row.Append(it2Cell);
         service4Row.Append(co2Cell);
         table.Append(service4Row);
         docBody.Append(table);
         docBody.AppendChild(CreateSectionProperties());
         wordDocument.MainDocumentPart.Document.Save();
     }
 }
Exemple #2
0
        private void GenerarExamen(int cantidadExamenes = 1, int cantidadCopias = 1)
        {
            string resultPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).ToString(CultureInfo) + "\\Test.docx";

            using (WordprocessingDocument document = WordprocessingDocument.Create(resultPath, WordprocessingDocumentType.Document))
            {
                var diccionarioBloqueCuestionarioCopy = new Dictionary <string, BloqueCuestionario>();
                var listBloqueCuestionarioCopy        = new List <BloqueCuestionario>();
                // listaBloqueCuestionarioCopy = listaBloqueCuestionario;
                diccionarioBloqueCuestionarioCopy = formularioEstructura.DiccionarioBloqueCuestionarioEstructurado;
                listBloqueCuestionarioCopy        = diccionarioBloqueCuestionarioCopy.Values.ToList();
                MainDocumentPart mainPart = document.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                int  contadorNumberingId = 0;
                for (int i = 0; i < cantidadExamenes; i++)
                {
                    if (true)
                    {
                        Random rnd = new Random((int)DateTime.Now.Ticks);

                        listBloqueCuestionarioCopy.Shuffle(rnd);
                    }

                    for (int j = 0; j < cantidadCopias; j++)
                    {
                        if (i > 0 || j > 0)
                        {
                            InsertarSaltoDePagina(body);
                        }
                        contadorNumberingId++;
                        foreach (var item in diccionarioBloqueCuestionarioCopy.Values)
                        {
                            ParagraphProperties paragraphProperties = new ParagraphProperties();
                            ParagraphStyleId    paragraphStyleId    = new ParagraphStyleId()
                            {
                                Val = "ListParagraph"
                            };
                            NumberingProperties     numberingProperties     = new NumberingProperties();
                            NumberingLevelReference numberingLevelReference = new NumberingLevelReference()
                            {
                                Val = 0
                            };
                            NumberingId numberingId = new NumberingId()
                            {
                                Val = contadorNumberingId
                            };                                                                         //Val is 1, 2, 3 etc based on your numberingid in your numbering element
                            NumberingFormat numberingFormat = new NumberingFormat()
                            {
                                Val = NumberFormatValues.UpperLetter
                            };

                            numberingProperties.Append(numberingLevelReference);
                            numberingProperties.Append(numberingFormat);
                            numberingProperties.Append(numberingId);
                            paragraphProperties.Append(paragraphStyleId);
                            paragraphProperties.Append(numberingProperties);

                            Paragraph para = body.AppendChild(new Paragraph());
                            para.Append(paragraphProperties);
                            Run run = para.AppendChild(new Run());
                            run.AppendChild(new Text(item.Pregunta.InnerText.Substring(1).Trim(' ')));
                        }
                    }
                }
            }
            if (formularioEstructura.DiccionarioBloqueCuestionarioEstructurado.Count > 0)
            {
                if (MessageBox.Show(Mensajes.AbrirArchivoGenerado + "\n" + resultPath, Mensajes.ArchivoGeneradoCorrectamenteTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName  = "WINWORD.EXE";
                    startInfo.Arguments = resultPath;
                    Process.Start(startInfo);
                }
            }
            else
            {
                Mensajes.NoExistenDatosParaEstructurar();
            }
        }
        public void GetXPathTest()
        {
            XmlPath actual;

            Paragraph p    = new Paragraph(new Run(), new BookmarkEnd(), new Run());
            Body      body = new Body(p);

            actual = XmlPath.GetXPath(p);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[1]", actual.XPath);
            Assert.Equal(1, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);

            actual = XmlPath.GetXPath(p.FirstChild);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[1]/w:r[1]", actual.XPath);
            Assert.Equal(1, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);

            body.PrependChild(new Paragraph());

            actual = XmlPath.GetXPath(p.FirstChild.NextSibling());
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[2]/w:bookmarkEnd[1]", actual.XPath);
            Assert.Equal(1, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);

            var r = p.LastChild;

            actual = XmlPath.GetXPath(r);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[2]/w:r[2]", actual.XPath);
            Assert.Equal(1, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);

            var unknown1 = p.PrependChild(new OpenXmlUnknownElement("my:test", "http://my"));

            actual = XmlPath.GetXPath(unknown1);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[2]/my:test[1]", actual.XPath);
            Assert.Equal(2, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);
            Assert.Equal(@"xmlns:my=""http://my""", actual.NamespacesDefinitions[1]);

            var unknown2 = p.AppendChild(new OpenXmlUnknownElement("my:test", "http://my"));

            actual = XmlPath.GetXPath(unknown2);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[2]/my:test[2]", actual.XPath);
            Assert.Equal(2, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);
            Assert.Equal(@"xmlns:my=""http://my""", actual.NamespacesDefinitions[1]);

            var miscNode = p.AppendChild(new OpenXmlMiscNode(System.Xml.XmlNodeType.Comment, "<!-- comment -->"));

            actual = XmlPath.GetXPath(miscNode);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[2]/<!-- comment -->", actual.XPath);
            Assert.Equal(1, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);

            actual = XmlPath.GetXPath(r);
            Assert.Null(actual.PartUri);
            Assert.Equal(@"/w:body[1]/w:p[2]/w:r[2]", actual.XPath);
            Assert.Equal(1, actual.NamespacesDefinitions.Count);
            Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);

            using (var stream = new MemoryStream())
                using (var doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                {
                    doc.AddMainDocumentPart();
                    doc.MainDocumentPart.Document = new Document(body);

                    actual = XmlPath.GetXPath(r);
                    Assert.Equal(doc.MainDocumentPart.Uri, actual.PartUri);
                    Assert.Equal(new Uri("/word/document.xml", UriKind.Relative), actual.PartUri);
                    Assert.Equal(@"/w:document[1]/w:body[1]/w:p[2]/w:r[2]", actual.XPath);
                    Assert.Equal(1, actual.NamespacesDefinitions.Count);
                    Assert.Equal(@"xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""", actual.NamespacesDefinitions[0]);
                }
        }
Exemple #4
0
        public void HyperlinkRelationshipTest2()
        {
            using (var stream = new MemoryStream())
            {
                using (var testDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                {
                    var mainPart  = testDocument.AddMainDocumentPart();
                    var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Body());
                    mainPart.Document = new Document(new Body(paragraph));
                    mainPart.Document.Save();

                    var newUri = new System.Uri("#New", System.UriKind.Relative);
                    var ridnew = mainPart.AddHyperlinkRelationship(newUri, false);
                    var newRel = mainPart.PackagePart.GetRelationship(ridnew.Id);
                    Assert.Equal(System.IO.Packaging.TargetMode.Internal, newRel.TargetMode);
                    Assert.Equal(ridnew.Id, newRel.Id);
                    Assert.Equal(newUri, newRel.TargetUri);
                    Assert.Equal(HyperlinkRelationship.RelationshipTypeConst, newRel.RelationshipType);

                    mainPart.DeleteReferenceRelationship(ridnew);
                    Assert.Empty(mainPart.HyperlinkRelationships);

                    newUri = new System.Uri("http://microsoft.com", System.UriKind.Absolute);
                    ridnew = mainPart.AddHyperlinkRelationship(newUri, true, ridnew.Id);
                    newRel = mainPart.PackagePart.GetRelationship(ridnew.Id);
                    Assert.Equal(System.IO.Packaging.TargetMode.External, newRel.TargetMode);
                    Assert.Equal(ridnew.Id, newRel.Id);
                    Assert.Equal(newUri, newRel.TargetUri);
                    Assert.Equal(HyperlinkRelationship.RelationshipTypeConst, newRel.RelationshipType);
                }

                // Test the OpenXmlPartContainer.AddSubPartFromOtherPackage().
                // The method should import all hyperlink relationships.
                stream.Seek(0, SeekOrigin.Begin);
                using (var testDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                    using (var sourcestream = GetStream(TestFiles.May_12_04))
                        using (var sourceDocument = WordprocessingDocument.Open(sourcestream, false))
                        {
                            var parts = new System.Collections.Generic.Dictionary <OpenXmlPart, bool>();
                            sourceDocument.MainDocumentPart.FindAllReachableParts(parts);
                            var partCounts = parts.Count;

                            var hyperlinksBefore   = sourceDocument.MainDocumentPart.HyperlinkRelationships.ToArray();
                            var externalRelsBefore = sourceDocument.MainDocumentPart.ExternalRelationships.ToArray();

                            testDocument.AddPart(sourceDocument.MainDocumentPart);
                            parts.Clear();
                            testDocument.MainDocumentPart.FindAllReachableParts(parts);

                            // all parts under the main document part should be imported.
                            Assert.Equal(partCounts, parts.Count);

                            var hyperlinksAfter   = testDocument.MainDocumentPart.HyperlinkRelationships.ToArray();
                            var externalRelsAfter = testDocument.MainDocumentPart.ExternalRelationships.ToArray();

                            // all hyperlink relationships should be imported.
                            Assert.Equal(hyperlinksBefore.Length, hyperlinksAfter.Length);
                            for (int i = 0; i < hyperlinksBefore.Length; i++)
                            {
                                Assert.Equal(hyperlinksBefore[i].Id, hyperlinksAfter[i].Id);
                                Assert.Equal(hyperlinksBefore[i].IsExternal, hyperlinksAfter[i].IsExternal);
                                Assert.Equal(hyperlinksBefore[i].Uri, hyperlinksAfter[i].Uri);
                            }

                            // all external relationships should be improted.
                            Assert.Equal(externalRelsBefore.Length, externalRelsAfter.Length);
                        }
            }
        }
        public void CreateWordDoc(DataTable data, decimal t, string user)
        {
            string pathUser     = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string pathDownload = Path.Combine(pathUser, "Downloads");
            //string pathDownload = Server.MapPath("~/Content/");
            decimal total = t;

            try
            {
                //Set the current directory.
                Directory.SetCurrentDirectory(pathDownload);
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine("The specified directory does not exist. {0}", e);
            }

            WordprocessingDocument doc         = WordprocessingDocument.Create("ExpenseReport.docx", WordprocessingDocumentType.Document);
            MainDocumentPart       mainDocPart = doc.AddMainDocumentPart();

            mainDocPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
            DocumentFormat.OpenXml.Wordprocessing.Body body = new DocumentFormat.OpenXml.Wordprocessing.Body();
            mainDocPart.Document.Append(body);
            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

            //border
            TableProperties tblProp = new TableProperties(
                new TableBorders(
                    new InsideHorizontalBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.BasicThinLines), Size = 10
            })
                );

            // Append the TableProperties object to the empty table.
            table.AppendChild <TableProperties>(tblProp);

            //setting header
            DocumentFormat.OpenXml.Wordprocessing.TableRow      tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            DocumentFormat.OpenXml.Wordprocessing.RunProperties rp = new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
            rp.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
            {
                Val = "#FF0000"
            });
            RunFonts rFont1 = new RunFonts();

            rFont1.Ascii = "Arial";
            rp.Append(rFont1);
            rp.Append(new Bold());
            rp.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });

            DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run();
            run.RunProperties = rp;
            run.Append(new Text("Expense Report for " + user));
            DocumentFormat.OpenXml.Wordprocessing.Paragraph           para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
            DocumentFormat.OpenXml.Wordprocessing.TableCellProperties tcpp = new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties();
            tcpp.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
            });
            GridSpan gs = new GridSpan();

            gs.Val = 5;
            tcpp.Append(gs);
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell(tcpp, para);
            tr.Append(tc);
            table.Append(tr);

            DocumentFormat.OpenXml.Wordprocessing.TableRow row_header = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            foreach (DataColumn column in data.Columns)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                                new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(column.ToString()))));
                cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                    Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
                }));
                row_header.Append(cell);
            }

            table.Append(row_header);

            for (int i = 0; i < data.Rows.Count; ++i)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableRow row = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
                    cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                        Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
                    }));
                    row.Append(cell);
                }
                table.Append(row);
            }
            body.Append(table);

            Run       run1  = new Run();
            Paragraph para1 = new Paragraph(run1);

            run1.AppendChild(new Text("The total Expenditure is " + total));
            body.Append(para1);
            doc.MainDocumentPart.Document.Save();
            doc.Dispose();
        }
Exemple #6
0
        public void Build(GeneralTree <INode> features)
        {
            string filename = string.IsNullOrEmpty(this.configuration.SystemUnderTestName)
                ? "features.docx"
                : this.configuration.SystemUnderTestName + ".docx";
            string documentFileName = this.fileSystem.Path.Combine(this.configuration.OutputFolder.FullName, filename);

            if (this.fileSystem.File.Exists(documentFileName))
            {
                try
                {
                    this.fileSystem.File.Delete(documentFileName);
                }
                catch (System.IO.IOException ex)
                {
                    Log.Error("Cannot delete Word file. Is it still open in Word?", ex);
                    return;
                }
            }

            using (
                WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Create(
                    documentFileName,
                    WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainDocumentPart = wordProcessingDocument.AddMainDocumentPart();
                this.wordStyleApplicator.AddStylesPartToPackage(wordProcessingDocument);
                this.wordStyleApplicator.AddStylesWithEffectsPartToPackage(wordProcessingDocument);
                this.wordFontApplicator.AddFontTablePartToPackage(wordProcessingDocument);
                var documentSettingsPart = mainDocumentPart.AddNewPart <DocumentSettingsPart>();
                documentSettingsPart.Settings = new Settings();
                this.wordHeaderFooterFormatter.ApplyHeaderAndFooter(wordProcessingDocument);

                var document = new Document();
                var body     = new Body();
                document.Append(body);

                var actionVisitor = new ActionVisitor <INode>(node =>
                {
                    var featureDirectoryTreeNode =
                        node as FeatureNode;
                    if (featureDirectoryTreeNode != null)
                    {
                        this.wordFeatureFormatter.Format(body, featureDirectoryTreeNode);
                    }
                });

                features.AcceptVisitor(actionVisitor);

                mainDocumentPart.Document = document;
                mainDocumentPart.Document.Save();
            }

            // HACK - Add the table of contents
            using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(documentFileName, true))
            {
                XElement firstPara = wordProcessingDocument
                                     .MainDocumentPart
                                     .GetXDocument()
                                     .Descendants(W.p)
                                     .FirstOrDefault();

                TocAdder.AddToc(wordProcessingDocument, firstPara, @"TOC \o '1-2' \h \z \u", null, 4);
            }
        }
Exemple #7
0
        protected void btnIspisi_Click(object sender, EventArgs e)
        {
            /*DateTime dt;
             * string d1 = "";
             * string d2 = "";
             * try {
             *  dt = Convert.ToDateTime(txtOdDatuma.Text);
             *  d1 = "#" + dt.Month + "/" + dt.Day + "/" + dt.Year + "#";
             * }
             * catch {
             * }
             * try {
             *  dt = Convert.ToDateTime(txtDoDatuma.Text);
             *  d2 = "#" + dt.Month + "/" + dt.Day + "/" + dt.Year + "#";
             * }
             * catch {
             * }*/

            Body      body;
            Paragraph par;
            Run       run;

            DocumentFormat.OpenXml.Wordprocessing.TableRow  tr;
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc;
            TableCellProperties tcp;
            RunProperties       rp;

            WordprocessingDocument package = WordprocessingDocument.Create(HttpRuntime.AppDomainAppPath + "\\sintetika.docx", WordprocessingDocumentType.Document);

            package.AddMainDocumentPart();

            Document document = new Document();

            package.MainDocumentPart.Document = document;
            body = document.AppendChild(new Body());
            SectionProperties sectionProps = body.AppendChild(new SectionProperties());

            sectionProps.Append(new PageMargin()
            {
                Top = 720, Right = 720, Bottom = 720, Left = 720, Header = 0, Footer = 0, Gutter = 0
            });                                                                                                                             // 1440 = 1", 720 = 0.5";

            par = body.AppendChild(new Paragraph());
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.AppendChild(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "32"
            });
            run.AppendChild(new Text("Sintetika"));

            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
            TableProperties props = new TableProperties
                                    (
                new TableBorders
                (
                    new TableWidth {
                Width = "5000", Type = TableWidthUnitValues.Pct
            },                                                                                  // 100%
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            }
                )
                                    );

            table.AppendChild <TableProperties>(props);

            tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new GridSpan()
            {
                Val = 2
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });
            run.Append(new Text("PRIPRAVNICI"));
            table.Append(tr);

            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Standard"));

            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj"));

            table.Append(tr);

            string          query = query = "select qvodicitecajevi.standard, count(*) as broj from vodici inner join qvodicitecajevi on vodici.id = qvodicitecajevi.vod_id where vodici.clanarina like '%" + txtGodina.Text + "%' group by qvodicitecajevi.standard order by qvodicitecajevi.standard";
            OleDbConnection con   = new OleDbConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
            OleDbCommand    cmd   = new OleDbCommand();

            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection  = con;
            con.Open();
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["standard"].ToString()));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["broj"].ToString()));

                table.Append(tr);
            }


            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // ćelija
            tc = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            //tcp = tc.AppendChild(new TableCellProperties());
            //tcp.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black" });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            //rp.Append(new Color() { Val = "ffffff" });
            //rp.Append(new Bold() { Val = OnOffValue.FromBoolean(true) });
            run.Append(new Text(""));
            table.Append(tr);


            tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new GridSpan()
            {
                Val = 2
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });
            run.Append(new Text("VODIČI"));
            table.Append(tr);

            tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Standard"));

            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj"));

            table.Append(tr);

            query           = "select qvodiciispiti.standard, count(*) as broj from vodici inner join qvodiciispiti on vodici.id = qvodiciispiti.vod_id where vodici.clanarina like '%" + txtGodina.Text + "%' group by qvodiciispiti.standard order by qvodiciispiti.standard";
            cmd.CommandText = query;
            dr.Close();
            dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["standard"].ToString()));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["broj"].ToString()));

                table.Append(tr);
            }

            document.Body.Append(table);
            document.Save();
            package.Close();

            con.Close();

            Response.ContentType = "Application/docx";
            Response.AppendHeader("Content-Disposition", "attachment; filename=sintetika.docx");
            Response.TransmitFile(HttpRuntime.AppDomainAppPath + "\\sintetika.docx");
            Response.End();
        }
        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, "FF0000", "Arial", "28");
                    ClsOpenXmlUtilities.AddStyle(mainPart, "MyHeading1", "Titolone", "0000FF", "Verdana", 28, false, true, true);
                    ClsOpenXmlUtilities.AddStyle(mainPart, "MyTypeScript", "Macchina da scrivere", "333333", "Consolas", 12, true, false, false);

                    // Add heading
                    Paragraph headingPar = ClsOpenXmlUtilities.CreateParagraphWithStyle("MyHeading1", JustificationValues.Center);
                    ClsOpenXmlUtilities.AddTextToParagraph(headingPar, "Titolo con stile applicato");
                    body.AppendChild(headingPar);

                    //Add MyTypeScript
                    Paragraph typeScriptPar = ClsOpenXmlUtilities.CreateParagraphWithStyle("MyTypeScript", JustificationValues.Center);
                    ClsOpenXmlUtilities.AddTextToParagraph(typeScriptPar, "Testo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo lungo");
                    body.AppendChild(typeScriptPar);

                    // 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 = ClsOpenXmlUtilities.createHeading("Testo con stili");
                    //body.AppendChild(headingPar);

                    // Append a paragraph with styles
                    Paragraph newPar = createParagraphWithStyles();
                    body.AppendChild(newPar);

                    // Append a table
                    Table myTable = ClsOpenXmlUtilities.createTable(3, 3, "ok");
                    body.Append(myTable);

                    // Append bullet list
                    ClsOpenXmlUtilities.createBulletNumberingPart(mainPart, "-");
                    List <Paragraph> bulletList = ClsOpenXmlUtilities.createList(3, "bullet", "bullet", "0", "100", "200");/*createBulletList(4, "yes");*/
                    foreach (Paragraph paragraph in bulletList)
                    {
                        body.Append(paragraph);
                    }

                    // Append numbered list
                    List <Paragraph> numberedList = ClsOpenXmlUtilities.createList(3, "numbered", "numbered", "0", "100", "240");/*createNumberedList();*/
                    foreach (Paragraph paragraph in numberedList)
                    {
                        body.Append(paragraph);
                    }

                    // Append image
                    ClsOpenXmlUtilities.InsertPicture(doc, "panorama.jpg");
                }
                MessageBox.Show("Il documento è pronto!");
                Process.Start(filepath);
            }
            catch (Exception)
            {
                MessageBox.Show("Problemi col documento. Se è aperto da un altro programma, chiudilo e riprova...");
            }
        }
Exemple #9
0
        public async Task <IHttpActionResult> Get(Guid DocId)
        {
            try
            {
                var fullDoc = DataService.getFullDoc(DocId);

                IHttpActionResult result;
                MemoryStream      mem = new MemoryStream();


                // Create Document
                using (WordprocessingDocument wordDocument =
                           WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                    DocHelper.AddStyles(mainPart);

                    // Create the document structure and add some text.
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());

                    // Title and Sub-title
                    Paragraph titlePara = body.AppendChild(new Paragraph());
                    DocHelper.ApplyStyleToParagraph(wordDocument, "unknown", "Title", titlePara);
                    Run run = titlePara.AppendChild(new Run());
                    run.AppendChild(new Text(fullDoc.Header.Title));

                    Paragraph subTitlePara = body.AppendChild(new Paragraph());
                    DocHelper.ApplyStyleToParagraph(wordDocument, "unknown", "Subtitle", subTitlePara);
                    subTitlePara.AppendChild(new Run(new Text($"Created {fullDoc.Header.Created} (UTC)")));

                    // Paragraph for each para in the list
                    foreach (var para in fullDoc.Paragraphs)
                    {
                        var paragraph = body.AppendChild(new Paragraph(new Run(new Text(
                                                                                   $"[{para.TimeStamp} (UTC)] - {para.Text}"))));
                        if (!string.IsNullOrWhiteSpace(para.Style))
                        {
                            DocHelper.ApplyStyleToParagraph(wordDocument, "unknown", para.Style, paragraph);
                        }
                    }


                    mainPart.Document.Save();
                }

                mem.Seek(0, SeekOrigin.Begin);

                HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
                msg.Content = new StreamContent(mem);

                msg.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                msg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"{fullDoc.Header.FileName}"
                };
                result = ResponseMessage(msg);


                return(result);
            }
            catch (KeyNotFoundException e)
            {
                return(NotFound());
            }
        }
Exemple #10
0
        public MemoryStream CreateWordInvoice(ShipmentDTO shipment)
        {
            var    body     = new Body();
            var    document = new Document(body);
            string fontName = "Times New Roman";

            var table   = CreateTable();
            var headRow = new TableRow();

            table.Append(headRow);
            headRow.Append(new TableCell(CreateParagraph("№", fontName, 12, JustificationValues.Center)));
            headRow.Append(new TableCell(CreateParagraph("Код", fontName, 12, JustificationValues.Center)));
            headRow.Append(new TableCell(CreateParagraph("Товар", fontName, 12, JustificationValues.Center)));
            headRow.Append(new TableCell(CreateParagraph("Кол-во", fontName, 12, JustificationValues.Center)));
            headRow.Append(new TableCell(CreateParagraph("Ед.", fontName, 12, JustificationValues.Center)));
            headRow.Append(new TableCell(CreateParagraph("Цена", fontName, 12, JustificationValues.Center)));
            headRow.Append(new TableCell(CreateParagraph("Сумма", fontName, 12, JustificationValues.Center)));

            int i = 1;

            foreach (var orderItem in shipment.Order.Items)
            {
                var row = new TableRow();
                table.Append(row);
                row.Append(new TableCell(CreateParagraph(i.ToString(), fontName, 12, JustificationValues.Center)));
                row.Append(new TableCell(CreateParagraph(orderItem.ProductId.ToString(), fontName, 12, JustificationValues.Center)));
                row.Append(new TableCell(CreateParagraph(orderItem.Product.Name, fontName, 12, JustificationValues.Center)));
                row.Append(new TableCell(CreateParagraph("1", fontName, 12, JustificationValues.Center)));
                row.Append(new TableCell(CreateParagraph(orderItem.Product.Unit.ToString(), fontName, 12, JustificationValues.Center)));
                row.Append(new TableCell(CreateParagraph(orderItem.Price.ToString(), fontName, 12, JustificationValues.Center)));
                row.Append(new TableCell(CreateParagraph((new Price(orderItem.Price.Penny * 1)).ToString(), fontName, 12, JustificationValues.Center)));
                ++i;
            }

            var table2 = CreateTable(BorderValues.None);
            var row2   = new TableRow();

            row2.Append(new TableCell(CreateParagraph("Сдал:")));
            row2.Append(new TableCell(CreateParagraph(shipment.Conveyed.UserName ?? shipment.ConveyedName)));
            row2.Append(new TableCell(CreateParagraph("____________")));
            row2.Append(new TableCell(CreateParagraph("подпись")));
            table2.Append(row2);

            row2 = new TableRow();
            row2.Append(new TableCell(CreateParagraph("Получил:")));
            row2.Append(new TableCell(CreateParagraph(shipment.Repicient.UserName ?? shipment.RepicientName)));
            row2.Append(new TableCell(CreateParagraph("____________")));
            row2.Append(new TableCell(CreateParagraph("подпись")));
            table2.Append(row2);

            document.Append(CreateParagraph($"Накладная №{shipment.Id} от {shipment.DateTime.ToString("dd MMMM yyyy")}", fontName, 16, JustificationValues.Center));
            document.Append(table);
            document.Append(CreateParagraph($"Итого {shipment.Order.TotalPrice}"));
            document.Append(table2);

            MemoryStream resultStream = new MemoryStream();

            using (var doc = WordprocessingDocument.Create(
                       resultStream, WordprocessingDocumentType.Document))
            {
                doc.AddMainDocumentPart();
                doc.MainDocumentPart.Document = document;
                doc.MainDocumentPart.Document.Save();
            }
            resultStream.Flush();
            resultStream.Position = 0;
            return(resultStream);
        }
Exemple #11
0
        public void BuildImplementationGuide(ExportSettings aModel, IIGTypePlugin igTypePlugin)
        {
            this.exportSettings = aModel;
            this.igTypePlugin   = igTypePlugin;

            this.docStream = new MemoryStream();
            this.document  = WordprocessingDocument.Create(this.docStream, WordprocessingDocumentType.Document);
            this.document.AddMainDocumentPart();

            this.SetupStyles();

            this.document.MainDocumentPart.Document =
                new Document(
                    new Body());

            this.hyperlinkTracker         = new HyperlinkTracker();
            this.tables                   = new TableCollection(this.document.MainDocumentPart.Document.Body, this.hyperlinkTracker);
            this.constraintTableGenerator = new TemplateConstraintTable(this._tdb, this.constraintReferences, this.igSettings, igTypePlugin, this.templates, this.tables, exportSettings.SelectedCategories, this.hyperlinkTracker);
            this.figures                  = new FigureCollection(this.document.MainDocumentPart.Document.Body);
            this.valueSetsExport
                = new ValueSetsExport(
                      igTypePlugin,
                      this.document.MainDocumentPart,
                      this.hyperlinkTracker,
                      this.tables,
                      exportSettings.GenerateValueSetAppendix,
                      exportSettings.DefaultValueSetMaxMembers,
                      exportSettings.ValueSetMaxMembers);
            this.codeSystemTable = new CodeSystemTable(this._tdb, this.document.MainDocumentPart.Document.Body, this.templates, this.tables);

            this.AddTitlePage();

            this.AddTableOfContents();

            this.AddVolume1(false);

            this.AddTemplateTypeSections();

            if (exportSettings.GenerateDocTemplateListTable || exportSettings.GenerateDocContainmentTable)
            {
                Paragraph entryLevelHeading = new Paragraph(
                    new ParagraphProperties(
                        new ParagraphStyleId()
                {
                    Val = Properties.Settings.Default.TemplateTypeHeadingStyle
                }),
                    new Run(
                        new Text("Template Ids in This Guide")));
                this.document.MainDocumentPart.Document.Body.AppendChild(entryLevelHeading);

                if (exportSettings.GenerateDocTemplateListTable)
                {
                    // Add used template table
                    this.AddDocumentTemplateListTable();
                }

                if (exportSettings.GenerateDocContainmentTable)
                {
                    TemplateContainmentGenerator.AddTable(this._tdb, this.document, this.templateRelationships, this.templates, this.tables, this.hyperlinkTracker);
                }
            }

            this.valueSetsExport.AddValueSetsAppendix();

            this.codeSystemTable.AddCodeSystemAppendix();

            this.AddRetiredTemplatesAppendix();

            if (exportSettings.IncludeChangeList)
            {
                this.LoadChangesAppendix();
            }

            this.AddVolume1(true);
        }
        public string ConvertHtmlToOpenXml(string html, List <string> logListOfString)
        {
            ////create a outer html as htmldoc from html fragment
            //var htmlDocument = new HtmlDocument();

            //var node = HtmlNode.CreateNode("<html><head></head><body>" + html + "</body></html>");

            //htmlDocument.DocumentNode.AppendChild(node);

            string docOuterHtml = "<html><head></head><body>" + html + "</body></html>";

            //htmlDocument.DocumentNode.OuterHtml;

            //htmlDocument = null;

            //using struct will help dispose off memory stream, as auto disposed
            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);
                    }

                    logListOfString.Add("memory stream created");

                    // Assign a reference to the existing document body.
                    //Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                    // Add new text.
                    //Paragraph para = body.AppendChild(new Paragraph());
                    //Run run = para.AppendChild(new Run());
                    //run.AppendChild(new Text(txt));

                    //< w:document xmlns:w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" >

                    //< w:body >

                    //< w:p >

                    //< w:r >

                    //< w:t > Example text.</ w:t >

                    //</ w:r >

                    //</ w:p >

                    //</ w:body >
                    //</ w:document >

                    if (mainPart.Document.Elements <Paragraph>().Count() != 0)
                    {
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);



                    //string html = "<HTML><Body>Test</Body></HTML>";
                    //var paralist = converter.Parse(docOuterHtml);

                    //return returnableOpenXML;

                    Body body = mainPart.Document.Body;

                    var paragraphs = converter.Parse(html);

                    logListOfString.Add("Tag converter success");

                    string returnableOpenXML = string.Empty;

                    foreach (OpenXmlCompositeElement t in paragraphs)
                    {
                        //body.Append(t);
                        returnableOpenXML += t.InnerXml;
                    }


                    //https://en.wikipedia.org/wiki/Control_character
                    //http://www.codetable.net/hex/3
                    //http://paulbourke.net/dataformats/ascii/
                    if (returnableOpenXML.Contains("&#"))
                    {
                        returnableOpenXML = returnableOpenXML.Replace("&#x0;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x2;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x3;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x4;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x5;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x6;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x7;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x8;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x9;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xa;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xb;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xc;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xd;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xe;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xf;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x10;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x11;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x12;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x13;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x14;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x15;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x16;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x17;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x18;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x19;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1a;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1b;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1c;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1d;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1f;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x7f;", "");
                        //&#xC; form feed escape sequence character
                        //returnableOpenXML = returnableOpenXML.Replace("&#xC;", "");
                        //http://www.codetable.net/hex/b
                        //repeating above small case charcters as above C
                        returnableOpenXML = returnableOpenXML.Replace("&#xA;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xB;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xC;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xD;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xE;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#xF;", "");

                        returnableOpenXML = returnableOpenXML.Replace("&#x1A;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1B;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1C;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1D;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1E;", "");
                        returnableOpenXML = returnableOpenXML.Replace("&#x1F;", "");

                        returnableOpenXML = returnableOpenXML.Replace("&#x7F;", "");
                    }

                    returnableOpenXML = returnableOpenXML.Replace("\f", "");
                    returnableOpenXML = returnableOpenXML.Replace("\n", "");
                    returnableOpenXML = returnableOpenXML.Replace("\r", "");
                    returnableOpenXML = returnableOpenXML.Replace("\a", "");
                    returnableOpenXML = returnableOpenXML.Replace("\b", "");
                    returnableOpenXML = returnableOpenXML.Replace("\t", "");
                    returnableOpenXML = returnableOpenXML.Replace("\v", "");

                    return(returnableOpenXML);
                }


                //generatedDocument.WriteTo(new FileStream("d:\\test.docx",FileMode.Create) );
            }
            //return "";
        }
Exemple #13
0
        public FileStreamResult CreateReport(IEnumerable <BookDto> bookList)
        {
            if (bookList == null)
            {
                throw new NullReferenceException();
            }

            var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();

            culture.NumberFormat.CurrencySymbol = "€";
            using (MemoryStream mem = new MemoryStream())
            {
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(mem,
                                                                                      WordprocessingDocumentType.Document, true))
                {
                    wordDoc.AddMainDocumentPart();
                    Document doc  = new Document();
                    Body     body = new Body();

                    // Create an empty table.
                    Table table = new Table();

                    // Append the TableProperties object to the empty table.
                    table.AppendChild(CreateTableProperties());


                    // Create row for title.
                    TableRow tr = new TableRow();
                    tr.Append(CreateCell("Title", true));
                    tr.Append(CreateCell("Author", true));
                    tr.Append(CreateCell("Price", true));
                    tr.Append(CreateCell("Best Seller", true));
                    tr.Append(CreateCell("Availability", true));
                    table.Append(tr);

                    foreach (var book in bookList)
                    {
                        tr = new TableRow();

                        // create data cells.
                        tr.Append(CreateCell(book.Title));

                        tr.Append(CreateCell(book.Author.Firstname + " " + book.Author.Lastname));

                        tr.Append(CreateCell(book.Price.ToString("C", culture)));

                        tr.Append(CreateCell(book.IsBestSeller ? "Bestseller" : "Not Bestseller"));

                        tr.Append(CreateCell(book.AvailableStock > 0
                            ? "Available in stock\n(" + book.AvailableStock + ")"
                            : "Not available in stock"));

                        // Append the table row to the table.
                        table.Append(tr);
                    }

                    body.Append(table);
                    doc.Append(body);
                    wordDoc.MainDocumentPart.Document = doc;
                    wordDoc.Close();
                }

                var ms = new MemoryStream(mem.ToArray());
                return(new FileStreamResult(ms,
                                            "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                {
                    FileDownloadName = $"BookSearchReport-" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm")
                });
            }
        }
Exemple #14
0
 public static void CreateDoc(WordInfoAvto 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
             }
         }));
         Table           table   = new Table();
         TableProperties tblProp = new TableProperties(
             new TableBorders(
                 new TopBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new BottomBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new LeftBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new RightBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new InsideHorizontalBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new InsideVerticalBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         }
                 )
             );
         table.AppendChild <TableProperties>(tblProp);
         TableRow  headerRow        = new TableRow();
         TableCell headerNumberCell = new TableCell(new Paragraph(new Run(new Text("№"))));
         TableCell headerNameCell   = new TableCell(new Paragraph(new Run(new Text("Название"))));
         TableCell headerDescCell   = new TableCell(new Paragraph(new Run(new Text("Описание"))));
         TableCell headerPriceCell  = new TableCell(new Paragraph(new Run(new Text("Цена"))));
         headerRow.Append(headerNumberCell);
         headerRow.Append(headerNameCell);
         headerRow.Append(headerDescCell);
         headerRow.Append(headerPriceCell);
         table.Append(headerRow);
         int i = 1;
         foreach (var car in info.Cars)
         {
             TableRow  serviceRow = new TableRow();
             TableCell numberCell = new TableCell(new Paragraph(new Run(new Text(i.ToString()))));
             TableCell nameCell   = new TableCell(new Paragraph(new Run(new Text(car.CarName))));
             TableCell descCell   = new TableCell(new Paragraph(new Run(new Text(car.Year.ToString()))));
             TableCell priceCell  = new TableCell(new Paragraph(new Run(new Text(car.Price.ToString()))));
             serviceRow.Append(numberCell);
             serviceRow.Append(nameCell);
             serviceRow.Append(descCell);
             serviceRow.Append(priceCell);
             table.Append(serviceRow);
             i++;
         }
         docBody.Append(table);
         docBody.AppendChild(CreateSectionProperties());
         wordDocument.MainDocumentPart.Document.Save();
     }
 }
Exemple #15
0
        public string BuildDocument(string filepath, string sn, List <VTFormObject> forms)
        {
            try
            {
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
                //using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filepath, true))
                {
                    MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
                    mainPart.Document = new Document();

                    var margin_size = 100;

                    PageMargin pargeMargins = new PageMargin();
                    pargeMargins.Top    = margin_size;
                    pargeMargins.Bottom = margin_size;
                    Columns columns = new Columns();
                    columns.ColumnCount = 2;


                    SectionProperties sectionProps = new SectionProperties();
                    sectionProps.Append(columns);
                    sectionProps.Append(pargeMargins);

                    Body body = mainPart.Document.AppendChild(new Body());
                    body.Append(sectionProps);
                    ParagraphProperties paragraphProperties = new ParagraphProperties
                                                              (
                        //new ParagraphStyleId() { Val = "No Spacing" },
                        new SpacingBetweenLines()
                    {
                        After = "0"
                    }
                                                              );



                    Paragraph para_main = body.AppendChild(new Paragraph(paragraphProperties));

                    // Creating the Header where the Serial Number will exist

                    // Serial Number
                    Run           run_mainHeader     = para_main.AppendChild(new Run());
                    RunProperties runProp_mainHeader = new RunProperties();    // Create run properties.
                    FontSize      size_mainHeader    = new FontSize();
                    size_mainHeader.Val = new StringValue("48");
                    runProp_mainHeader.Append(size_mainHeader);
                    run_mainHeader.Append(runProp_mainHeader);                              // Append all of the properties
                    run_mainHeader.Append(new Text("S/N: " + sn));
                    run_mainHeader.Append(new Break());

                    // Serial Barcode
                    Run           run_barcode         = para_main.AppendChild(new Run());
                    RunProperties runProp_barcode     = new RunProperties();                // Create run properties.
                    RunFonts      runFontMain_barcode = new RunFonts();                     // Create font
                    runFontMain_barcode.Ascii = "Code39AzaleaNarrow1";                      // Specify font family
                    FontSize size_barcode = new FontSize();
                    size_barcode.Val = new StringValue("56");

                    runProp_barcode.Append(runFontMain_barcode);
                    runProp_barcode.Append(size_barcode);

                    run_barcode.PrependChild <RunProperties>(runProp_barcode);
                    sn = sn.ToUpper();                                                      // Sets all the values to uppercase to be a barcode format
                    run_barcode.AppendChild(new Text("*" + sn + "*"));
                    run_barcode.AppendChild(new Break());

                    // Tube Type
                    Run           run_tubetype     = para_main.AppendChild(new Run());
                    RunProperties runProp_tubetype = new RunProperties();                   // Create run properties.
                    FontSize      size_tubetype    = new FontSize();
                    size_tubetype.Val = new StringValue("38");
                    runProp_tubetype.Append(size_tubetype);
                    run_tubetype.Append(runProp_tubetype);                                  // Append all of the properties
                    run_tubetype.Append(new Text("Tube Type: " + forms[0].TubeType + " "));
                    run_tubetype.Append(new Break());

                    // Tube Barcode
                    Run           run_barcode_tube         = para_main.AppendChild(new Run());
                    RunProperties runProp_barcode_tube     = new RunProperties();           // Create run properties.
                    RunFonts      runFontMain_barcode_tube = new RunFonts();                // Create font
                    runFontMain_barcode_tube.Ascii = "Code39AzaleaNarrow1";                 // Specify font family
                    FontSize size_barcode_tube = new FontSize();
                    size_barcode_tube.Val = new StringValue("56");

                    runProp_barcode_tube.Append(runFontMain_barcode_tube);
                    runProp_barcode_tube.Append(size_barcode_tube);

                    run_barcode_tube.PrependChild <RunProperties>(runProp_barcode_tube);
                    sn = sn.ToUpper();                                                       // Sets all the values to uppercase to be a barcode format
                    run_barcode_tube.AppendChild(new Text("*" + forms[0].TubeType + "*"));
                    run_barcode_tube.AppendChild(new Break());



                    // Goes through all of the forms
                    foreach (var form in forms)
                    {
                        // Set up a header per form
                        Run           run_header         = para_main.AppendChild(new Run());
                        RunProperties runProp_formHeader = new RunProperties();
                        Bold          bold = new Bold();
                        Underline     ul   = new Underline()
                        {
                            Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single
                        };
                        FontSize size_formHeader = new FontSize();
                        size_formHeader.Val = new StringValue("24");
                        runProp_formHeader.Append(size_formHeader);
                        runProp_formHeader.Append(bold);
                        runProp_formHeader.Append(ul);
                        run_header.AppendChild(new RunProperties(runProp_formHeader));
                        //run_header.AppendChild(new RunProperties(new Bold(), new Underline()));

                        string username      = form.Username;
                        string proces_header = form.HeaderTitle;

                        run_header.AppendChild(new Text(proces_header));
                        run_header.AppendChild(new Break());

                        // Goes through all of the fields that each form contains.
                        for (int i = 0; i < form.FieldList.Count; i++)
                        {
                            // Do not need to print out user or serial for each form.
                            if (!(form.FieldList[i].Token == "SNT"))
                            {
                                Run run_data = para_main.AppendChild(new Run());
                                if (form.FieldList[i].Default)
                                {
                                    run_data.AppendChild(new Text(form.FieldList[i].Label));
                                }
                                else
                                {
                                    run_data.AppendChild(new Text(form.FieldList[i].Label + " " + form.FieldList[i].Spec + form.FieldList[i].Value));
                                }
                                run_data.AppendChild(new Break());
                            }
                        }
                    }

                    mainPart.Document.Save();
                    wordDoc.Close();
                    return("Success");
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
        /// <summary>
        /// 完全以 HTML 編輯內容,並將其匯出成檔案
        /// </summary>
        /// <param name="result">執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>匯出的 docx 文件資訊流</returns>
        public byte[] ExportByHtml(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                using (WordprocessingDocument doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
                {
                    #region 文件宣告與定義

                    //建立 MainDocumentPart 類別物件 mainPart,加入主文件部分
                    MainDocumentPart mainPart = doc.AddMainDocumentPart();
                    //實例化 Document(w) 部分
                    mainPart.Document = new Document();
                    //建立 Body 類別物件,於加入 Doucment(w) 中加入 Body 內文
                    Body body = mainPart.Document.AppendChild(
                        new Body(
                            new SectionProperties(new PageMargin()
                    {
                        Left   = 600,
                        Right  = 600,
                        Bottom = 700,
                        Top    = 740
                    })));

                    #endregion

                    #region 產出內容

                    Paragraph paragraph;
                    Run       run;

                    //建立「段落 Paragraph」類別物件,於 Body 本文中加入段落 Paragraph(p)
                    paragraph = body.AppendChild(new Paragraph());
                    //建立 Run 類別物件,於 段落 Paragraph(p) 中加入文字屬性 Run(r) 範圍
                    run = paragraph.AppendChild(new Run());
                    //在文字屬性 Run(r) 範圍中加入文字內容
                    run.AppendChild(new Text("履歷匯出範例"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("(使用 HTML 直接匯出)"));


                    //建立要產出的 HTML 內容
                    Resume        model = new Resume();
                    StringBuilder html  = new StringBuilder();
                    html.Append("Name: " + model.Name + "<br />");
                    html.Append("Gender: " + model.Gender + "<br />");
                    html.Append("Email: " + model.Email + "<br />");
                    html.Append("Address: " + model.Address + "<br />");
                    html.Append("Phone: " + model.Phone + "<br />");
                    html.Append("Mobile: " + model.Mobile + "<br />");
                    html.Append("Description1:<br />" + HttpUtility.HtmlDecode(model.Description1) + "<br /></p>");
                    html.Append("Description2:<br />" + HttpUtility.HtmlDecode(model.Description2) + "<br /></p>");

                    if (model.JobHistory.Count > 0)
                    {
                        int i = 1;
                        model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                        html.Append("<p>簡歷</p>");

                        //注意: HTML Table 轉成 OpenXML SDK 的 Table 物件時不會有框線,因此框線須直接於 HTML table Tag 中設定
                        html.Append("<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"4\"><tr><th>項目</th><th>任職</th><th>職稱</th><th>開始時間</th><th>結束時間</th></tr>");
                        foreach (var h in model.JobHistory)
                        {
                            html.Append("<tr>");
                            html.Append("<td>" + i.ToString() + "</td>");
                            html.Append("<td>" + h.CompanyName + "</td>");
                            html.Append("<td>" + h.JobTitle + "</td>");
                            html.Append("<td>" + (h.StartDT.HasValue ? h.StartDT.Value.ToShortDateString() : "") + "</td>");
                            html.Append("<td>" + (h.EndDT.HasValue ? h.EndDT.Value.ToShortDateString() : "") + "</td>");
                            html.Append("</tr>");
                            i++;
                        }
                        html.Append("</table>");
                    }

                    //將 HTML 內容轉換成 XML,並添加至文件內
                    HtmlConverter converter = new HtmlConverter(mainPart);
                    converter.ParseHtml(html.ToString());

                    //分隔線
                    paragraph = body.AppendChild(new Paragraph(new Run(new Text("-----------------------------------------------------------------"))));

                    #region 動態建立表格

                    //建立一個新的空白表格
                    Table table = new Table();

                    //建立表格屬性物件 (TableProperties object),並設定表格邊框及框度
                    TableProperties tblProp = new TableProperties(
                        new TableBorders(
                            new TopBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Sawtooth), Size = 1
                    },
                            new BottomBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Sawtooth), Size = 1
                    },
                            new LeftBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Sawtooth), Size = 1
                    },
                            new RightBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Sawtooth), Size = 1
                    },
                            new InsideHorizontalBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Sawtooth), Size = 1
                    },
                            new InsideVerticalBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Sawtooth), Size = 1
                    }),
                        new TableWidth()
                    {
                        Width = "5000", Type = TableWidthUnitValues.Pct
                    });


                    //將表格屬性物件 (TableProperties) 指定給表格 (table) 物件
                    TableStyle tableStyle = new TableStyle {
                        Val = "LightShadingAccent1"
                    };
                    tblProp.TableStyle = tableStyle;
                    table.AppendChild(tblProp); //<= 指定

                    //建立表格儲存格屬性
                    TableCellProperties cellProp = new TableCellProperties(
                        new TableCellVerticalAlignment()
                    {
                        Val = TableVerticalAlignmentValues.Center
                    },
                        new TableCellWidth()
                    {
                        Type = TableWidthUnitValues.Auto
                    }
                        );


                    //建立表格列 (Row) 及儲存格 (Cell)
                    TableRow  tableRow   = new TableRow();
                    TableCell tableCell1 = new TableCell();

                    //將儲存格屬性 (TableCellProperties) 指定給新建立的儲存格
                    tableCell1.Append(cellProp);

                    //在儲存格中添加段落,並於段落內加入文字
                    tableCell1.Append(new Paragraph(new Run(new Text("測試 Some cell text."))));

                    //將儲存格添加至表格列中
                    tableRow.Append(tableCell1);


                    //建立第二個儲存格 (直接複製第一個儲存格),並加入至表格列中
                    TableCell tableCell2 = new TableCell(tableCell1.OuterXml);
                    tableRow.Append(tableCell2);


                    //最後將表格列添加到表格物件上
                    table.Append(tableRow);

                    //將表格附加到文件 Body 上
                    mainPart.Document.Body.Append(table);

                    #endregion

                    #endregion

                    #region 套用樣式

                    //由於已經定義了段落樣式,因此將文件中所有的段落取出後,一一套用段落樣式
                    foreach (var p in mainPart.Document.Descendants <Paragraph>())
                    {
                        ApplyStyleToParagraph(doc, "BasicParagraphStyle", "Basic Paragraph Style", p);
                        p.ParagraphProperties.SpacingBetweenLines = new SpacingBetweenLines()
                        {
                            After = "300", LineRule = LineSpacingRuleValues.Auto
                        };
                    }

                    //上一步驟會將一般文章段落樣式套在表格儲存格內的文字段落,因此取出表格內的所有段落,將樣式覆寫
                    foreach (var t in mainPart.Document.Descendants <Table>())
                    {
                        foreach (var cell_p in t.Descendants <Paragraph>())
                        {
                            cell_p.ParagraphProperties.SpacingBetweenLines = new SpacingBetweenLines()
                            {
                                After = "0", LineRule = LineSpacingRuleValues.Auto
                            };
                        }
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }


            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
Exemple #17
0
        private void button_run_Click(object sender, EventArgs e)
        {
            VideoFileReader reader = new VideoFileReader();

            reader.Open(textBox_pathFile.Text);
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(@"C:\Users\Cake\Desktop\test.docx", DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                ParagraphProperties bodyProperty   = new ParagraphProperties();
                Justification       justification1 = new Justification()
                {
                    Val = JustificationValues.Center
                };
                bodyProperty.Append(justification1);
                Paragraph para = body.AppendChild(new Paragraph(bodyProperty));

                int iterator = (int)(reader.FrameRate / 3);

                for (int i = 0; i < 2000; i += iterator)
                {
                    Bitmap videoFrame  = reader.ReadVideoFrame(i);
                    Bitmap image       = (Bitmap)resizeImage(videoFrame, new Size(380, 100));
                    string str         = textBox_word.Text;
                    int    indexLetter = 0;
                    for (int y = 0; y < image.Height; y++)
                    {
                        for (int x = 0; x < image.Width; x++)
                        {
                            System.Drawing.Color color = image.GetPixel(x, y);
                            DocumentFormat.OpenXml.Wordprocessing.Color wordColor = new DocumentFormat.OpenXml.Wordprocessing.Color()
                            {
                                Val = color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2")
                            };
                            FontSize fontSize = new FontSize()
                            {
                                Val = "12"
                            };

                            RunProperties runPro = new RunProperties();
                            runPro.Append(wordColor);
                            runPro.Append(fontSize);

                            Run run = para.AppendChild(new Run());
                            run.AppendChild(runPro);
                            char letter = str[indexLetter];

                            run.AppendChild(new Text(letter.ToString()));

                            if (str.Length > 0)
                            {
                                indexLetter = (indexLetter + 1) % str.Length;
                            }
                        }
                        Run runNewLine = para.AppendChild(new Run());
                        runNewLine.AppendChild(new Break());
                    }

                    Run runBreakPage = para.AppendChild(new Run());
                    runBreakPage.AppendChild(new Break()
                    {
                        Type = BreakValues.Page
                    });

                    videoFrame.Dispose();
                    image.Dispose();
                }
            }

            reader.Close();
            MessageBox.Show("finish");
        }
Exemple #18
0
        //Main class function, export the mutationList to DOCX file, sets file name to patient's testName.
        public static void saveDOC(Patient patient, List <Mutation> mutationList, bool includePersonalDetails)
        {
            WordprocessingDocument myDoc = null;
            string fullPath = Properties.Settings.Default.ExportSavePath + @"\" + patient.TestName;

            if (includePersonalDetails)
            {
                fullPath += "_withDetails";
            }
            fullPath += ".docx";
            try
            {
                myDoc = WordprocessingDocument.Create(fullPath, WordprocessingDocumentType.Document);
            }
            catch (IOException)
            {
                throw;
            }
            MainDocumentPart mainPart = myDoc.AddMainDocumentPart();

            mainPart.Document = new Document();
            Body      body          = new Body();
            Paragraph paragraph     = new Paragraph();
            Run       run_paragraph = new Run();

            paragraph.Append(run_paragraph);

            //add paragraph for each detail of the patient.
            body.Append(generateParagraph("Test Name", true));
            body.Append(generateParagraph(patient.TestName, false));
            //add personal details of the patien, if includePersonalDetails=true
            if (includePersonalDetails)
            {
                body.Append(generateParagraph("ID", true));
                body.Append(generateParagraph(patient.PatientID, false));
                body.Append(generateParagraph("First Name", true));
                body.Append(generateParagraph(patient.FName, false));
                body.Append(generateParagraph("Last Name", true));
                body.Append(generateParagraph(patient.LName, false));
            }

            body.Append(generateParagraph("Pathological Number", true));
            body.Append(generateParagraph(patient.PathoNum, false));
            body.Append(generateParagraph("Run Number", true));
            body.Append(generateParagraph(patient.RunNum, false));
            body.Append(generateParagraph("Tumour Site", true));
            body.Append(generateParagraph(patient.TumourSite, false));
            body.Append(generateParagraph("Disease Level", true));
            body.Append(generateParagraph(patient.DiseaseLevel, false));
            body.Append(generateParagraph("Backgroud", true));
            body.Append(generateParagraph(patient.Background, false));
            body.Append(generateParagraph("Previous Treatment", true));
            body.Append(generateParagraph(patient.PrevTreatment, false));
            body.Append(generateParagraph("Current Treatment", true));
            body.Append(generateParagraph(patient.CurrTreatment, false));
            body.Append(generateParagraph("Conclusion", true));
            body.Append(generateParagraph(patient.Conclusion, false));

            //Add related mutation of the patient.
            CreateTable(body, mutationList);

            mainPart.Document.Append(body);
            mainPart.Document.Save();
            myDoc.Close();
        }
Exemple #19
0
        /// <summary>
        /// Creates a new document of type Document using a stream
        /// </summary>
        /// <returns></returns>
        public void Create()
        {
            stream = new MemoryStream();

            Create(WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, false));
        }
Exemple #20
0
        public string ConvertHtmlToOpenXml(string html, List <ParagraphImageData> listOfParagraphImageData)
        {
            ////create a outer html as htmldoc from html fragment
            //var htmlDocument = new HtmlDocument();

            //var node = HtmlNode.CreateNode("<html><head></head><body>" + html + "</body></html>");

            //htmlDocument.DocumentNode.AppendChild(node);

            string docOuterHtml = "<html><head></head><body>" + html + "</body></html>";

            //htmlDocument.DocumentNode.OuterHtml;

            //htmlDocument = null;

            //using struct will help dispose off memory stream, as auto disposed
            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);
                    }

                    // Assign a reference to the existing document body.
                    //Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                    // Add new text.
                    //Paragraph para = body.AppendChild(new Paragraph());
                    //Run run = para.AppendChild(new Run());
                    //run.AppendChild(new Text(txt));

                    //< w:document xmlns:w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" >

                    //< w:body >

                    //< w:p >

                    //< w:r >

                    //< w:t > Example text.</ w:t >

                    //</ w:r >

                    //</ w:p >

                    //</ w:body >
                    //</ w:document >

                    if (mainPart.Document.Elements <Paragraph>().Count() != 0)
                    {
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);
                    //string html = "<HTML><Body>Test</Body></HTML>";
                    //var paralist = converter.Parse(docOuterHtml);

                    //return entitizedTextFromXml;

                    Body body = mainPart.Document.Body;

                    var paragraphs = converter.Parse(html);

                    string entitizedTextFromXml = string.Empty;

                    foreach (OpenXmlCompositeElement t in paragraphs)
                    {
                        //body.Append(t);
                        entitizedTextFromXml += t.InnerXml;

                        // get all images in paragraph
                        List <A.Blip> imagesInParagraph = t.Descendants <A.Blip>().ToList();

                        if (imagesInParagraph.Any())
                        {
                            foreach (var imageInParagraph in imagesInParagraph)
                            {
                                string embed = imageInParagraph.Embed;
                            }
                        }
                    }

                    //clean control characters(invisible characters)
                    entitizedTextFromXml = CleanupControlCharactersAsEntities(entitizedTextFromXml);

                    entitizedTextFromXml = CleanupEscapedLineFeedCharacters(entitizedTextFromXml);


                    //// get all images in paragraph
                    //List<A.Blip> imagesInParagraph = paragraph.Descendants<A.Blip>().ToList();

                    //if (imagesInParagraph.Any())
                    //{
                    //    foreach (var imageInParagraph in imagesInParagraph)
                    //    {
                    //        string embed = imageInParagraph.Embed;
                    //    }
                    //}

                    mainPart.Document.Save();

                    var imageParts = mainPart.ImageParts;
                    foreach (var imagePart in imageParts)
                    {
                        var imageStream = imagePart.GetStream();
                        imageStream.Position = 0;
                        ParagraphImageData paragraphImageData = new ParagraphImageData();
                        paragraphImageData.ImageStream = new  MemoryStream();
                        imageStream.CopyTo(paragraphImageData.ImageStream);
                        paragraphImageData.ImageContentType = imagePart.ContentType;

                        listOfParagraphImageData.Add(paragraphImageData);
                    }
                    //generatedDocument.WriteTo(new FileStream("d:\\test05.docx", FileMode.Create));
                    return(entitizedTextFromXml);
                }


                //generatedDocument.WriteTo(new FileStream("d:\\test05.docx",FileMode.Create) );
            }
            //return "";
        }
Exemple #21
0
    public void ProcessRequest(System.Data.DataTable dt, string docFileName)
    { 

        using (MemoryStream mem = new MemoryStream())
        {
            // Create Document
            using (WordprocessingDocument wordDocument =
            WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
            {
                // Add a main document part. 
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                StyleDefinitionsPart stylePart= mainPart.AddNewPart<StyleDefinitionsPart>();

                RunProperties rPrNormal = new RunProperties();
                RunFonts rFont1 = new RunFonts();
                //rFont1.Ascii = "Times New Roman";
                //rPrNormal.Append(rFont1);
                rPrNormal.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "24" });
                DocumentFormat.OpenXml.Wordprocessing.Style style1 = new DocumentFormat.OpenXml.Wordprocessing.Style();
                style1.StyleId = "myText";
                style1.Append(new Name() { Val = "text" });
                style1.Append(rPrNormal);
                stylePart.Styles = new Styles();
                stylePart.Styles.Append(style1);
                
                RunProperties rPr = new RunProperties();
                Color color = new Color() { Val = "FF0000" };
                RunFonts rFont = new RunFonts();
                //rFont.Ascii = "Times New Roman";
                //rPr.Append(color);
                //rPr.Append(rFont);
                rPr.Append(new Bold());
                rPr.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "24" });
                DocumentFormat.OpenXml.Wordprocessing.Style style= new DocumentFormat.OpenXml.Wordprocessing.Style();
                style.StyleId = "myHeading1";
                style.Append(new Name() {Val="My Heading 1"});
                style.Append(new NextParagraphStyle() { Val = "Normal" });
                style.Append(rPr);
                stylePart.Styles = new Styles();
                stylePart.Styles.Append(style);
                stylePart.Styles.Save();

                // Create the document structure and add some text.
                mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                
                Body body = mainPart.Document.AppendChild(new Body());
                ParagraphProperties Normal_pPr = new ParagraphProperties(new ParagraphStyleId() { Val = "myText" });

                foreach (DataRow row in dt.Rows)
                {
                    Paragraph paraTo = body.AppendChild(new Paragraph());
                    Run runHead = paraTo.AppendChild(new Run());
                    RunProperties rpHead = new RunProperties();
                    rpHead.Append(new Bold());
                    runHead.Append(rpHead);
                    runHead.AppendChild(new Text("Mr.Ateet P"));
                    runHead.AppendChild(new Break());
                    runHead.AppendChild(new Text("Marketing Manager"));
                    runHead.AppendChild(new Break());
                    runHead.AppendChild(new Text("IPM Cell"));
                    runHead.AppendChild(new Break());
                    Run runTo = paraTo.AppendChild(new Run());                    
                    runTo.AppendChild(new Text("To"));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Text("" + row["ContactName"]));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Text(""+row["Address1"]));
                    runTo.AppendChild(new Break());
                    runTo.AppendChild(new Text("" + row["Address2"]));                                                            
                    Paragraph paraDate = body.AppendChild(new Paragraph());
                    ParagraphProperties ppDate = new ParagraphProperties();
                    Justification dateAlign = new Justification() { Val = JustificationValues.Right };
                    ppDate.Append(dateAlign);
                    paraDate.Append(ppDate);
                    Run runDate = paraDate.AppendChild(new Run());
                    runDate.AppendChild(new Text("Date : " + DateTime.Now.ToShortDateString()));                    
                    Paragraph paraTitle = body.AppendChild(new Paragraph());
                    ParagraphProperties heading_pPr = new ParagraphProperties();
                    heading_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "myHeading1" };
                    Justification centerHeading = new Justification() { Val = JustificationValues.Center };
                    heading_pPr.Append(centerHeading);
                    paraTitle.Append(heading_pPr);
                    Run runTitle = paraTitle.AppendChild(new Run());
                    runTitle.AppendChild(new Text("SUB : TECHNOLOGY TRANSFER - IP Licensing, Collaboration"));
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run run = para.AppendChild(new Run());
                    run.AppendChild(new Text("Dear Sir / Madam,"));
                    Paragraph para1 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run1 = para1.AppendChild(new Run());
                    run1.AppendChild(new Text("Greetings from IIT Madras!"));
                    Paragraph para2 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run2 = para2.AppendChild(new Run());
                    Text para21Text = new Text() { Text = "Indian Institute of Technology Madras, is a leading Institute for Technology Research and Education. Further details are available at ",Space=SpaceProcessingModeValues.Preserve};
                    run2.AppendChild(para21Text);
                    RunProperties rpBold = new RunProperties();
                    Bold bold = new Bold();
                    rpBold.Append(bold);
                    Text para22Text = new Text() { Text = "https://www.iitm.ac.in" };
                    run2.AppendChild(rpBold);
                    run2.AppendChild(para22Text);
                    Paragraph para3 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));                    
                    Run run3 = para3.AppendChild(new Run());
                    run3.AppendChild(new Text("Researchers at the institute have developed following technology with potential application in your industry. Details are as follows:"));
                    Paragraph para4 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new SpacingBetweenLines() { After = "120" })));
                    Run run4 = para4.AppendChild(new Run());
                    Text para41Text = new Text() { Text = "IP Type :     ", Space = SpaceProcessingModeValues.Preserve };
                    RunProperties rpBold4 = new RunProperties();
                    rpBold4.Append(new Bold());
                    run4.AppendChild(rpBold4);
                    rpBold4.Append(para41Text);
                    Run run41 = para4.AppendChild(new Run());
                    Text para42Text = new Text() { Text = "" + row["PType"]};
                    run41.Append(para42Text);
                    Paragraph para5 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new Justification() { Val = JustificationValues.Both }, new SpacingBetweenLines() { After = "120" })));
                    Run run5 = para5.AppendChild(new Run());
                    RunProperties rprun5 = new RunProperties();
                    rprun5.Append(new Bold());
                    run5.Append(rprun5);
                    Text para51Text = new Text() { Text = "Title :     ", Space = SpaceProcessingModeValues.Preserve };
                    run5.Append(para51Text);
                    Run run51 = para5.AppendChild(new Run());
                    run51.AppendChild(new Text("" + row["Title"]));
                    Paragraph para6 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new SpacingBetweenLines() { After = "120" })));
                    Run run6 = para6.AppendChild(new Run());
                    RunProperties rp6 = new RunProperties();
                    rp6.Append(new Bold());
                    run6.Append(rp6);
                    Text para61Text = new Text() {Text="Reference :     ", Space=SpaceProcessingModeValues.Preserve};
                    run6.Append(para61Text);
                    Run run61 = para6.AppendChild(new Run());
                    run61.Append( new Text ("Application Number : " + row["ApplicationNo"] + "            Filing Date : " + row["FilingDt"]));
                    Paragraph para7 = body.AppendChild(new Paragraph(new ParagraphProperties(new Indentation() { Left = "500" }, new Justification() { Val = JustificationValues.Both }, new SpacingBetweenLines() { After = "120" })));
                    Run run7 = para7.AppendChild(new Run());
                    RunProperties rp7 = new RunProperties();
                    rp7.Append(new Bold());
                    run7.Append(rp7);
                    Text para71Text = new Text() { Text = "Abstract :     ", Space = SpaceProcessingModeValues.Preserve };
                    run7.Append(para71Text);
                    Run run71 = para7.AppendChild(new Run());
                    run71.AppendChild(new Text("" + row["Specification"]));
                    Paragraph para8 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run8 = para8.AppendChild(new Run());
                    Text para81Text= new Text () {Text="We are writing to check your interest in the technology for Licensing, or further development. Other related technologies may be accessed at ", Space= SpaceProcessingModeValues.Preserve};
                    run8.Append(para81Text);
                    Text para82Text = new Text() { Text = "https://icsris.iitm.ac.in/ipr" };
                    RunProperties rp8 = new RunProperties();
                    rp8.Append(new Bold());
                    run8.Append(rp8);
                    run8.Append(para82Text);
                    Paragraph para10 = body.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines() { After = "120" })));
                    Run run10 = para10.AppendChild(new Run());
                    run10.AppendChild(new Text("We are looking forward to your interest and feedback."));
                    Paragraph para11 = body.AppendChild(new Paragraph());
                    Run run11 = para11.AppendChild(new Run());
                    run11.AppendChild(new Text("Yours sincerely,"));
                    Paragraph para12 = body.AppendChild(new Paragraph());
                    ParagraphProperties Design_pPr = new ParagraphProperties();
                    Design_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "myHeading1" };
                    para12.Append(Design_pPr);                    
                    Run run12 = para12.AppendChild(new Run());
                    run12.AppendChild(new Break());
                    run12.AppendChild(new Text("Marketing Manager"));
                    Paragraph tt1 = new Paragraph(new Run(new Break() { Type = BreakValues.Page }));
                    body.Append(tt1);
                }
                //Paragraph p232= new Paragraph();
               // ParagraphProperties pp220 = new ParagraphProperties();
                //SectionProperties sp1 = new SectionProperties();
                
                
                //.PrependChild<RunProperties>(rPrNormal);
                mainPart.Document.Save();
            }
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + docFileName);
            mem.Seek(0, SeekOrigin.Begin);
            mem.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();           
        }
    }
Exemple #22
0
        public static byte[] GetSeniorityList(SeniorityListReportViewModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      recordCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (SeniorityListRecord seniorityList in reportModel.SeniorityListRecords)
                        {
                            recordCount++;

                            using (MemoryStream listStream = new MemoryStream())
                            {
                                WordprocessingDocument listDocument = (WordprocessingDocument)wordTemplate.Clone(listStream);
                                listDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", reportModel.Classification },
                                    { "printedOn", reportModel.PrintedOn },
                                    { "districtName", seniorityList.DistrictName },
                                    { "localAreaName", seniorityList.LocalAreaName },
                                    { "districtEquipmentTypeName", seniorityList.DistrictEquipmentTypeName }
                                };

                                // update main document
                                MergeHelper.ConvertFieldCodes(listDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, listDocument.MainDocumentPart.Document);
                                listDocument.MainDocumentPart.Document.Save();

                                // setup table for seniority list
                                Table seniorityTable = GenerateSeniorityTable(seniorityList.SeniorityList, seniorityList);

                                // find our paragraph
                                Paragraph tableParagraph = null;
                                bool      found          = false;

                                foreach (OpenXmlElement paragraphs in listDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("SeniorityListTable"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(seniorityTable);
                                }

                                listDocument.MainDocumentPart.Document.Save();
                                listDocument.Save();

                                // merge owner into the master document
                                if (recordCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in listDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)listDocument.Clone(documentStream);

                                    listDocument.Close();
                                    listDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    listDocument.MainDocumentPart.DeleteParts(listDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = listDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    listDocument.MainDocumentPart.DeleteParts(listDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = listDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = listDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    listDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph pageBreak = new Paragraph(new Run(new Break {
                                        Type = BreakValues.Page
                                    }));

                                    mainPart.Document.Body.InsertAfter(pageBreak, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{recordCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    listDocument.Close();
                                    listDocument.Dispose();

                                    listStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(listStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemple #23
0
        //private string getFooter()
        //{
        //    StringBuilder _footer = new StringBuilder();
        //    if (ShowFooter)
        //    {
        //        String url = @"http://www.alsglobal.com/ALS.Corporate.Web/styles/img/logo_icon.png";
        //        _footer.Append(String.Format("<img src=\"{0}\" alt=\"Test picture\" />", url));
        //    }
        //    return _footer.ToString();
        //}

        //public string GenerateHtml()
        //{
        //    StringBuilder html = new StringBuilder();
        //    //html.Append("<html " + "xmlns:o='urn:schemas-microsoft-com:office:office' " + "xmlns:w='urn:schemas-microsoft-com:office:word'" + "xmlns='http://www.w3.org/TR/REC-html40'>" + "<head><title>Time</title>");
        //    ////The setting specifies document's view after it is downloaded as Print
        //    ////instead of the default Web Layout
        //    //html.Append("<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:Zoom>90</w:Zoom>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->");
        //    //html.Append("<style>" + "<!-- /* Style Definitions */" + "@page Section1" + "   {size:8.5in 11.0in; " + "   margin:0.2in 0.2in 0.2in 0.2in ; " + "   mso-header-margin:.5in; " + "   mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + "   {page:Section1;}" + "-->" + "</style></head>");
        //    //html.Append("<body lang=EN-US style='tab-interval:.5in'>");
        //    html.Append(getHeader().ToString());
        //    html.Append(getBody().ToString());
        //    html.Append(getFooter().ToString());
        //    //html.Append("</body>");
        //    //html.Append("</html>");
        //    return html.ToString();
        //}


        public void download(HttpContext p, string _filename)
        {
            string filename    = _filename + ".docx";
            string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

            //string html = File.ReadAllText(Server.MapPath("~/Template.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);

                    //setting the page margins go here
                    //DocumentFormat.OpenXml.Wordprocessing.PageMargin pageMargins = new DocumentFormat.OpenXml.Wordprocessing.PageMargin();
                    //pageMargins.Left = 600;
                    //pageMargins.Right = 600;
                    //pageMargins.Bottom = 500;
                    //pageMargins.Top = 500;
                    ////pageMargins.Header = 1500; //not needed for now
                    ////pageMargins.Footer = 1500; //not needed for now

                    ////Important needed to access properties (sections) to set values for all elements.
                    //DocumentFormat.OpenXml.Wordprocessing.SectionProperties sectionProps = new DocumentFormat.OpenXml.Wordprocessing.SectionProperties();
                    //sectionProps.Append(pageMargins);


                    Body body = mainPart.Document.Body;
                    // ------------------ PAGE 1 ------------------
                    var page1 = converter.Parse(Page1());
                    for (int i = 0; i < page1.Count; i++)
                    {
                        body.Append(page1[i]);
                    }
                    // ------------------ PAGE 2 ------------------
                    var page2 = converter.Parse(Page2());
                    for (int i = 0; i < page2.Count; i++)
                    {
                        body.Append(page2[i]);
                    }
                    mainPart.Document.Save();
                }

                byte[] bytesInStream = generatedDocument.ToArray(); // simpler way of converting to array
                generatedDocument.Close();

                p.Response.Clear();
                p.Response.ContentType = contentType;
                p.Response.AddHeader("content-disposition", "attachment;filename=" + filename);

                //this will generate problems
                p.Response.BinaryWrite(bytesInStream);
                try
                {
                    p.Response.End();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //Response.End(); generates an exception. if you don't use it, you get some errors when Word opens the file...
                }
            }

            //lblError.Visible = false;
            //lblFeedback.Visible = true;
        }
 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
             }
         }));
         Table           table   = new Table();
         TableProperties tblProp = new TableProperties(
             new TableBorders(
                 new TopBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new BottomBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new LeftBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new RightBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new InsideHorizontalBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         },
                 new InsideVerticalBorder()
         {
             Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 8
         }
                 )
             );
         table.AppendChild <TableProperties>(tblProp);
         TableRow  headerRow         = new TableRow();
         TableCell headerFIOCell     = new TableCell(new Paragraph(new Run(new Text("ФИО сотрудника"))));
         TableCell headerNameSerCell = new TableCell(new Paragraph(new Run(new Text("Тип билета"))));
         TableCell headerStatusCell  = new TableCell(new Paragraph(new Run(new Text("Статус"))));
         headerRow.Append(headerFIOCell);
         headerRow.Append(headerNameSerCell);
         headerRow.Append(headerStatusCell);
         table.Append(headerRow);
         int i = 1;
         foreach (var ticket in info.Tickets)
         {
             TableRow  tourRow    = new TableRow();
             TableCell fioCell    = new TableCell(new Paragraph(new Run(new Text(ticket.WorkerFIO))));
             TableCell nameCell   = new TableCell(new Paragraph(new Run(new Text(ticket.TypeTicket))));
             TableCell statusCell = new TableCell(new Paragraph(new Run(new Text(ticket.Status.ToString()))));
             tourRow.Append(fioCell);
             tourRow.Append(nameCell);
             tourRow.Append(statusCell);
             table.Append(tourRow);
             i++;
         }
         docBody.Append(table);
         docBody.AppendChild(CreateSectionProperties());
         wordDocument.MainDocumentPart.Document.Save();
     }
 }
        public ActionResult ExportDOC()
        {
            var stream = new MemoryStream();

            using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                new Document(new Body()).Save(mainPart);

                Body body = mainPart.Document.Body;

                var sessions = _context.Sessions.Include("Players").ToList();
                if (mapid != null)
                {
                    sessions = _context.Sessions.Where(s => s.MapId == mapid).Include("Players").ToList();
                }

                foreach (var c in sessions)
                {
                    body.Append(new Paragraph(new Run(new Text(c.Server))));

                    Table table = new Table();

                    TableProperties tblProp = new TableProperties(
                        new TableBorders(
                            new TopBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1
                    },
                            new BottomBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1
                    },
                            new LeftBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1
                    },
                            new RightBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1
                    },
                            new InsideHorizontalBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1
                    },
                            new InsideVerticalBorder()
                    {
                        Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1
                    }),
                        new TableStyle()
                    {
                        Val = "TableGrid"
                    },
                        new TableWidth()
                    {
                        Width = "5000", Type = TableWidthUnitValues.Pct
                    }
                        );
                    table.AppendChild <TableProperties>(tblProp);

                    TableRow tr = new TableRow();



                    TableCell tc1  = new TableCell(new Paragraph(new Run(new Text("Логін"))));
                    var       tcp1 = new TableCellProperties(new Shading()
                    {
                        Color = "auto", Fill = "a8a8a8", Val = ShadingPatternValues.Clear
                    });
                    tc1.Append(tcp1);
                    TableCell tc2  = new TableCell(new Paragraph(new Run(new Text("Пароль"))));
                    var       tcp2 = new TableCellProperties(new Shading()
                    {
                        Color = "auto", Fill = "b3b3b3", Val = ShadingPatternValues.Clear
                    });
                    tc2.Append(tcp2);
                    TableCell tc3  = new TableCell(new Paragraph(new Run(new Text("Нікнейм"))));
                    var       tcp3 = new TableCellProperties(new Shading()
                    {
                        Color = "auto", Fill = "c4c4c4", Val = ShadingPatternValues.Clear
                    });
                    tc3.Append(tcp3);
                    TableCell tc4  = new TableCell(new Paragraph(new Run(new Text("Персонажі"))));
                    var       tcp4 = new TableCellProperties(new Shading()
                    {
                        Color = "auto", Fill = "d1d1d1", Val = ShadingPatternValues.Clear
                    });
                    tc4.Append(tcp4);

                    tr.Append(tc1, tc2, tc3, tc4);
                    table.Append(tr);

                    var players = c.Players.ToList();

                    for (int i = 0; i < players.Count; i++)
                    {
                        TableRow tr1 = new TableRow();
                        tc1 = new TableCell(new Paragraph(new Run(new Text(players[i].Login))));
                        tc2 = new TableCell(new Paragraph(new Run(new Text(players[i].Password))));
                        tc3 = new TableCell(new Paragraph(new Run(new Text(players[i].Nickname))));
                        tr1.Append(tc1, tc2, tc3);

                        var    ab     = _context.CharacterChooses.Where(a => a.PlayerId == players[i].Id).Include(c => c.Character).ToList();
                        string charac = "";
                        foreach (var a in ab)
                        {
                            charac += a.Character.Name;
                        }
                        tc4 = new TableCell(new Paragraph(new Run(new Text(charac))));
                        tr1.Append(tc4);

                        table.Append(tr1);
                    }

                    body.Append(table);

                    body.Append(new Paragraph(new Run(new Text("\n\n"))));
                }

                doc.MainDocumentPart.Document.Save();

                mainPart.Document.Save();

                doc.Close();
            }
            stream.Seek(0, SeekOrigin.Begin);

            return(File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", $"gameDB_{DateTime.UtcNow.ToShortDateString()}.docx"));
        }
Exemple #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Read the data that has been posted
            connectedSiteUrl = Request.Form["connectedSiteUrl"];
            accessToken      = Request.Form["accessToken"];
            refreshToken     = Request.Form["refreshToken"];

            // Note that the following form fields were set dynamically by JavaScript
            // to represent the data from the document to be translated and the target language
            string documentContent = string.Empty;
            string targetLanguage  = string.Empty;

            documentContent = Request.Form["documentContent"];
            targetLanguage  = Request.Form["documentLanguage"];
            try
            {
                using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(connectedSiteUrl, accessToken))
                {
                    // Use standard CSOM and OOXML approaches for creating a file
                    Web    thisWeb    = context.Web;
                    List   docLib     = thisWeb.Lists.GetByTitle("Documents");
                    Folder rootFolder = docLib.RootFolder;
                    context.Load(thisWeb);
                    context.Load(docLib);
                    context.Load(rootFolder);
                    context.ExecuteQuery();
                    FileStream fs = null;
                    try
                    {
                        // We'll build a Word Document by using OOXML
                        // Note that we'll first create it in a folder in this Web app.
                        using (WordprocessingDocument wordDocument =
                                   WordprocessingDocument.Create(Server.MapPath("~/TempOOXML/SourceDocument.docx"),
                                                                 WordprocessingDocumentType.Document))
                        {
                            // Add a main document part.
                            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                            // Create the document structure.
                            mainPart.Document = new Document();
                            Body body = mainPart.Document.AppendChild(new Body());

                            // Create a paragraph based on the text that was posted
                            // in Request.Form["documentContent"]
                            Paragraph para = body.AppendChild(new Paragraph());
                            Run       run  = para.AppendChild(new Run());
                            run.AppendChild(new Text(documentContent));
                        }

                        // At this stage, the local file has been created in the folder of this Web project
                        // so we'll now read it and create a new file in SharePoint, based on this local file.
                        byte[] documentBytes;
                        fs            = System.IO.File.OpenRead(Server.MapPath("~/TempOOXML/SourceDocument.docx"));
                        documentBytes = new byte[fs.Length];
                        fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length));


                        // At this stage, the file contents of the OOXML document has been read into the byte array
                        // so we can use that as the content of a new file in SharePoint.
                        Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile
                            = new Microsoft.SharePoint.Client.FileCreationInformation();
                        ooxmlFile.Overwrite = true;
                        ooxmlFile.Url       = thisWeb.Url
                                              + rootFolder.ServerRelativeUrl
                                              + "/SharePointSourceDocument.docx";
                        ooxmlFile.Content = documentBytes;
                        Microsoft.SharePoint.Client.File newFile = rootFolder.Files.Add(ooxmlFile);
                        context.Load(newFile);
                        context.ExecuteQuery();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        // Tell the user what went wrong. These variables will be used
                        // to report the error to the user in the TextTranslator.aspx page.
                        success   = false;
                        exception = ex;
                    }
                    finally
                    {
                        // Clean up our filestream object
                        fs.Close();
                    }


                    // Do the actual translation work. Note that we use a synchronous translation
                    // approach here, but you could also use the TranslationJob object to
                    // perform an asynchronous translation.
                    if (success)
                    {
                        try
                        {
                            SyncTranslator job = new SyncTranslator(context, targetLanguage);
                            job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                            job.Translate(
                                thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx",
                                thisWeb.Url + rootFolder.ServerRelativeUrl + "/" + targetLanguage + "_Document.docx");
                            context.ExecuteQuery();
                            targetLibrary = thisWeb.Url + rootFolder.ServerRelativeUrl;
                        }
                        catch (Exception ex)
                        {
                            // Tell the user what went wrong. These variables will be used
                            // to report the error to the user in the TextTranslator.aspx page.
                            success   = false;
                            exception = ex;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Tell the user what went wrong. These variables will be used
                // to report the error to the user in the TextTranslator.aspx page.
                success   = false;
                exception = ex;
            }
        }
        public void CreateWithFalseAutoSaveTest()
        {
            var testfiles = CopyTestFiles("bvt")
                            .Where(fi => fi.IsOpenXmlFile());

            bool           autoSave       = false;
            OpenXmlPackage createdPackage = null;

            foreach (var testfile in testfiles)
            {
                string newlyCreatedName = null;
                if (testfile.IsWordprocessingFile())
                {
                    newlyCreatedName = Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");
                }
                else if (testfile.IsSpreadsheetFile())
                {
                    newlyCreatedName = Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".xlsx");
                }
                else if (testfile.IsPresentationFile())
                {
                    newlyCreatedName = Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".pptx");
                }

                Log.Comment("Opening source package in readOnly mode...");
                var sourcePackage = testfile.OpenPackage(false);
                Log.Comment("Creating new package with AutoSave={0}...", autoSave);
                if (testfile.IsWordprocessingFile())
                {
                    createdPackage = WordprocessingDocument.Create(newlyCreatedName, WordprocessingDocumentType.Document, autoSave);
                }
                else if (testfile.IsSpreadsheetFile())
                {
                    createdPackage = SpreadsheetDocument.Create(newlyCreatedName, SpreadsheetDocumentType.Workbook, autoSave);
                }
                else if (testfile.IsPresentationFile())
                {
                    createdPackage = PresentationDocument.Create(newlyCreatedName, PresentationDocumentType.Presentation, autoSave);
                }
                else
                {
                    Log.Fail("Unexpected document type passed in.");
                }
                if (createdPackage != null)
                {
                    Log.Comment("Feeding main part with DOM operations...");
                    duplicteMainPart(sourcePackage, createdPackage);
                    Log.Comment("Closing package...");
                    createdPackage.Close();
                }

                Log.Warning("Reopening...Expecting null for root element of main part as AutoSave is false thus no DOM changes will be saved.");
                if (testfile.IsWordprocessingFile())
                {
                    createdPackage = WordprocessingDocument.Open(newlyCreatedName, false);
                }
                else if (testfile.IsSpreadsheetFile())
                {
                    createdPackage = SpreadsheetDocument.Open(newlyCreatedName, false);
                }
                else if (testfile.IsPresentationFile())
                {
                    createdPackage = PresentationDocument.Open(newlyCreatedName, false);
                }
                else
                {
                    Log.Fail("Unexpected document type passed in.");
                }
                var mainpart = createdPackage.MainPart();
                var dom      = mainpart.RootElement;
                if (dom == null)
                {
                    Log.Pass("Null root element of main part just as expected.");
                }
                else
                {
                    Log.Fail("Root element of main part is not null. Something must be wrong.");
                }
                createdPackage.Close();
                FileInfo fz = new FileInfo(newlyCreatedName);
                if (fz.Exists)
                {
                    fz.Delete();
                }
            }
        }
        private void Window_Closed(object sender, System.EventArgs e) // SensorsNumbers window
        {
            if (window.sensorsNumbersBoxesFilled)
            {
                if (!AreThereIncorrectNumbers())
                {
                    using (WordprocessingDocument wordDocument =
                               WordprocessingDocument.Create(FolderPathAndName(), WordprocessingDocumentType.Document))
                    {
                        // Main
                        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                        mainPart.Document = new Document();
                        Body body = mainPart.Document.AppendChild(new Body());

                        // Head
                        Paragraph paragraph = body.AppendChild(new Paragraph());
                        body.AppendChild(new Paragraph()); // new line
                        ParagraphProperties paragraphPr = new ParagraphProperties();
                        paragraphPr.Justification = new Justification()
                        {
                            Val = JustificationValues.Center
                        };
                        paragraph.Append(paragraphPr);
                        Run           run   = paragraph.AppendChild(new Run());
                        RunProperties runPr = new RunProperties();
                        runPr.Bold     = new Bold();
                        runPr.FontSize = new FontSize()
                        {
                            Val = "32"
                        };
                        runPr.RunFonts = new RunFonts()
                        {
                            Ascii         = "Times New Roman",
                            ComplexScript = "Times New Roman",
                            HighAnsi      = "Times New Roman"
                        };
                        run.Append(runPr);
                        run.AppendChild(new Text("Задание на обработку"));

                        // Table_1
                        Table table_1 = CustomTable_1();
                        body.Append(table_1);
                        body.AppendChild(new Paragraph()); // new line

                        // Table_2
                        Table table_2 = CustomTable_2();
                        body.Append(table_2);
                        body.AppendChild(new Paragraph()); // new line

                        // Paragraph
                        body.AppendChild(SensorsCoeffitientsP());

                        // Table_3
                        Table table_3 = CustomTable_3();
                        body.Append(table_3);

                        // End
                        mainPart.Document.Save();
                        wordDocument.Close();
                    }
                    Department.Text          = Stand.Text = DateP.Text = TestNumber.Text =
                        NumberOfSensors.Text = FolderPath.Text = Unit.Text = null;
                }
                else
                {
                    MessageBox.Show("Среди указанных вами номеров датчиков есть номер, " +
                                    "которого не удалось найти в базе данных", "Указан неверный номер", MessageBoxButton.OK);
                }
            }
            else
            {
                MessageBox.Show("Вы не заполнили поля, поэтому отчет не будет создан", "", MessageBoxButton.OK);
            }
        }
        private void btnSimpleWordTest_Click(object sender, EventArgs e)
        {
            try
            {
                string filepath = "Mytest.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
                    ClsOpenXmlUtilitiesWord.AddStyle(mainPart, "MyHeading1", "style1", "Verdana", 28, "#0000FF", false, true, true);
                    ClsOpenXmlUtilitiesWord.AddStyle(mainPart, "MyTypeScript", "Macchina da scrivere", "Consolas", 10, "#333333", true, false, false);

                    // Add MyHeading1 styled text
                    Paragraph headingPar = ClsOpenXmlUtilitiesWord.CreateParagraphWithStyle("MyHeading1", JustificationValues.Center);
                    ClsOpenXmlUtilitiesWord.AddTextToParagraph(headingPar, "Titolo con stile applicato");
                    body.AppendChild(headingPar);

                    // Add MyTypeScript styled text
                    Paragraph typescriptPar = ClsOpenXmlUtilitiesWord.CreateParagraphWithStyle("MyTypeScript", JustificationValues.Left);
                    ClsOpenXmlUtilitiesWord.AddTextToParagraph(typescriptPar, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
                    body.AppendChild(typescriptPar);

                    // 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));


                    // Append a paragraph with styles
                    Paragraph newPar = createParagraphWithStyles();
                    body.AppendChild(newPar);

                    // Append a table
                    Table myTable = createTable();
                    body.Append(myTable);

                    // Append bullet list
                    createBulletNumberingPart(mainPart);
                    List <Paragraph> bulletList = createBulletList();
                    foreach (Paragraph paragraph in bulletList)
                    {
                        body.Append(paragraph);
                    }

                    // Append numbered list
                    List <Paragraph> numberedList = createNumberedList();
                    foreach (Paragraph paragraph in numberedList)
                    {
                        body.Append(paragraph);
                    }

                    // Append image
                    ClsOpenXmlUtilitiesWord.InsertPicture(doc, "panorama.jpg");
                }
                Process.Start(filepath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problemi col documento. Se è aperto da un altro programma, chiudilo e riprova...");
                MessageBox.Show(ex.Message);
            }
        }
Exemple #30
0
        private void button2_Click(object sender, EventArgs e)
        {
            string pathWord = "C:\\Users\\mishka\\Desktop\\UpWork\\wordTOXml\\wordTOXml\\bin\\Debug\\newword\\Before.docx";
            string savePath = "C:\\Users\\mishka\\Desktop\\UpWork\\wordTOXml\\wordTOXml\\bin\\Debug\\newword\\After.docx";

            using (var mainDoc = WordprocessingDocument.Open(pathWord, false))
                using (var resultDoc = WordprocessingDocument.Create(savePath,
                                                                     WordprocessingDocumentType.Document))
                {
                    // copy parts from source document to new document
                    foreach (var part in mainDoc.Parts)
                    {
                        resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId);
                    }

                    IEnumerable <DocumentFormat.OpenXml.Vml.Shape> shapes =
                        resultDoc.MainDocumentPart.Document.Body.Descendants <DocumentFormat.OpenXml.Vml.Shape>();

                    UInt32 height = 0;

                    foreach (var shape in shapes)
                    {
                        // Getting shape height for adjusting table height
                        var    val        = shape.Style.Value;
                        string height_str = val.Split(new string[] { "height:" }, StringSplitOptions.None)[1]
                                            .Split(new string[] { "pt;" }, StringSplitOptions.None)[0]
                                            .Trim();
                        double h1 = double.Parse(height_str, System.Globalization.CultureInfo.InvariantCulture);
                        int    h  = Convert.ToInt32(h1);
                        height = Convert.ToUInt32(h);

                        //shape
                        shape.HorizontalAlignment = DocumentFormat.OpenXml.Vml.Office.HorizontalRuleAlignmentValues.Center;
                    }

                    foreach (var cc in resultDoc.ContentControls())
                    {
                        DocumentFormat.OpenXml.Wordprocessing.Table table1 = new DocumentFormat.OpenXml.Wordprocessing.Table();

                        TableProperties tableProperties1 = new TableProperties();
                        DocumentFormat.OpenXml.Wordprocessing.TableStyle tableStyle1 = new DocumentFormat.OpenXml.Wordprocessing.TableStyle()
                        {
                            Val = "ad"
                        };
                        BiDiVisual biDiVisual1 = new BiDiVisual();
                        TableWidth tableWidth1 = new TableWidth()
                        {
                            Width = "5200", Type = TableWidthUnitValues.Pct
                        };
                        TableJustification tableJustification1 = new TableJustification()
                        {
                            Val = TableRowAlignmentValues.Center
                        };

                        TableCellMarginDefault tableCellMarginDefault1 = new TableCellMarginDefault();
                        TableCellLeftMargin    tableCellLeftMargin1    = new TableCellLeftMargin()
                        {
                            Width = 0, Type = TableWidthValues.Dxa
                        };
                        TableCellRightMargin tableCellRightMargin1 = new TableCellRightMargin()
                        {
                            Width = 0, Type = TableWidthValues.Dxa
                        };


                        tableCellMarginDefault1.Append(tableCellLeftMargin1);
                        tableCellMarginDefault1.Append(tableCellRightMargin1);
                        TableLook tableLook1 = new TableLook()
                        {
                            Val = "04A0"
                        };


                        tableProperties1.Append(tableStyle1);
                        tableProperties1.Append(biDiVisual1);
                        tableProperties1.Append(tableWidth1);
                        tableProperties1.Append(tableJustification1);
                        tableProperties1.Append(tableCellMarginDefault1);
                        tableProperties1.Append(tableLook1);


                        TableGrid  tableGrid1  = new TableGrid();
                        GridColumn gridColumn1 = new GridColumn()
                        {
                            Width = "555"
                        };
                        GridColumn gridColumn2 = new GridColumn()
                        {
                            Width = "556"
                        };


                        tableGrid1.Append(gridColumn1);
                        tableGrid1.Append(gridColumn2);

                        TableRow tableRow1 = new TableRow()
                        {
                            RsidTableRowAddition = "00AE49FD", RsidTableRowProperties = "00AE49FD"
                        };

                        TableRowProperties tableRowProperties1 = new TableRowProperties();
                        TableRowHeight     tableRowHeight1     = new TableRowHeight()
                        {
                            Val = 200, HeightType = HeightRuleValues.Exact
                        };

                        TableJustification tableJustification2 = new TableJustification()
                        {
                            Val = TableRowAlignmentValues.Center
                        };

                        tableRowProperties1.Append(tableRowHeight1);
                        tableRowProperties1.Append(tableJustification2);

                        TableCell tableCell1 = new TableCell();

                        TableCellProperties tableCellProperties1 = new TableCellProperties();
                        TableCellWidth      tableCellWidth1      = new TableCellWidth()
                        {
                            Width = "100", Type = TableWidthUnitValues.Pct
                        };
                        //tableCell1.TableCellProperties.TableCellMargin.BottomMargin = new BottomMargin() { Width = "0" };
                        //tableCell1.TableCellProperties.TableCellMargin.TopMargin = new TopMargin() { Width = "0" };
                        TableCellVerticalAlignment tableCellVerticalAlignment = new TableCellVerticalAlignment()
                        {
                            Val = TableVerticalAlignmentValues.Top
                        };
                        tableCellProperties1.Append(tableCellWidth1, tableCellVerticalAlignment);

                        DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph2 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph()
                        {
                            RsidParagraphAddition = "00AE49FD", RsidParagraphProperties = "00AE49FD", RsidRunAdditionDefault = "00AE49FD"
                        };

                        ParagraphProperties paragraphProperties2 = new ParagraphProperties();
                        Justification       justification1       = new Justification()
                        {
                            Val = JustificationValues.Right
                        };

                        ParagraphMarkRunProperties paragraphMarkRunProperties2 = new ParagraphMarkRunProperties();
                        RightToLeftText            rightToLeftText2            = new RightToLeftText();

                        paragraphMarkRunProperties2.Append(rightToLeftText2);

                        paragraphProperties2.Append(justification1);
                        paragraphProperties2.Append(paragraphMarkRunProperties2);

                        paragraph2.Append(paragraphProperties2);

                        tableCell1.Append(tableCellProperties1);
                        tableCell1.Append(paragraph2);

                        TableCell tableCell2 = new TableCell();

                        TableCellProperties tableCellProperties2 = new TableCellProperties();
                        TableCellWidth      tableCellWidth2      = new TableCellWidth()
                        {
                            Width = "100", Type = TableWidthUnitValues.Pct
                        };
                        //tableCell2.TableCellProperties.TableCellMargin.BottomMargin = new BottomMargin() { Width = "0" };
                        //tableCell2.TableCellProperties.TableCellMargin.TopMargin = new TopMargin() { Width = "0" };
                        TableCellVerticalAlignment tableCellVerticalAlignment1 = new TableCellVerticalAlignment()
                        {
                            Val = TableVerticalAlignmentValues.Bottom
                        };

                        tableCellProperties2.Append(tableCellWidth2);
                        tableCellProperties2.Append(tableCellVerticalAlignment1);

                        DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph3 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph()
                        {
                            RsidParagraphAddition = "00AE49FD", RsidParagraphProperties = "00AE49FD", RsidRunAdditionDefault = "00AE49FD"
                        };

                        ParagraphProperties paragraphProperties3 = new ParagraphProperties();
                        Justification       justification2       = new Justification()
                        {
                            Val = JustificationValues.Left
                        };

                        ParagraphMarkRunProperties paragraphMarkRunProperties3 = new ParagraphMarkRunProperties();
                        RightToLeftText            rightToLeftText3            = new RightToLeftText();

                        paragraphMarkRunProperties3.Append(rightToLeftText3);

                        paragraphProperties3.Append(justification2);
                        paragraphProperties3.Append(paragraphMarkRunProperties3);

                        paragraph3.Append(paragraphProperties3);

                        tableCell2.Append(tableCellProperties2);
                        tableCell2.Append(paragraph3);

                        tableRow1.Append(tableRowProperties1);
                        tableRow1.Append(tableCell1);
                        tableRow1.Append(tableCell2);

                        table1.Append(tableProperties1);
                        table1.Append(tableGrid1);
                        table1.Append(tableRow1);

                        cc.AppendChild(table1);
                    }
                }
        }