コード例 #1
0
ファイル: FindBookMarks.cs プロジェクト: jlovenpk1/FreeDocs
        string pathFolder = "";           // путь к файлу

        /// <summary>
        /// Начать работу с документом шаблоном
        /// </summary>
        /// <param name="type">тип документа</param>
        /// <param name="name">имя документа</param>
        public void Run(string type, string name)
        {
            _bookMarks = new List <string>();
            switch (type)
            {
            case TypeDocs._act:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._act + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._act + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;

            case TypeDocs._agreement:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._agreement + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._agreement + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;

            case TypeDocs._blank:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._blank + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._blank + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;

            case TypeDocs._reference:
                pathFile   = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._reference + "\\" + name;
                pathFolder = AppDomain.CurrentDomain.BaseDirectory + FolderName._document + "\\" + FolderName._reference + "\\" + DateTime.Now.ToString("dd-MM-yy-hh-mm-ss");
                break;
            }
            Directory.CreateDirectory(pathFolder);
            File.Copy(pathFile, Path.Combine(pathFolder, name));
            pathFolder += "\\" + name;
            _document   = WordprocessingDocument.Open(pathFolder, true);
            _body       = _document.MainDocumentPart.Document.Body;
            FindMarks(_body);
            WorkWithText(_body);
            _document.Save();
            _document.Dispose();
        }
コード例 #2
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                WordprocessingDocument doc = Word.CreateWordFile("Prova", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Prova.docx");
                string[][]             c   = new string[4][];
                for (int i = 0; i < c.Length; i++)
                {
                    c[i] = new string[5];
                    for (int j = 0; j < c[i].Length; j++)
                    {
                        c[i][j] = i + "-" + j;
                    }
                }
                doc.MainDocumentPart.Document.GetFirstChild <Body>().AppendChild(Word.CreateTable(c));
                doc.MainDocumentPart.Document.GetFirstChild <Body>().AppendChild(Word.CreateParagraph("È universalmente riconosciuto che un lettore che osserva il layout di una pagina viene distratto dal contenuto testuale se questo è leggibile. Lo scopo dell’utilizzo del Lorem Ipsum è che offre una normale distribuzione delle lettere (al contrario di quanto avviene se si utilizzano brevi frasi ripetute, ad esempio “testo qui”), apparendo come un normale blocco di testo leggibile. Molti software di impaginazione e di web design utilizzano Lorem Ipsum come testo modello. Molte versioni del testo sono state prodotte negli anni, a volte casualmente, a volte di proposito (ad esempio inserendo passaggi ironici)."));

                MessageBox.Show("Il documento è pronto!");
                doc.Dispose();
                Process.Start(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Prova.docx"));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problemi col documento. Se è aperto da un altro programma, chiudilo e riprova... \n" + ex.Message);
            }
        }
コード例 #3
0
 public void Dispose()
 {
     if (wdDoc != null)
     {
         wdDoc.Dispose();
     }
 }
コード例 #4
0
 public void Dispose()
 {
     if (_wordDocument != null)
     {
         _wordDocument.Dispose();
     }
 }
コード例 #5
0
 public void Dispose()
 {
     if (_package != null)
     {
         _package.Dispose();
     }
 }
コード例 #6
0
        public static void InsertImages(string fullPathToDocument, List <KeyValuePair <string, List <string> > > pictures)
        {
            WordprocessingDocument wordDoc = WordprocessingDocument.Open(fullPathToDocument, true);
            string currentHeader           = "";

            foreach (var keyValuePair in pictures)
            {
                if (currentHeader != keyValuePair.Key)
                {
                    if (currentHeader != "")
                    {
                        SectionProperties sectPr = (SectionProperties)wordDoc.MainDocumentPart.Document.Body.ChildElements.Last();

                        wordDoc.MainDocumentPart.Document.Body.InsertBefore(
                            new Paragraph(
                                new Run(
                                    new Break()
                        {
                            Type = BreakValues.Page
                        }
                                    )),
                            sectPr
                            );
                    }
                    InsertHeader(keyValuePair.Key, wordDoc, currentHeader);
                }

                currentHeader = keyValuePair.Key;
                InsertPicture(keyValuePair.Value, wordDoc);
            }

            wordDoc.Save();
            wordDoc.Close();
            wordDoc.Dispose();
        }
コード例 #7
0
ファイル: OpenXmlHelper.cs プロジェクト: IreneGigabit/Nbrp
    /// <summary>
    /// 關閉
    /// </summary>
    public void Dispose()
    {
        if (this.outDoc != null)
        {
            outDoc.Dispose();
        }
        if (this.outMem != null)
        {
            outMem.Close();
        }

        foreach (var item in tplDoc)
        {
            item.Value.Dispose();
        }
        foreach (var item in tplMem)
        {
            item.Value.Close();
            item.Value.Dispose();
        }
        //微軟KB 312629https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end--response-redi
        //Response.End、Server.Transfer、Response.Redirect被呼叫時,會觸發ThreadAbortException,因此要改用CompleteRequest()
        //HttpContext.Current.Response.End();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
コード例 #8
0
 public void Dispose()
 {
     if (_wordDocx != null)
     {
         _wordDocx.Save();
         _wordDocx.Dispose();
     }
 }
コード例 #9
0
 /// <summary>
 /// Dispose of document object.
 /// </summary>
 private void CloseAndDisposeOfDocument()
 {
     if (_document != null)
     {
         _document.Close();
         _document.Dispose();
         _document = null;
     }
 }
コード例 #10
0
        public void Dispose()
        {
            if (_wordDocument == null)
            {
                return;
            }

            _wordDocument.Dispose();
        }
コード例 #11
0
ファイル: MSDocFilter.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Close the document.
        /// </summary>
        private void CloseDocument()
        {
            if (_document != null)
            {
                _document.Dispose();
            }

            _document  = null;
            _xDocument = null;
        }
コード例 #12
0
        private static void cloneStreamDoc()
        {
            templateFile = CurrDir + @"\01發明專利申請書_img.docx";

            byte[]       tempArray = File.ReadAllBytes(templateFile);
            byte[]       outArray  = File.ReadAllBytes(templateFile);
            MemoryStream tempMem   = new MemoryStream();

            tempMem.Write(tempArray, 0, (int)tempArray.Length);

            MemoryStream outMem = new MemoryStream();

            outMem.Write(outArray, 0, (int)outArray.Length);

            WordprocessingDocument tempDoc = WordprocessingDocument.Open(tempMem, false);
            WordprocessingDocument outDoc  = WordprocessingDocument.Open(outMem, true);

            try {
                //using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(tempMem, true)) {
                //using (WordprocessingDocument outDoc = WordprocessingDocument.Open(outMem, true)) {
                Body body = outDoc.MainDocumentPart.Document.Body;
                SectionProperties[] foot = outDoc.MainDocumentPart.RootElement.Descendants <SectionProperties>().ToArray();

                body.RemoveAllChildren <SdtElement>();
                body.RemoveAllChildren <Paragraph>();
                body.RemoveAllChildren <SectionProperties>();

                body.Append(copyTag2(tempDoc, "b_title"));
                copyTag3(tempDoc, outDoc, "b_apply");
                PasteBookmarkText(outDoc.MainDocumentPart, "reality", "是");
                PasteBookmarkText(outDoc.MainDocumentPart, "seq", "NT66824(20180111)");
                PasteBookmarkText(outDoc.MainDocumentPart, "cappl_name", "FE9測試");
                PasteBookmarkText(outDoc.MainDocumentPart, "eappl_name", "colors test");
                body.AppendChild(new Paragraph(GenerateImageRun(outDoc, new ImageFile(imgFile))));
                copyTag5(tempDoc, outDoc, "b_table");

                outDoc.MainDocumentPart.Document.Body.InsertAt(new Paragraph(new Run(new Text("Newly inserted paragraph."))), 0);
                //}
                //}
                outDoc.MainDocumentPart.Document.Save();
                outDoc.Close();

                using (FileStream fileStream = new FileStream(outputFile, FileMode.Create)) {
                    outMem.Position = 0;
                    outMem.WriteTo(fileStream);
                }
            }
            finally {
                //if (outDoc.Dispose()!=null) outDoc.Close();
                outDoc.Dispose();
                tempDoc.Close();
                outMem.Close();
                tempMem.Close();
            }
        }
コード例 #13
0
 public void Dispose()
 {
     if (cWordprocessing == null)
     {
         return;
     }
     cWordprocessing.MainDocumentPart?.Document?.Save();
     cWordprocessing.Close();
     cWordprocessing.Dispose();
     cWordprocessing = null;
 }
コード例 #14
0
ファイル: ModelProcessor.cs プロジェクト: JabX/kinetix
 /// <summary>
 /// Libère les ressources.
 /// </summary>
 /// <param name="disposing">Dispose.</param>
 public void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_document != null)
         {
             _contextDocumentParams.Remove(_document.ToString());
             _document.Dispose();
         }
     }
 }
コード例 #15
0
        }//NASCONDO E MOSTRO IL BOTTONE PER CHIUDERE LA TAB

        private void ExportToWordDocument_Click(object sender, EventArgs e)
        {
            try
            {
                Word   w    = new Word();
                string s    = string.Join(" ", search);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Volantino" + (this.Tb.SelectedTab == tRicerca && this.results != null ? " " + s : "") + ".docx";
                WordprocessingDocument doc = w.CreateWordFile("SALONE VENDITA VEICOLI NUOVI E USATI", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Volantino " + (this.Tb.SelectedTab == tRicerca && this.results != null ? s : "") + ".docx"));

                var  mainPart = doc.MainDocumentPart.Document;
                Body body     = mainPart.GetFirstChild <Body>();

                if (this.Tb.SelectedTab == tRicerca && this.results != null)
                {
                    body.AppendChild(w.CreateParagraph($"Ricerca basata su: \"{s}\""));
                }// SE SI PREME IL BOTTONE DI ESPORTAZIONE SULLA PAGINA DEI RISULTATI DI UNA RICERCA, VERRANNO ESPORATI QUEI RISULTATI
                string[][] contenuto;
                if (this.Tb.SelectedTab == tRicerca && this.results != null)
                {
                    contenuto = new string[this.results.Count][];
                    for (int i = 0; i < this.results.Count; i++)
                    {
                        contenuto[i]    = new string[4];
                        contenuto[i][0] = this.results[i].Marca + " " + this.results[i].Modello;
                        contenuto[i][1] = this.results[i].Prezzo.ToString("C");
                        contenuto[i][2] = this.results[i].Stato;
                        contenuto[i][3] = "";
                    }
                }
                else
                {
                    contenuto = new string[listaVeicoli.Count][];
                    for (int i = 0; i < listaVeicoli.Count; i++)
                    {
                        contenuto[i]    = new string[4];
                        contenuto[i][0] = listaVeicoli[i].Marca + " " + listaVeicoli[i].Modello;
                        contenuto[i][1] = listaVeicoli[i].Prezzo.ToString("C");
                        contenuto[i][2] = listaVeicoli[i].Stato;
                        contenuto[i][3] = "";
                    }
                }
                // Append a table
                body.Append(w.CreateTable(contenuto));
                doc.Close();
                doc.Dispose();
                MessageBox.Show("Il documento è pronto!");
                //Process.Start(path);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Problemi col documento. Se è aperto da un altro programma, chiudilo e riprova..." + ex.Message, "Errore", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }//ESPORTA I DATI DEI VEICOLI CREANDO UN DOCUMENTO WORD
コード例 #16
0
        public void Save()
        {
            SaveNumberDefinitions();

            Document.Save();

            document.Close();
            document.Dispose();

            document = null;
            mainPart = null;
        }
コード例 #17
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _document?.Dispose();
                }

                disposedValue = true;
            }
        }
コード例 #18
0
ファイル: Md2MlCore.cs プロジェクト: ashok19r91d/md2ml
 private bool disposedValue = false;         // To detect redundant calls
 protected virtual void Dispose(bool disposing)
 {
     SaveDocument();
     if (!disposedValue)
     {
         if (disposing)
         {
             package.Dispose();
         }
         package       = null;
         disposedValue = true;
     }
 }
コード例 #19
0
ファイル: WordEdit.cs プロジェクト: fialot/CardGenIDE
 /// <summary>
 /// Close and Save .docx file
 /// </summary>
 public void Close()
 {
     if (Paragraphs != null)
     {
         Paragraphs.Clear();
     }
     if (doc != null)
     {
         doc.Close();
         doc.Dispose();
         doc = null;
     }
     isOpen = false;
 }
コード例 #20
0
        public static void SearchAndReplace(string fullPathToDocument, SortedDictionary <string, string> valuesToReplace, string outputFileName)
        {
            File.Copy(fullPathToDocument, outputFileName);

            WordprocessingDocument wordDoc = WordprocessingDocument.Open(outputFileName, true);

            SearchAndReplaceHeaders(wordDoc, valuesToReplace);

            SearchAndReplaceBody(wordDoc, valuesToReplace);

            SearchAndReplaceFooters(wordDoc, valuesToReplace);

            wordDoc.Save();
            wordDoc.Close();
            wordDoc.Dispose();
        }
コード例 #21
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_wordprocessingDocument != null)
                {
                    _wordprocessingDocument.Dispose();
                }
            }
            _disposed = true;
        }
コード例 #22
0
        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                WordDocument.Dispose();
                // Free any other managed objects here.
                //
            }

            disposed = true;
        }
コード例 #23
0
        private static bool DocumentStylesAreEqual(FileInfo expectedOutputWordFile, FileInfo actualOutputWordFile)
        {
            WordprocessingDocument doc1 = WordprocessingDocument.Open(expectedOutputWordFile.FullName, false);
            WordprocessingDocument doc2 = WordprocessingDocument.Open(actualOutputWordFile.FullName, false);

            XDocument expectedDocumentStyles = doc1.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
            XDocument actualDocumentStyles   = doc2.MainDocumentPart.StyleDefinitionsPart.GetXDocument();

            var outputCompareHtmlFile =
                new FileInfo(Path.Combine(actualOutputWordFile.Directory.FullName,
                                          Path.GetFileNameWithoutExtension(actualOutputWordFile.FullName) + "_StylePart", actualOutputWordFile.Name + ".html"));

            doc1.Dispose();
            doc2.Dispose();

            return(ComparingElementsAreEqual(expectedDocumentStyles.CreateReader(), actualDocumentStyles.CreateReader(), outputCompareHtmlFile));
        }
コード例 #24
0
            protected virtual void Dispose(bool disposing)
            {
                // Protect from being called multiple times.
                if (_disposed)
                {
                    return;
                }

                if (disposing)
                {
                    if (_package != null)
                    {
                        _package.Dispose();
                    }
                }
                _disposed = true;
            }
コード例 #25
0
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                    inputFs.Dispose();
                    doc.Dispose();
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }
コード例 #26
0
        public ActionResult LettersFiles()
        {
            var    result   = new List <ChartViewModel>();
            string pathName = Server.MapPath(@"../SpecialData/HrLetters");
            string ListPath = Server.MapPath("/App_Data/ContractsList.mdb");

            if (User.Identity.RTL())
            {
                ListPath = Server.MapPath("/App_Data/arContractsList.mdb");
            }
            if (Directory.Exists(pathName))
            {
                var Files = Directory.GetFiles(pathName);
                foreach (var item in Files)
                {
                    FileInfo fl = new FileInfo(item);
                    using (WordprocessingDocument docPKG = WordprocessingDocument.Open(item, true))
                    {
                        MailMerge mymerge = docPKG.MainDocumentPart.DocumentSettingsPart.Settings.Elements <MailMerge>().FirstOrDefault();
                        if (mymerge != null)
                        {
                            mymerge.ConnectString = new ConnectString()
                            {
                                Val = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" + ListPath + ";Mode=Read;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Engine Type=6;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False"
                            };

                            var Relation = docPKG.MainDocumentPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource", new Uri(ListPath));
                            mymerge.DataSourceReference = new DataSourceReference()
                            {
                                Id = Relation.Id
                            };
                        }
                        docPKG.Save();
                        docPKG.Dispose();
                    }
                    var f = new ChartViewModel()
                    {
                        category = fl.Name,
                        color    = "/SpecialData/HrLetters/" + fl.Name
                    };
                    result.Add(f);
                }
            }
            return(PartialView("_ContractFiles", result));
        }
コード例 #27
0
        public async Task <string> GetDocument(string siteName, string docLibraryName, string id)
        {
            List <Option> options = new List <Option>();

            options.Add(new QueryOption("search", siteName));

            Site site = (await _graphServiceClient.Sites.Request(options).GetAsync()).First();

            Drive docLibrary = (await(_graphServiceClient.Sites[site.Id].Drives.Request().GetAsync())).Where(x => x.Name == docLibraryName).First();

            IEnumerable <DriveItem> documentsList = await _graphServiceClient.Sites[site.Id].Drives[docLibrary.Id].Root.Children.Request().GetAsync();

            foreach (DriveItem document in documentsList)
            {
                Microsoft.Graph.ListItem item = await _graphServiceClient.Sites[site.Id].Drives[docLibrary.Id].Items[document.Id].ListItem.Request().GetAsync();
                if (item.Id == id)
                {
                    if ((document.File.MimeType.ToLower() == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") || (document.File.MimeType.ToLower() == "application / msword"))
                    {
                        using (Stream stream = await _graphServiceClient.Sites[site.Id].Drives[docLibrary.Id].Items[document.Id].Content.Request().GetAsync())
                        {
                            WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, false);
                            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                            wordprocessingDocument.Close();
                            wordprocessingDocument.Dispose();
                            return(body.InnerText);
                        }
                    }

                    if (document.File.MimeType.ToLower() == "application/pdf")
                    {
                        using (Stream stream = await _graphServiceClient.Sites[site.Id].Drives[docLibrary.Id].Items[document.Id].Content.Request().GetAsync())
                        {
                            PdfReader _reader = new PdfReader(stream);
                            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                            string currentText = PdfTextExtractor.GetTextFromPage(_reader, 1, strategy);
                            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                            return(currentText);
                        }
                    }
                }
            }
            return("Lo siento, no he encontrado el documento que buscas.");
        }
コード例 #28
0
        public async Task <List <string> > GetDocument()
        {
            try
            {
                List <string> data    = new List <string>();
                List <Option> options = new List <Option>();

                options.Add(new QueryOption("search", "devsite"));

                Site site = (await _graphServiceClient.Sites.Request(options).GetAsync()).First();

                Drive docContratos = (await(_graphServiceClient.Sites[site.Id].Drives.Request().GetAsync())).Where(x => x.Name == "Contratos").First();

                IEnumerable <DriveItem> contratos = await _graphServiceClient.Sites[site.Id].Drives[docContratos.Id].Root.Children.Request().GetAsync();

                foreach (DriveItem driveItem in contratos)
                {
                    if ((driveItem.File.MimeType.ToLower() == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") || (driveItem.File.MimeType.ToLower() == "application / msword"))
                    {
                        Stream stream = await _graphServiceClient.Sites[site.Id].Drives[docContratos.Id].Items[driveItem.Id].Content.Request().GetAsync();
                        WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, false);
                        Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                        wordprocessingDocument.Close();
                        wordprocessingDocument.Dispose();
                        data.Add(body.InnerText);
                    }
                    if (driveItem.File.MimeType.ToLower() == "application/pdf")
                    {
                        Stream    stream  = await _graphServiceClient.Sites[site.Id].Drives[docContratos.Id].Items[driveItem.Id].Content.Request().GetAsync();
                        PdfReader _reader = new PdfReader(stream);
                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                        string currentText = PdfTextExtractor.GetTextFromPage(_reader, 1, strategy);
                        currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                        data.Add(currentText);
                    }
                }
                return(data);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #29
0
        protected virtual void Dispose(bool disposing)
        {
            // Protect from being called multiple times.
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                // Clean up all managed resources.
                if (package != null)
                {
                    package.Dispose();
                }
            }

            disposed = true;
        }
コード例 #30
0
        public static void InsertSignature(string fullPathToDocument, List <KeyValuePair <string, string> > pictures)
        {
            WordprocessingDocument wordDoc = WordprocessingDocument.Open(fullPathToDocument, true);

            foreach (var keyValuePair in pictures)
            {
                MainDocumentPart mainPart  = wordDoc.MainDocumentPart;
                ImagePart        imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                long iWidth  = 0;
                long iHeight = 0;
                using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(keyValuePair.Value))
                {
                    iWidth  = bmp.Width;
                    iHeight = bmp.Height;
                }

                iWidth  = (long)Math.Round((decimal)iWidth * 9525);
                iHeight = (long)Math.Round((decimal)iHeight * 9525);

                double    maxWidthCm   = 16.5;
                const int emusPerCm    = 360000;
                long      maxWidthEmus = (long)(maxWidthCm * emusPerCm);
                if (iWidth > maxWidthEmus)
                {
                    var ratio = (iHeight * 1.0m) / iWidth;
                    iWidth  = maxWidthEmus;
                    iHeight = (long)(iWidth * ratio);
                }


                using (FileStream stream = new FileStream(keyValuePair.Value, FileMode.Open)) {
                    imagePart.FeedData(stream);
                }

                AddSignatureToParagraph(wordDoc, mainPart.GetIdOfPart(imagePart), iWidth, iHeight, keyValuePair.Key);
            }

            wordDoc.Save();
            wordDoc.Close();
            wordDoc.Dispose();
        }
コード例 #31
0
        public void Create(HtmlParser parser, Calculator calculator)
        {
            // Создание Wordprocessing документа
            try
            {
                myDoc =
                   WordprocessingDocument.Create(MainWindow.Folder + Path.DirectorySeparatorChar + parser.ResultDirName + Path.DirectorySeparatorChar + parser.ResultFileNameWordTable,
                                 WordprocessingDocumentType.Document);
            }
            catch
            {
                // Укорачивание наименование файла в 2 раза, если превышает допустимое кол-во символов
                int halfLenghtWordFile = parser.ResultFileNameWordTable.Length / 2;
                string tmpWordStr = parser.ResultFileNameWordTable.Substring(0, halfLenghtWordFile);

                myDoc =
                   WordprocessingDocument.Create(MainWindow.Folder + Path.DirectorySeparatorChar + parser.ResultDirName + Path.DirectorySeparatorChar + tmpWordStr + ".docx",
                                 WordprocessingDocumentType.Document);
            }

            // Добавление главной части документа
            MainDocumentPart mainPart = myDoc.AddMainDocumentPart();

            // Создание дерева DOM для простого документа
            mainPart.Document = new Document();
            Body body = new Body();
            Table table = new Table();
            TableProperties tblPr = new TableProperties();
            TableBorders tblBorders = new TableBorders();
            tblBorders.TopBorder = new TopBorder();
            tblBorders.TopBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
            tblBorders.BottomBorder = new BottomBorder();
            tblBorders.BottomBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
            tblBorders.LeftBorder = new LeftBorder();
            tblBorders.LeftBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
            tblBorders.RightBorder = new RightBorder();
            tblBorders.RightBorder.Val = new EnumValue<BorderValues>(BorderValues.Single);
            tblBorders.InsideHorizontalBorder = new InsideHorizontalBorder();
            tblBorders.InsideHorizontalBorder.Val = BorderValues.Single;
            tblBorders.InsideVerticalBorder = new InsideVerticalBorder();
            tblBorders.InsideVerticalBorder.Val = BorderValues.Single;
            tblPr.Append(tblBorders);
            table.Append(tblPr);
            // Первый ряд с наименованием файла
            TableRow tr;
            TableCell tc;
            tr = new TableRow();
            tc = new TableCell(new Paragraph(new Run(
                               new Text(parser.ResultFileNameWordTable.Replace(".docx", "")))));
            TableCellProperties tcp = new TableCellProperties();
            GridSpan gridSpan = new GridSpan();
            gridSpan.Val = 5;
            tcp.Append(gridSpan);
            tc.Append(tcp);
            tr.Append(tc);
            table.Append(tr);
            // Последующие ряды
            tr = new TableRow();
            tc = new TableCell();
            for (int i = 1; i <= 5; i++)
            {
                switch (i)
                {
                    case 1:
                        tr.Append(new TableCell(new Paragraph(new Run(new Text("№")))));
                        break;
                    case 2:
                        tr.Append(new TableCell(new Paragraph(new Run(new Text("Показатель")))));
                        break;
                    case 3:
                        tr.Append(new TableCell(new Paragraph(new Run(new Text("Взвешенная оценка")))));
                        break;
                    case 4:
                        tr.Append(new TableCell(new Paragraph(new Run(new Text("Оценка")))));
                        break;
                    case 5:
                        tr.Append(new TableCell(new Paragraph(new Run(new Text("Вес показателя")))));
                        break;
                }
            }
            table.Append(tr);
            int tmpInt = 1;
            for (int i = 1; i <= 9; i++)
            {
                tr = new TableRow();
                if (i <= 7)
                {
                    tc = new TableCell(new Paragraph(new Run(new Text(i.ToString()))));
                }
                else
                {
                    tc = new TableCell(new Paragraph(new Run(new Text(""))));
                }
                tr.Append(tc);
                for (int j = 1; j <= 4; j++)
                {
                    switch (tmpInt)
                    {
                        case 1:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Изменение выручки")))));
                            break;
                        case 2:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogIzmeneniyaViruchki.ToString())))));
                            break;
                        case 3:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogIzmeneniyaViruchki.ToString())))));
                            break;
                        case 4:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2")))));
                            break;
                        case 5:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Коэффициент текущей ликвидности")))));
                            break;
                        case 6:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogKoeficientaTekucsheyLikvidnosti.ToString())))));
                            break;
                        case 7:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogKoeficientaTekucsheyLikvidnosti.ToString())))));
                            break;
                        case 8:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2")))));
                            break;
                        case 9:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Коэффициент финансовой независимости")))));
                            break;
                        case 10:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogKoeficientaFinNezavisimosti.ToString())))));
                            break;
                        case 11:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogKoeficientaFinNezavisimosti.ToString())))));
                            break;
                        case 12:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2")))));
                            break;
                        case 13:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Чистые активы")))));
                            break;
                        case 14:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogChistihActivov.ToString())))));
                            break;
                        case 15:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogChistihActivov.ToString())))));
                            break;
                        case 16:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,2")))));
                            break;
                        case 17:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Рентабельность продаж")))));
                            break;
                        case 18:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogRentabelnostiProdag.ToString())))));
                            break;
                        case 19:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogRentabelnostiProdag.ToString())))));
                            break;
                        case 20:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,05")))));
                            break;
                        case 21:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Рентабельность деятельности")))));
                            break;
                        case 22:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.VzvesheniyItogRentabelnostiDeyatelnosti.ToString())))));
                            break;
                        case 23:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text(calculator.ItogRentabelnostiDeyatelnosti.ToString())))));
                            break;
                        case 24:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,15")))));
                            break;
                        case 25:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Коэффициент оборачиваемости (динамика)")))));
                            break;
                        case 26:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text()))));
                            break;
                        case 27:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text()))));
                            break;
                        case 28:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("0,1")))));
                            break;
                        case 29:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Итого: ")))));
                            break;
                        case 30:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text()))));
                            break;
                        case 31:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text()))));
                            break;
                        case 32:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text()))));
                            break;
                        case 33:
                            tr.Append(new TableCell(new Paragraph(new Run(new Text("Оценка финансового положения заемщика")))));
                            break;
                        case 34:
                            tc = new TableCell(new Paragraph(new Run(
                               new Text(""))));
                            tcp = new TableCellProperties();
                            gridSpan = new GridSpan();
                            gridSpan.Val = 3;
                            tcp.Append(gridSpan);
                            tc.Append(tcp);
                            tr.Append(tc);
                            break;
                    }

                    tmpInt++;
                }
                table.Append(tr);
            }
            // Добавления таблицы к основе
            body.Append(table);
            // Добавление основы к документу
            mainPart.Document.Append(body);
            // Сохрание изменений главной части документа
            mainPart.Document.Save();
            myDoc.Dispose();
        }