/// <summary>
        /// Append SubDocument at end of current doc
        /// </summary>
        /// <param name="content"></param>
        public void AppendSubDocument(Stream content, bool withPageBreak)
        {
            if (wdDoc == null)
            {
                throw new InvalidOperationException("Document not loaded");
            }

            AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

            formatImportPart.FeedData(content);

            AltChunk altChunk = new AltChunk();

            altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart);

            wdMainDocumentPart.Document.Body.Elements <Paragraph>().Last().InsertAfterSelf(altChunk);

            if (withPageBreak)
            {
                Paragraph p = new Paragraph(
                    new Run(
                        new Break()
                {
                    Type = BreakValues.Page
                }));
                altChunk.InsertAfterSelf(p);
            }
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: mono {0} inputfile.html outputfile.docx",
                                  System.AppDomain.CurrentDomain.FriendlyName);
                return;
            }

            string inputFile  = args[0];
            string outputFile = args[1];

            using (WordprocessingDocument myDoc =
                       WordprocessingDocument.Create(
                           outputFile, WordprocessingDocumentType.Document))
            {
                string           altChunkId = "AltChunkId1";
                MainDocumentPart mainPart   = myDoc.AddMainDocumentPart();
                mainPart.Document      = new Document();
                mainPart.Document.Body = new Body();
                var chunk = mainPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.Html, altChunkId);
                using (FileStream fileStream =
                           File.Open(inputFile, FileMode.Open))
                {
                    chunk.FeedData(fileStream);
                }
                AltChunk altChunk = new AltChunk()
                {
                    Id = altChunkId
                };
                mainPart.Document.Append(altChunk);
                mainPart.Document.Save();
            }
        }
Exemple #3
0
        private static void CombinarDocumentos(List <string> anexos, MainDocumentPart documentoBase)
        {
            if (anexos != null)
            {
                if (anexos.Count > 0)
                {
                    foreach (var anexo in anexos)
                    {
                        AlternativeFormatImportPart chunk =
                            documentoBase.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

                        using (FileStream fileStream = File.Open(anexo, FileMode.Open))
                        {
                            chunk.FeedData(fileStream);
                        }

                        AltChunk altChunk = new AltChunk()
                        {
                            Id = documentoBase.GetIdOfPart(chunk)
                        };

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

                        documentoBase.Document.Body.AppendChild(saltoPagina);
                        documentoBase.Document.Body.AppendChild(altChunk);
                    }

                    //documentoBase.Document.Save();
                }
            }
        }
Exemple #4
0
    /// <summary>
    /// Merges docxs in a new docx
    /// </summary>
    /// <param name="path">A new document destination</param>
    /// <param name="documents">Documents to be merged</param>
    private static void GenerateDocument(string path, List <byte[]> documents)
    {
        GenerateNewDocx(path);

        using (WordprocessingDocument mainDoc = WordprocessingDocument.Open(path, true))
        {
            MainDocumentPart mainPart         = mainDoc.MainDocumentPart;
            XDocument        mainDocumentXDoc = GetXDocument(mainDoc);

            foreach (var item in documents)
            {
                var currentAltChunkId             = findNextIdForAltChunk(mainDocumentXDoc);
                AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
                    currentAltChunkId);

                chunk.FeedData(GetStream(item));

                XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", currentAltChunkId));

                mainDocumentXDoc.Root
                .Element(w + "body")
                .Elements()
                .Last()
                .AddAfterSelf(altChunk);
            }

            SaveXDocument(mainDoc, mainDocumentXDoc);
        }
    }
Exemple #5
0
        static void DocxMerge(string srcFile1, string srcFile2, string outFile)
        {
            File.Delete(outFile);
            File.Copy(srcFile1, outFile);

            using (WordprocessingDocument myDoc =
                       WordprocessingDocument.Open(outFile, true))
            {
                string                      altChunkId = "AltChunkId1";
                MainDocumentPart            mainPart   = myDoc.MainDocumentPart;
                AlternativeFormatImportPart chunk      =
                    mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML,
                        altChunkId);

                using (FileStream fileStream = File.Open(srcFile2,
                                                         FileMode.Open))
                    chunk.FeedData(fileStream);

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainPart.Document.Body.InsertAfter(altChunk,
                                                   mainPart.Document.Body.Elements <Paragraph>().Last());
                mainPart.Document.Save();
            }
        }
Exemple #6
0
        public void HtmlToWordPartial(string html, string destinationFileName)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(destinationFileName, WordprocessingDocumentType.Document))
            {
                string altChunkId = "myId";

                MainDocumentPart mainPart = wordDocument.MainDocumentPart;
                if (mainPart == null)
                {
                    mainPart = wordDocument.AddMainDocumentPart();
                    new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart);
                }
                MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(html)).ToArray());

                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainPart.Document.Body.Append(altChunk);
                wordDocument.Save();
                wordDocument.Close();
            }
        }
Exemple #7
0
        //gavdcodeend 06

        //gavdcodebegin 07
        public static void WordOpenXmlJoinTwoDocuments()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                string           altChunkId = "ID" + Guid.NewGuid().ToString();
                MainDocumentPart mainPart   = myWordDoc.MainDocumentPart;

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

                using (FileStream fileStream =
                           File.Open(@"C:\Temporary\WordDoc02.docx", FileMode.Open))

                    myChunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk
                {
                    Id = altChunkId
                };
                mainPart.Document.Body
                .InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>()
                             .Last());
                mainPart.Document.Save();
            }
        }
Exemple #8
0
        public void Update(DocumentFormat.OpenXml.Wordprocessing.Tag tag, string value, MainDocumentPart mainPart)
        {
            string mainhtml = "<html><head><style type='text/css'>.catalogGeneralTable{border-collapse: collapse;text-align: left;} .catalogGeneralTable td, th{ padding: 5px; border: 1px solid #999999; } </style></head> <body style='font-family:Trebuchet MS;font-size:.9em;'>" + value + "</body></html>";


            int    blockLevelCounter = 1;
            string altChunkId        = String.Format("AltChunkId{0}", altChunkIdCounter++);

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

            using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter stringWriter = new StreamWriter(chunkStream, Encoding.UTF8)) //Encoding.UTF8 is important to remove special characters
                {
                    stringWriter.Write(mainhtml);
                }
            }

            AltChunk altChunk = new AltChunk();

            altChunk.Id = altChunkId;

            SdtBlock sdtBlock = tag.Ancestors <SdtBlock>().Single();

            sdtBlock.InsertAt(altChunk, blockLevelCounter++);
        }
         private static byte[] Merge(byte[] dest, byte[] src)
         {
             string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString();
 
             var memoryStreamDest = new MemoryStream();
             memoryStreamDest.Write(dest, 0, dest.Length);
             memoryStreamDest.Seek(0, SeekOrigin.Begin);
             var memoryStreamSrc = new MemoryStream(src);
 
             using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true))
             {
                 MainDocumentPart mainPart = doc.MainDocumentPart;
                 AlternativeFormatImportPart altPart =
                     mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                 altPart.FeedData(memoryStreamSrc);
                 var altChunk = new AltChunk();
                 altChunk.Id = altChunkId;
                               OpenXmlElement lastElem = mainPart.Document.Body.Elements<AltChunk>().LastOrDefault();
             if(lastElem == null)
             {
                 lastElem = mainPart.Document.Body.Elements<Paragraph>().Last();
             }
             //Page Brake einfügen
             Paragraph pageBreakP = new Paragraph();
             Run pageBreakR = new Run();
             Break pageBreakBr = new Break() { Type = BreakValues.Page };
             pageBreakP.Append(pageBreakR);
             pageBreakR.Append(pageBreakBr);                
 
             return memoryStreamDest.ToArray();
         }
     }
Exemple #10
0
        public WordManipulator AppendOtherWordFile(String wordFilePath, Boolean addPageBreak = true)
        {
            MainDocumentPart            mainPart   = _document.MainDocumentPart;
            string                      altChunkId = "AltChunkId" + Guid.NewGuid().ToString();
            AlternativeFormatImportPart chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

            using (FileStream fileStream = File.Open(wordFilePath, FileMode.Open))
            {
                chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                .Body
                .InsertAfter(altChunk, mainPart.Document.Body
                             .Elements().LastOrDefault());
                mainPart.Document.Save();
            }
            if (addPageBreak)
            {
                _body.Append(
                    new Paragraph(
                        new Run(
                            new Break()
                {
                    Type = BreakValues.Page
                })));
            }
            return(this);
        }
Exemple #11
0
        //OpenXML Word中写入html
        private void button9_Click(object sender, EventArgs e)
        {
            string docName = @"openxmltest-copy.docx";

            File.Copy(@"openxmltest.docx", docName, true);
            using (WordprocessingDocument doc = WordprocessingDocument.Open(docName, true))
            {
                string           altChunkId  = "myId";
                MainDocumentPart mainDocPart = doc.MainDocumentPart;

                var run       = new DocumentFormat.OpenXml.Wordprocessing.Run(new Text("test"));
                var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new ParagraphProperties(
                                                                                        new Justification()
                {
                    Val = JustificationValues.Center
                }),
                                                                                    run);

                //RunProperties runProperties = new RunProperties(); //属性

                //RunFonts fonts = new RunFonts() { EastAsia = "DFKai-SB" }; // 设置字体
                //FontSize size = new FontSize() { Val = "52" }; // 设置字体大小
                //DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "red" }; // 设置字体样式

                //// 将样式添加到属性里面
                //runProperties.Append(color);
                //runProperties.Append(size);
                //runProperties.Append(fonts);

                //run.Append(runProperties);
                //paragraph.Append(run);

                var body = mainDocPart.Document.Body;
                body.Append(paragraph);

                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body><h1>HELLO</h1></body></html>"));
                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                using (StreamReader reader = new StreamReader("苏州抵押合同模板.html")) //苏州抵押合同模板.html 苏州借款合同模板-3月.html
                {
                    string content = reader.ReadToEnd();
                    ms = new MemoryStream(Encoding.UTF8.GetBytes(content));
                }

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart =
                    mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                body.Append(altChunk);
                //mainDocPart.Document.Save();
            }
        }
Exemple #12
0
 public void open(string fname)
 {
     wordDocument      = WordprocessingDocument.Create(fname, WordprocessingDocumentType.Document, true);
     mainPart          = wordDocument.AddMainDocumentPart();
     mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
     body  = mainPart.Document.AppendChild(new Body());
     chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf, altChunkId);
 }
Exemple #13
0
        /// <summary>
        /// Append SubDocument at end of current doc
        /// </summary>
        /// <param name="content"></param>
        /// <param name="withPageBreak">If true insert a page break before.</param>
        public void AppendSubDocument(Stream content, bool withPageBreak)
        {
            if (wdDoc == null)
            {
                throw new InvalidOperationException("Document not loaded");
            }

            AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

            formatImportPart.FeedData(content);

            AltChunk altChunk = new AltChunk();

            altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart);

            OpenXmlElement lastElement = wdMainDocumentPart.Document.Body.LastChild;

            if (lastElement is SectionProperties)
            {
                lastElement.InsertBeforeSelf(altChunk);
                if (withPageBreak)
                {
                    SectionProperties sectionProps = (SectionProperties)lastElement.Clone();
                    var p   = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    var ppr = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties();
                    p.AppendChild(ppr);
                    ppr.AppendChild(sectionProps);
                    altChunk.InsertBeforeSelf(p);
                }
            }
            else
            {
                lastElement.InsertAfterSelf(altChunk);
                if (withPageBreak)
                {
                    Paragraph p = new Paragraph(
                        new Run(
                            new Break()
                    {
                        Type = BreakValues.Page
                    }));
                    altChunk.InsertBeforeSelf(p);
                }
            }
        }
Exemple #14
0
        private string Compose(string[] sourceFiles, string outputFile)
        {
            string altChunkIdBase  = "acID";
            int    altChunkCounter = 1;
            string altChunkId      = altChunkIdBase + altChunkCounter.ToString();

            // 选择第一个文件为主文件,保留里面的样式
            string masterFile = sourceFiles[0];

            File.Copy(masterFile, outputFile, true);

            // 后续文件合并进来
            List <string> fileList = sourceFiles.ToList();

            fileList.RemoveAt(0);

            // 打开目标文件进行合并
            MainDocumentPart wdDocTargetMainPart = null;
            Document         docTarget           = null;
            AlternativeFormatImportPartType afType;

            using (WordprocessingDocument wdPkgTarget = WordprocessingDocument.Open(outputFile, true))
            {
                wdDocTargetMainPart = wdPkgTarget.MainDocumentPart;

                docTarget = wdDocTargetMainPart.Document;
                Paragraph           lastParaTarget = docTarget.Body.Descendants <Paragraph>().Last();
                ParagraphProperties paraPropTarget = lastParaTarget.ParagraphProperties;
                if (paraPropTarget == null)
                {
                    paraPropTarget = new ParagraphProperties();
                }
                Run paraRun = lastParaTarget.Descendants <Run>().FirstOrDefault();

                foreach (string fi in fileList)
                {
                    afType = AlternativeFormatImportPartType.WordprocessingML;
                    AlternativeFormatImportPart chunk            = wdDocTargetMainPart.AddAlternativeFormatImportPart(afType, altChunkId);
                    System.IO.FileStream        fsSourceDocument = new FileStream(fi, FileMode.Open);
                    chunk.FeedData(fsSourceDocument);
                    //Create the chunk
                    AltChunk ac = new AltChunk
                    {
                        //Link it to the part
                        Id = altChunkId
                    };
                    docTarget.Body.Append(ac);
                    docTarget.Save();
                    altChunkCounter += 1;
                    altChunkId       = altChunkIdBase + altChunkCounter.ToString();
                    chunk            = null;
                    ac = null;
                }
            }

            return(outputFile);
        }
Exemple #15
0
    public static int Main(string[] args)
    {
      // https://docs.microsoft.com/ja-jp/dotnet/api/documentformat.openxml.wordprocessing.altchunk?view=openxml-2.8.1

      var app = new CommandLineApplication(throwOnUnexpectedArg: false);
      app.Name = nameof(docxmerge);
      app.Description = "Mearge .docx files. ";
      app.HelpOption("-h|--help");
      app.ExtendedHelpText = @"Merged files should be the end of argument like: 
      docxmerge [options] file1 file2
      ";
      var optionTemplateFile = app.Option(
        template: "-t|--template",
        description: "Template filename. merged files will be appended after the contents of template file. ",
        optionType: CommandOptionType.SingleValue
      );

      var optionOutFile = app.Option(
        template: "-o|--output",
        description: "Output filename",
        optionType: CommandOptionType.SingleValue
      );

      app.OnExecute(() =>
      {
        var templateFile = optionTemplateFile.Value();
        var outFile = optionOutFile.Value();
        // Because position of last paragraph is not updated while looping
        var mergedFiles = app.RemainingArguments;
        mergedFiles.Reverse();
        File.Delete(outFile);
        File.Copy(templateFile, outFile);

        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outFile, true))
        {
          MainDocumentPart mainPart = myDoc.MainDocumentPart;
          foreach (var f in mergedFiles.Select((Value, Index) => new { Value, Index }))
          {
            string altChunkId = $"AltChunkId{f.Index}";
            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
              AlternativeFormatImportPartType.WordprocessingML, altChunkId
            );
            using (FileStream fileStream = File.Open(f.Value, FileMode.Open))
            {
              chunk.FeedData(fileStream);
            }
            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;
            mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());

          }
          mainPart.Document.Save();
        }
      });
      return app.Execute(args);
    }
Exemple #16
0
        /// <summary>
        /// Constructs a new instance of the class.
        /// </summary>
        /// <param name="mainPart">The template document's <see cref="MainDocumentPart"/></param>
        public SmartPAFMappedFieldSet(MainDocumentPart mainPart)
        {
            Table PAFFields = mainPart.Document.Body.Elements <Table>().ElementAt(0);

            PAF_ProbationaryMidpoint          = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(1));
            PAF_PeriodicPerformanceAssessment = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(2).Elements <TableCell>().ElementAt(1));
            PAF_RatingJustification           = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(3).Elements <TableCell>().ElementAt(1));
            PAF_EmployeeName     = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(5).Elements <TableCell>().ElementAt(1));
            PAF_PayrollId        = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(6).Elements <TableCell>().ElementAt(1));
            PAF_StartDate        = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(7).Elements <TableCell>().ElementAt(1));
            PAF_EndDate          = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(7).Elements <TableCell>().ElementAt(3));
            PAF_ClassGrade       = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(9).Elements <TableCell>().ElementAt(1));
            PAF_DistrictDivision = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(8).Elements <TableCell>().ElementAt(1));

            PAF_Assessment            = new SmartParagraph(mainPart.Document.Body.Elements <Table>().ElementAt(1).Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(0));
            PAF_Assessment_Chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, "assessmentChunk");
            PAF_Recommendations       = new SmartParagraph(mainPart.Document.Body.Elements <Table>().ElementAt(2).Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(0));
            PAF_Recommendations_Chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, "recommendationsChunk");
        }
Exemple #17
0
        public static void DoConversionViaWord(FileInfo newAltChunkBeforeFi, FileInfo newAltChunkAfterFi, XElement html)
        {
            var blankAltChunkFi = new DirectoryInfo(Path.Combine(TestUtil.SourceDir.FullName, "Blank-altchunk.docx"));

            File.Copy(blankAltChunkFi.FullName, newAltChunkBeforeFi.FullName);
            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(newAltChunkBeforeFi.FullName, true))
            {
                string                      altChunkId = "AltChunkId1";
                MainDocumentPart            mainPart   = myDoc.MainDocumentPart;
                AlternativeFormatImportPart chunk      = mainPart.AddAlternativeFormatImportPart(
                    "application/xhtml+xml", altChunkId);
                using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
                    using (StreamWriter stringStream = new StreamWriter(chunkStream))
                        stringStream.Write(html.ToString());
                XElement altChunk = new XElement(W.altChunk,
                                                 new XAttribute(R.id, altChunkId)
                                                 );
                XDocument mainDocumentXDoc = myDoc.MainDocumentPart.GetXDocument();
                mainDocumentXDoc.Root
                .Element(W.body)
                .AddFirst(altChunk);
                myDoc.MainDocumentPart.PutXDocument();
            }

            WordAutomationUtilities.OpenAndSaveAs(newAltChunkBeforeFi.FullName, newAltChunkAfterFi.FullName);

            while (true)
            {
                try
                {
                    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(newAltChunkAfterFi.FullName, true))
                    {
                        SimplifyMarkupSettings settings2 = new SimplifyMarkupSettings
                        {
                            RemoveMarkupForDocumentComparison = true,
                        };
                        MarkupSimplifier.SimplifyMarkup(wDoc, settings2);
                        XElement newRoot = (XElement)RemoveDivTransform(wDoc.MainDocumentPart.GetXDocument().Root);
                        wDoc.MainDocumentPart.GetXDocument().Root.ReplaceWith(newRoot);
                        wDoc.MainDocumentPart.PutXDocumentWithFormatting();
                    }
                    break;
                }
                catch (IOException)
                {
                    System.Threading.Thread.Sleep(50);
                    continue;
                }
            }
        }
Exemple #18
0
        private void button2_Click(object sender, EventArgs e)
        {
            //AddHeaderFromTo(@"C:\Temp\Teste1.docx", @"C:\Temp\Teste2.docx");

            using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Temp\Teste2.docx", true))
            {
                string altChunkId = "AltChunkId5";

                MainDocumentPart            mainDocPart = doc.MainDocumentPart;
                AlternativeFormatImportPart chunk       = mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf, altChunkId);

                string rtfEncodedString = richTextBox1.Rtf;

                using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString)))
                {
                    chunk.FeedData(ms);
                }

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                // Funciona adicionando na sequencia
                //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());


                //teste para adicionar no cabeçalho
                //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());

                // itera os elementos do documento
                //var paragraphs = doc.MainDocumentPart.Document.Body.Elements<Paragraph>();
                // Iterate through paragraphs, runs, and text, finding the text we want and replacing it
                //foreach (Paragraph paragraph in paragraphs)
                //{
                //    foreach (Run run in paragraph.Elements<Run>())
                //    {
                //        foreach (Text text in run.Elements<Text>())
                //        {
                //            if (text.Text == "CABEÇALHO")
                //            {
                //                text.Text = "CABEÇALHO 2";
                //           }
                //        }
                //    }
                //}

                mainDocPart.Document.Save();
            }
        }
Exemple #19
0
        private void SetHtml(MainDocumentPart mainDocumentPart, string sdtBlockTag, string value, OpenXmlElement elem)
        {
            string       html       = "<html><body><div>" + value + "</div></body></html>";
            string       altChunkId = sdtBlockTag;
            MemoryStream ms         = new MemoryStream(Encoding.Default.GetBytes(html));
            AlternativeFormatImportPart formatImportPart =
                mainDocumentPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.Html, altChunkId);

            formatImportPart.FeedData(ms);
            ms.Close();
            AltChunk altChunk = new AltChunk();

            altChunk.Id = altChunkId;
            elem.Append(altChunk);
        }
Exemple #20
0
    private void generatedocxfile(StringBuilder strHTMLContent, string FederationName)
    {
        /*t create and init a new docx file and
         * a WordprocessingDocument object to represent it t*/

        string docPath = getPPRPath();

        //string docPath=GetSavePath();

        DocumentFormat.OpenXml.Packaging.WordprocessingDocument doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(docPath + FederationName + ".docx", WordprocessingDocumentType.Document);
        MainDocumentPart mainDocPart = doc.AddMainDocumentPart();

        mainDocPart.Document = new Document();
        Body body = new Body();

        mainDocPart.Document.Append(body);

        // Add an aFChunk part to the package
        string altChunkId = "AltChunkId1";

        AlternativeFormatImportPart chunk = mainDocPart
                                            .AddAlternativeFormatImportPart(
            AlternativeFormatImportPartType.Xhtml, altChunkId);

        string html = strHTMLContent.ToString();

        using (MemoryStream ms =
                   new MemoryStream(Encoding.UTF8.GetBytes(html)))
        {
            chunk.FeedData(ms);
        }

        // Add the aFChunk to the document
        AltChunk altChunk = new AltChunk();

        altChunk.Id = altChunkId;
        mainDocPart.Document.Body.Append(altChunk);

        /*t to save the changes t*/
        doc.MainDocumentPart.Document.Save();
        doc.Dispose();
    }
Exemple #21
0
    //-----Word
    /// <summary>
    /// 将html导出为Word
    /// </summary>
    /// <param name="html">必须以<html>包裹</param>
    /// <param name="vpath">保存路径</param>
    /// <returns></returns>
    public static string W_HtmlToWord(string html, string vpath)
    {
        if (string.IsNullOrEmpty(html))
        {
            throw new Exception("未指定需要生成Word的内容");
        }
        if (string.IsNullOrEmpty(vpath))
        {
            throw new Exception("未指定Word保存路径");
        }
        string ppath = function.VToP(vpath);
        string pdir  = Path.GetDirectoryName(ppath);

        if (!Directory.Exists(pdir))
        {
            Directory.CreateDirectory(pdir);
        }

        byte[]       array  = Encoding.UTF8.GetBytes(html);
        MemoryStream stream = new MemoryStream(array);

        using (WordprocessingDocument myDoc = WordprocessingDocument.Create(ppath, WordprocessingDocumentType.Document))
        {
            string           altChunkId = "AltChunkId";
            MainDocumentPart mainPart   = myDoc.AddMainDocumentPart();
            mainPart.Document      = new Document();
            mainPart.Document.Body = new Body();
            var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
            chunk.FeedData(stream);
            AltChunk altChunk = new AltChunk()
            {
                Id = altChunkId
            };
            mainPart.Document.Append(altChunk);
            mainPart.Document.Save();
            stream.Dispose();
        }
        return(vpath);
    }
        public static void AppendOtherWordFile(this Document document, String wordFilePath, Boolean addPageBreak = true)
        {
            if (addPageBreak)
            {
                document.AddPageBreak();
            }
            MainDocumentPart            mainPart   = document.MainDocumentPart;
            string                      altChunkId = "AltChunkId" + Guid.NewGuid().ToString();
            AlternativeFormatImportPart chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

            using (FileStream fileStream = File.Open(wordFilePath, FileMode.Open))
            {
                chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                .Body
                .InsertAfter(altChunk, mainPart.Document.Body
                             .Elements().LastOrDefault());
                mainPart.Document.Save();
            }
        }
Exemple #23
0
        public void CreateWordDocument(String file_path, String rtfEncodedString)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(file_path, WordprocessingDocumentType.Document))
            {
                // Create main document, add body and paragraph
                MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
                mainDocPart.Document = new Document();
                Body body = new Body();
                mainDocPart.Document.Append(body);

                String altChunkId = "Id1";

                // Set alternative format RTF to import text
                AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.Rtf, altChunkId);

                // Convert rtf to chunk data
                using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString)))
                {
                    chunk.FeedData(ms);
                }

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainDocPart.Document.Body.InsertAt(
                    altChunk, 0);

                // Save changes to the main document part.
                mainDocPart.Document.Save();

                // Open word compatible aplication
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = file_path;
                Process.Start(startInfo);
            }
        }
        private static byte[] Merge(byte[] dest, byte[] src)
        {
            string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString();

            var memoryStreamDest = new MemoryStream();

            memoryStreamDest.Write(dest, 0, dest.Length);
            memoryStreamDest.Seek(0, SeekOrigin.Begin);
            var memoryStreamSrc = new MemoryStream(src);

            using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true))
            {
                MainDocumentPart            mainPart = doc.MainDocumentPart;
                AlternativeFormatImportPart altPart  =
                    mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                altPart.FeedData(memoryStreamSrc);
                var altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>().Last());
                mainPart.Document.Save();
            }

            return(memoryStreamDest.ToArray());
        }
Exemple #25
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 #26
0
        /// <summary>
        /// 產生Word檔
        /// </summary>
        /// <param name="templateFile"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static byte[] MakeDocx(List <InputDatas> inputDatas)
        {
            try
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    if (inputDatas != null && inputDatas.Count > 0)
                    {
                        using (FileStream memFileStream = File.OpenRead(inputDatas[0].FilePath))
                        {
                            memStream.SetLength(memFileStream.Length);
                            memFileStream.Read(memStream.GetBuffer(), 0, (int)memFileStream.Length);
                        }

                        using (WordprocessingDocument mainWD = WordprocessingDocument.Open(memStream, true))
                        {
                            MainDocumentPart mainPart = mainWD.MainDocumentPart;
                            if (inputDatas[0].InputMessage != null)
                            {
                                //Replace key to data
                                Parse(mainPart, inputDatas[0].InputMessage);

                                foreach (HeaderPart hp in mainPart.HeaderParts)
                                {
                                    Parse(hp, inputDatas[0].InputMessage);
                                }

                                foreach (FooterPart fp in mainPart.FooterParts)
                                {
                                    Parse(fp, inputDatas[0].InputMessage);
                                }
                            }

                            for (int i = inputDatas.Count - 1; i >= 1; i--)
                            {
                                string altChunkId = "AltChunkId" + i;
                                AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                                    AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                using (MemoryStream childStream = new MemoryStream())
                                {
                                    using (FileStream childFileStream = File.OpenRead(inputDatas[i].FilePath))
                                    {
                                        childStream.SetLength(childFileStream.Length);
                                        childFileStream.Read(childStream.GetBuffer(), 0, (int)childFileStream.Length);
                                    }
                                    using (WordprocessingDocument childWD = WordprocessingDocument.Open(childStream, true))
                                    {
                                        MainDocumentPart childPart = childWD.MainDocumentPart;

                                        if (inputDatas[i].InputMessage != null)
                                        {
                                            //Replace key to data
                                            Parse(childPart, inputDatas[i].InputMessage);

                                            foreach (HeaderPart hp in childPart.HeaderParts)
                                            {
                                                Parse(hp, inputDatas[i].InputMessage);
                                            }

                                            foreach (FooterPart fp in childPart.FooterParts)
                                            {
                                                Parse(fp, inputDatas[i].InputMessage);
                                            }
                                        }

                                        childWD.Close();
                                    }
                                    childStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(childStream);
                                }

                                AltChunk altChunk = new AltChunk();
                                altChunk.Id = altChunkId;
                                mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>().Last());
                                mainPart.Document.Save();
                            }
                            mainWD.Close();
                        }
                    }
                    memStream.Seek(0, SeekOrigin.Begin);

                    return(memStream.ToArray());
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
            }
        }
Exemple #27
0
        public static byte[] GetOwnerVerification(OwnerVerificationReportModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      ownerCount = 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 (HetOwner owner in reportModel.Owners)
                        {
                            ownerCount++;

                            using (MemoryStream ownerStream = new MemoryStream())
                            {
                                WordprocessingDocument ownerDocument = (WordprocessingDocument)wordTemplate.Clone(ownerStream);
                                ownerDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", owner.Classification },
                                    { "districtAddress", reportModel.DistrictAddress },
                                    { "districtContact", reportModel.DistrictContact },
                                    { "organizationName", owner.OrganizationName },
                                    { "address1", owner.Address1 },
                                    { "address2", owner.Address2 },
                                    { "reportDate", reportModel.ReportDate },
                                    { "ownerCode", owner.OwnerCode },
                                    { "sharedKeyHeader", owner.SharedKeyHeader },
                                    { "sharedKey", owner.SharedKey },
                                    { "workPhoneNumber", owner.PrimaryContact.WorkPhoneNumber }
                                };

                                // update classification number first [ClassificationNumber]
                                owner.Classification = owner.Classification.Replace("&", "&amp;");
                                bool found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("ClassificationNumber"))
                                            {
                                                // replace text
                                                text.InnerXml = text.InnerXml.Replace("<w:t>ClassificationNumber</w:t>",
                                                                                      $"<w:t xml:space='preserve'>ORCS: {owner.Classification}</w:t>");

                                                found = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // update merge fields
                                MergeHelper.ConvertFieldCodes(ownerDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, ownerDocument.MainDocumentPart.Document);
                                ownerDocument.MainDocumentPart.Document.Save();

                                // setup table for equipment data
                                Table     equipmentTable = GenerateEquipmentTable(owner.HetEquipment);
                                Paragraph tableParagraph = null;
                                found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("Owner Equipment Table"))
                                            {
                                                // 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(equipmentTable);
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

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

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

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

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

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

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

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

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

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

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

                                    ownerDocument.Save();

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

                                    Paragraph         para      = new Paragraph();
                                    SectionProperties sectProp  = new SectionProperties();
                                    SectionType       secSbType = new SectionType()
                                    {
                                        Val = SectionMarkValues.OddPage
                                    };
                                    PageSize pageSize = new PageSize()
                                    {
                                        Width = 11900U, Height = 16840U, Orient = PageOrientationValues.Portrait
                                    };
                                    PageMargin pageMargin = new PageMargin()
                                    {
                                        Top = 2642, Right = 23U, Bottom = 278, Left = 23U, Header = 714, Footer = 0, Gutter = 0
                                    };

                                    // page numbering throws out the "odd page" section breaks
                                    //PageNumberType pageNum = new PageNumberType() {Start = 1};

                                    sectProp.AppendChild(secSbType);
                                    sectProp.AppendChild(pageSize);
                                    sectProp.AppendChild(pageMargin);
                                    //sectProp.AppendChild(pageNum);

                                    ParagraphProperties paragraphProperties = new ParagraphProperties(sectProp);
                                    para.AppendChild(paragraphProperties);

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

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

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

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();

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

                                    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 #28
0
        public void SaveDOCX(string fileName, string BodyText, bool isLandScape = false, double rMargin = 1, double lMargin = 1, double bMargin = 1, double tMargin = 1)
        {
            string destFile = Path.Combine(Path.Combine(_env.ContentRootPath, @"App_Data\Files"), "Clause Templat1_v1.0.0.5.docx");
            WordprocessingDocument document        = WordprocessingDocument.Create(destFile, WordprocessingDocumentType.Document);
            MainDocumentPart       mainDocumenPart = document.MainDocumentPart;

            //Place the HTML String into a MemoryStream Object
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(BodyText));

            //Assign an HTML Section for the String Text
            string htmlSectionID = "Sect1";

            // Create alternative format import part.
            AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);

            // Feed HTML data into format import part (chunk).
            formatImportPart.FeedData(ms);
            AltChunk altChunk = new AltChunk();

            altChunk.Id = htmlSectionID;

            //Clear out the Document Body and Insert just the HTML string.  (This prevents an empty First Line)
            mainDocumenPart.Document.Body.RemoveAllChildren();
            mainDocumenPart.Document.Body.Append(altChunk);

            /*
             * Set the Page Orientation and Margins Based on Page Size
             * inch equiv = 1440 (1 inch margin)
             */
            double width  = 8.5 * 1440;
            double height = 11 * 1440;

            SectionProperties sectionProps = new SectionProperties();
            PageSize          pageSize;

            if (isLandScape)
            {
                pageSize = new PageSize()
                {
                    Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape
                }
            }
            ;
            else
            {
                pageSize = new PageSize()
                {
                    Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait
                }
            };

            rMargin = rMargin * 1440;
            lMargin = lMargin * 1440;
            bMargin = bMargin * 1440;
            tMargin = tMargin * 1440;

            PageMargin pageMargin = new PageMargin()
            {
                Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U
            };

            sectionProps.Append(pageSize);
            sectionProps.Append(pageMargin);
            mainDocumenPart.Document.Body.Append(sectionProps);

            //Saving/Disposing of the created word Document
            document.MainDocumentPart.Document.Save();
            Stream stream = document.MainDocumentPart.GetStream();

            UploadFileToDatalake(stream, "Clause Templat1_v1.0.0.5.docx", 12, 13);
            document.Dispose();
        }
        /// <summary>
        /// Constructs a new instance of the class.
        /// </summary>
        /// <param name="mainPart">The template document's <see cref="MainDocumentPart"/></param>
        public SmartPPAMappedFieldSet(MainDocumentPart mainPart)
        {
            // PPA Fields start in table 1
            Table PPAFields = mainPart.Document.Body.Elements <Table>().ElementAt(0);

            PPA_EmployeeName     = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(0).Elements <TableCell>().ElementAt(1));
            PPA_PayrollId        = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(0).Elements <TableCell>().ElementAt(3));
            PPA_ClassTitle       = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(2).Elements <TableCell>().ElementAt(3));
            PPA_Grade            = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(2).Elements <TableCell>().ElementAt(4));
            PPA_PositionNumber   = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(2).Elements <TableCell>().ElementAt(5));
            PPA_StartDate        = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(2).Elements <TableCell>().ElementAt(0));
            PPA_EndDate          = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(2).Elements <TableCell>().ElementAt(2));
            PPA_DistrictDivision = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(4).Elements <TableCell>().ElementAt(3));
            PPA_AgencyActivity   = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(4).Elements <TableCell>().ElementAt(4));

            PPA_Categories = new List <SmartCategory>();
            Table PPACategories = mainPart.Document.Body.Elements <Table>().ElementAt(0);

            for (int i = 6; i < 12; i++)
            {
                PPA_Categories.Add(new SmartCategory(PPACategories.Elements <TableRow>().ElementAt(i)));
            }
            PPA_TotalRatingValue                  = new SmartParagraph(PPACategories.Elements <TableRow>().ElementAt(12).Elements <TableCell>().ElementAt(1));
            PPA_UnsatisfactoryRatingCheckBox      = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(13).Elements <TableCell>().ElementAt(1));
            PPA_NeedsImprovementRatingCheckBox    = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(13).Elements <TableCell>().ElementAt(3));
            PPA_SatisfactoryRatingCheckBox        = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(13).Elements <TableCell>().ElementAt(5));
            PPA_ExceedsSatisfactoryRatingCheckBox = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(13).Elements <TableCell>().ElementAt(7));
            PPA_OutstandingRatingCheckBox         = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(13).Elements <TableCell>().ElementAt(9));
            PPA_MeritApprovedCheckBox             = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(16).Elements <TableCell>().ElementAt(1));
            PPA_MeritNotApprovedCheckBox          = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(16).Elements <TableCell>().ElementAt(5));
            PPA_MeritNotApplicableCheckBox        = new SmartParagraph(PPAFields.Elements <TableRow>().ElementAt(16).Elements <TableCell>().ElementAt(3));

            // TODO: Consider adding Probationary Midpoint/Rating Justification?
            Table PAFFields = mainPart.Document.Body.Elements <Table>().ElementAt(1);

            PAF_EmployeeName     = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(5).Elements <TableCell>().ElementAt(1));
            PAF_PayrollId        = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(6).Elements <TableCell>().ElementAt(1));
            PAF_StartDate        = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(7).Elements <TableCell>().ElementAt(1));
            PAF_EndDate          = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(7).Elements <TableCell>().ElementAt(3));
            PAF_ClassGrade       = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(9).Elements <TableCell>().ElementAt(1));
            PAF_DistrictDivision = new SmartParagraph(PAFFields.Elements <TableRow>().ElementAt(8).Elements <TableCell>().ElementAt(1));

            PAF_Assessment            = new SmartParagraph(mainPart.Document.Body.Elements <Table>().ElementAt(2).Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(0));
            PAF_Assessment_Chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, "assessmentChunk");
            PAF_Recommendations       = new SmartParagraph(mainPart.Document.Body.Elements <Table>().ElementAt(3).Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(0));
            PAF_Recommendations_Chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, "recommendationsChunk");

            Table JOBFields = mainPart.Document.Body.Elements <Table>().ElementAt(4);

            JOB_EmployeeName     = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(3).Elements <TableCell>().ElementAt(0));
            JOB_DistrictDivision = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(2));
            JOB_AgencyActivity   = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(3));
            JOB_PositionNumber   = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(1).Elements <TableCell>().ElementAt(4));
            JOB_ClassTitle       = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(3).Elements <TableCell>().ElementAt(1));
            JOB_Grade            = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(3).Elements <TableCell>().ElementAt(2));
            JOB_WorkingTitle     = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(5).Elements <TableCell>().ElementAt(1));
            JOB_WorkAddress      = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(7).Elements <TableCell>().ElementAt(0));
            JOB_WorkingHours     = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(7).Elements <TableCell>().ElementAt(1));
            JOB_Supervisor       = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(9).Elements <TableCell>().ElementAt(0));
            JOB_Supervises       = new SmartParagraph(JOBFields.Elements <TableRow>().ElementAt(11).Elements <TableCell>().ElementAt(0));
            JobDescriptionTable  = mainPart.Document.Body.Elements <Table>().ElementAt(5);
        }