public override string ConvertToString(string path)
        {
            Spire.Doc.Document doc  = null;
            string             text = null;

            try
            {
                doc = new Spire.Doc.Document();
                doc.LoadFromFile(path);
                try
                {
                    doc.Sections[0].HeadersFooters.Header.ChildObjects.Clear();
                    doc.Sections[0].HeadersFooters.Footer.ChildObjects.Clear();
                }
                catch
                { }
                text = doc.GetText();
                text = text.Replace("#", "").Replace('\r', '#').Replace('\n', '#');
                text = Regex.Replace(text, @"[^\u4e00-\u9fa5\《\》\(\)\——\;\,\。\“\”\!\#]", "");
                text = new Regex("[#]+").Replace(text, "@@").Trim();
                text = TextFormat(text);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();
                }
            }
            return(text);
        }
        private static void method2(string filename, string printer)
        {
            Spire.Doc.Document doc = new Spire.Doc.Document();

            doc.LoadFromFile(filename);

            System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;

            //get the page size
            SizeF sf = doc.Sections[0].PageSetup.PageSize;
            float wd = sf.Width;
            float ht = sf.Height;
            float a  = (S.PageSize.A4.Height - wd) / 2;
            float b  = (S.PageSize.A4.Width - ht) / 2;


            //set printing margins
            printDoc.OriginAtMargins = true;
            //printDoc.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins((int)(a), (int)(a), (int)(b), (int)(b));
            printDoc.PrinterSettings.PrinterName   = printer;
            printDoc.PrinterSettings.Duplex        = Duplex.Horizontal;
            printDoc.DefaultPageSettings.PaperSize = new PaperSize("postcard", 600, 400);
            printDoc.PrintController = new StandardPrintController();
            printDoc.Print();
        }
示例#3
0
        private void DOCX()
        {
            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(sciezkaDoPliku);
            Image wynik = document.SaveToImages(0, Spire.Doc.Documents.ImageType.Metafile);

            Image[] images = document.SaveToImages(Spire.Doc.Documents.ImageType.Metafile);
            int     pom    = 0;

            for (int i = 1; i < images.Count(); i++)
            {
                try
                {
                    if (i != 73)
                    {
                        wynik = MergeTwoImages(wynik, images[i]);
                        images[i].Dispose();
                    }
                    else
                    {
                        wynik.Save(sciezgaDoZapisaniaPliku /*+"_"+ pom */ + ".jpg");
                        wynik.Dispose();
                        wynik = document.SaveToImages(i, Spire.Doc.Documents.ImageType.Metafile);
                        pom++;
                    }
                }
                catch (Exception)
                {
                }
            }
            wynik.Save(sciezgaDoZapisaniaPliku + "_" + document.Count + ".jpg");
            wynik.Dispose();
            document.Dispose();
        }
        private static void method1(string filename, string printer)
        {
            Spire.Doc.Document doc = new Spire.Doc.Document();

            //Load word document
            doc.LoadFromFile(filename);

            //Printing with Custom paper
            SizeF sf = doc.Sections[0].PageSetup.PageSize;

            float wd = sf.Width;
            float ht = sf.Height;

            System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;
            printDoc.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("custom", (int)wd / 72 * 100, (int)ht / 72 * 100);

            doc.PrintDocument.PrinterSettings.PrinterName = printer;

            if (doc.PrintDocument.PrinterSettings.CanDuplex)
            {
                //Setting Horizontal printing ;
                doc.PrintDocument.PrinterSettings.Duplex = Duplex.Horizontal;
            }

            System.Drawing.Printing.PrintController printController = new System.Drawing.Printing.StandardPrintController();
            printDoc.PrintController = printController;
            printDoc.Print();
        }
示例#5
0
        public byte[] CreateWordDocument2()
        {
            //创建一个Document实例并添加section
            Spire.Doc.Document doc     = new Spire.Doc.Document();
            Spire.Doc.Section  section = doc.AddSection();

            //添加指向网址的超链接
            Spire.Doc.Documents.Paragraph para1 = section.AddParagraph();
            para1.AppendHyperlink("www.baidu.com", "www.baidu.com",
                                  Spire.Doc.Documents.HyperlinkType.WebLink);

            //添加指向邮件地址的超链接
            Spire.Doc.Documents.Paragraph para2 = section.AddParagraph();
            para2.AppendHyperlink("mailto:[email protected]", "mailto:[email protected]",
                                  Spire.Doc.Documents.HyperlinkType.EMailLink);


            //设置段落之间的间距
            para1.Format.AfterSpacing = 15f;
            para2.Format.AfterSpacing = 15f;

            MemoryStream memoryStream = new MemoryStream();

            StreamWriter wr = new StreamWriter(memoryStream);


            //保存文档
            doc.SaveToStream(memoryStream, Spire.Doc.FileFormat.Docx2013);

            return(memoryStream.ToArray());
        }
示例#6
0
文件: Utils.cs 项目: iamHXQ/Oy
        /// <summary>
        /// 查找替换文本
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="strOld">查找文本</param>
        /// <param name="strNew">替换文本</param>
        public void WordReplace(string[] strOld, string[] strNew)
        {
            string[] SampleFilePaths = { @".\Resources\外封面.docx", @".\Resources\报告书.docx", @".\Resources\委托书.docx", @".\Resources\管理表.docx", @".\Resources\流程单.docx" };
            string   ProjectName     = NamedObjectDictionary.ReadFromNOD(lib.AppConfig.ProjectInfoName[1]);
            string   FolderPath      = Interaction.GetFolderPath();

            if (strOld.Length == strNew.Length)
            {
                using (Spire.Doc.Document doc = new Spire.Doc.Document())
                {
                    foreach (string SampleFilePath in SampleFilePaths)
                    {
                        string filename     = System.IO.Path.GetFileNameWithoutExtension(SampleFilePath) + "-" + ProjectName; //获取文件名
                        string extension    = System.IO.Path.GetExtension(SampleFilePath);                                    //获取扩展名
                        string saveFilePath = FolderPath + @"\" + filename + extension;                                       //合并成完整路径

                        doc.LoadFromFile(SampleFilePath);
                        for (int i = 0; i < strOld.Length; i++)
                        {
                            doc.Replace("[<" + strOld[i] + ">]", strNew[i], false, false);
                        }
                        if (saveFilePath != null)
                        {
                            doc.SaveToFile(saveFilePath);
                            doc.Close();
                        }
                    }
                }
            }
            else
            {
                Forms.MessageBox.Show("要替换的新旧字符串数量不同,取消操作");
            }
        }
示例#7
0
        public static string DOCToDOCX(string filepath)
        {
            string outputfilepath = string.Empty;

            /*
             * XWPFDocument doc = null;
             *
             * FileInfo fi = new FileInfo(filepath);
             * if (fi.Exists)
             * {
             *  using (FileStream fs = new FileStream(fi.FullName, FileMode.Open))
             *  {
             *      doc = new XWPFDocument(fs);
             *      outputfilepath = fi.FullName.Replace(fi.Extension, ".docx");
             *      FileStream out1 = new FileStream(outputfilepath, FileMode.Create);
             *      doc.Write(out1);
             *      out1.Close();
             *  }
             * }*/
            FileInfo fi = new FileInfo(filepath);

            if (fi.Exists)
            {
                Spire.Doc.Document doc = new Spire.Doc.Document();
                doc.LoadFromFile(fi.FullName);
                outputfilepath = fi.FullName.Replace(fi.Extension, ".docx");
                doc.SaveToFile(outputfilepath, Spire.Doc.FileFormat.Docx);
            }
            return(outputfilepath);
        }
示例#8
0
        public override string ConvertToString(string path, string blockText)
        {
            Spire.Doc.Document doc  = null;
            string             text = null;

            try
            {
                doc = new Spire.Doc.Document();
                doc.LoadFromFile(path);
                try
                {
                    doc.Sections[0].HeadersFooters.Header.ChildObjects.Clear();
                    doc.Sections[0].HeadersFooters.Footer.ChildObjects.Clear();
                }
                catch
                { }
                // 这里使用了Spire Doc免费版,免费版有篇幅限制。在加载或操作Word文档时,要求Word文档不超过500个段落,25个表格。如您有更高的需求,请自行购买、升级使用付费版。
                text = doc.GetText();
                text = text.Replace("#", "").Replace('\r', '#').Replace('\n', '#');
                text = Regex.Replace(text, @"[^\u4e00-\u9fa5\《\》\(\)\——\;\,\。\“\”\!\#]", "");
                text = new Regex("[#]+").Replace(text, "@@").Trim();
                text = TextFormat(text, blockText);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();
                }
            }
            return(text);
        }
        /// <summary>
        /// 将Pdf文档转换为xps文档
        /// </summary>
        /// <param name="wordDocName">word文档全路径</param>
        /// <param name="xpsDocName">xps文档全路径</param>
        /// <returns></returns>
        public static Boolean ConvertWordToXPS2(string wordDocName, string xpsDocName)
        {
            Boolean b = false;

            try
            {
                //初始化String类,元素为需要转换的Word文档

                //创建一个Document类对象,加载sample文件
                Spire.Doc.Document doc = new Spire.Doc.Document();
                doc.LoadFromFile(wordDocName);

                //  Spire.Doc.Section section =  new Spire.Doc.Section(null);
                // doc.Sections.Add(section);


                //设置文档的背景填充模式为颜色填充
                //  doc.Background.Type = BackgroundType.Color;
                //设置背景颜色
                //   doc.Background.Color = System.Drawing.Color.Transparent;

                //将Word文件保存为XPS,并运行生成的文档
                doc.SaveToFile(xpsDocName, Spire.Doc.FileFormat.XPS);
                b = true;
            }
            catch (Exception e1)
            {
                b = false;
                //  System.Windows.MessageBox.Show("word转换失败:" + e1.Message);
            }
            return(b);
        }
示例#10
0
 internal void method_0(OwnerHolder A_0)
 {
     this.ownerHolder_0 = A_0;
     if (A_0 != null)
     {
         this.m_doc = A_0.Document;
     }
 }
示例#11
0
        /// <summary>
        /// 向指定位置添加空行
        /// </summary>
        /// <param name="mydoc"></param>
        /// <param name="str"></param>
        /// <param name="spacenum"></param>
        public void AddSpaceLine(Spire.Doc.Document mydoc, string str, int spacenum)
        {
            var myts = mydoc.FindAllString(Regex.Replace(str, @"\r\n", ""), false, false);

            for (int spaceindex = 0; spaceindex < spacenum; spaceindex++)
            {
                myts[myts.Length - 1].GetAsOneRange().OwnerParagraph.AppendText("\r\n");
            }
        }
示例#12
0
 public static bool SaveToPDF(string srcFileName, string dstFileName)
 {
     File.Delete(dstFileName);
     using (Spire.Doc.Document doc = new Spire.Doc.Document(srcFileName))
     {
         doc.SaveToFile(dstFileName, Spire.Doc.FileFormat.PDF);
     }
     return(File.Exists(dstFileName));
 }
示例#13
0
        private static void method3(string filename, string printer)
        {
            MemoryStream ms = new MemoryStream();

            Spire.Doc.Document doc = new Spire.Doc.Document();
            doc.LoadFromFile(filename);
            doc.SaveToStream(ms, Spire.Doc.FileFormat.XPS);
            ms.Position = 0;
            XpsPrintHelper.Print(ms, printer, $"{Path.GetFileName(filename)}", true);
        }
 string get_text_from_word_by_spire(string path, Spire.Doc.Document doc)
 {
     doc.LoadFromFile(path);
     try
     {
         doc.Sections[0].HeadersFooters.Header.ChildObjects.Clear();
         doc.Sections[0].HeadersFooters.Footer.ChildObjects.Clear();
     }
     catch
     { }
     return(doc.GetText());
 }
 public string text()
 {
     if (string.IsNullOrEmpty(text_))
     {
         var document = new Document();
         document.LoadFromFile(path_);
         text_ = document.GetText().replace(new string[, ] {
             { "\r\n", " " }, { "\t", " " }
         });
     }
     return(text_);
 }
        private byte[] ConvertToPdf(string input)
        {
            var input_bytes   = System.Convert.FromBase64String(input);
            var input_stream  = new System.IO.MemoryStream(input_bytes);
            var output_stream = new System.IO.MemoryStream();

            var pdfdoc = new Spire.Doc.Document(input_stream, Spire.Doc.FileFormat.Auto);

            pdfdoc.SaveToStream(output_stream, Spire.Doc.FileFormat.PDF);

            return(output_stream.ToArray());
        }
示例#17
0
 internal void method_3(Spire.Doc.Document A_0, OwnerHolder A_1)
 {
     this.ownerHolder_0 = A_1;
     if (A_1 == null)
     {
         this.m_doc = A_0;
     }
     else
     {
         this.m_doc = A_1.Document;
     }
 }
示例#18
0
        private void printButton_Click(object sender, EventArgs e)
        {
            string fileName = "";

            switch (formName)
            {
            case "Клиенты":
            {
                if (Directory.Exists(dirName))
                {
                    fileName = $@"{dirName}\Заказ.docx";
                }
            }
            break;

            case "Услуги":
            {
                if (Directory.Exists(dirName))
                {
                    fileName = $@"{dirName}\Услуги.docx";
                }
            }
            break;
            }

            Document doc = new Document();

            if (File.Exists(fileName))
            {
                doc.LoadFromFile(fileName);
                PrintDialog dialog = new PrintDialog();

                dialog.AllowPrintToFile = true;
                dialog.AllowCurrentPage = true;
                dialog.AllowSomePages   = true;
                dialog.UseEXDialog      = true;

                doc.PrintDialog = dialog;
                PrintDocument printDoc = doc.PrintDocument;
                printDoc.DocumentName = fileName;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    printDoc.Print();
                }
            }
            else
            {
                MessageBox.Show("Не удалось найти файл для печати.\nПожалуйста закройте окно отправки", "",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }///////////Печать документа
示例#19
0
        public void CorruptedMathTypeEquation_SaveDocumentAsDoc_CallToWordOpenXMLWillNoLongerWork()
        {
            var inputPath = "test-inputs/CH7594-Corrupted MathType Equation.doc";

            this.Invoking(y => y.GetOpenXml(inputPath)).Should().NotThrow("before save call to WordOpenXML still works");

            var outputFilePath = $"{OutputPath}/{nameof(CorruptedMathTypeEquation_SaveDocumentAsDoc_CallToWordOpenXMLWillNoLongerWork)}.doc";

            using var doc = new Document(inputPath);
            doc.SaveToFile(outputFilePath);

            this.Invoking(y => y.GetOpenXml(outputFilePath)).Should().NotThrow("call to WordOpenXML still works as document is saved as .doc");
        }
 /// <summary>
 /// 替换Word
 /// </summary>
 /// <param name="path"></param>
 /// <param name="dics"></param>
 /// <param name="savePath"></param>
 /// <returns></returns>
 public bool WordReplace(string path, string savePath, Dictionary <string, string> dics)
 {
     using (var doc = new Spire.Doc.Document())
     {
         doc.LoadFromFile(path);
         foreach (var item in dics)
         {
             doc.Replace(new Regex(item.Key), item.Value);
         }
         doc.SaveToFile(savePath);
         doc.Close();
     }
     return(true);
 }
 internal static byte[] DocumentToPdf(byte[] docBytes)
 {
     byte[] result = null;
     using (MemoryStream ms = new MemoryStream(docBytes))
     {
         Spire.Doc.Document doc = new Spire.Doc.Document(ms);
         using (MemoryStream target = new MemoryStream())
         {
             doc.SaveToStream(target, Spire.Doc.FileFormat.PDF);
             result = target.ToArray();
         }
         return(result);
     }
 }
示例#22
0
        public static void saveNode(Spire.Doc.Document doc, MyNode myNode, int depth)
        {
            if (depth != 1)
            {
                //不保存最大的节点
                Spire.Doc.Documents.Paragraph paraInserted = doc.Sections[0].AddParagraph();
                Spire.Doc.Fields.TextRange    textRange1   = paraInserted.AppendText(myNode.Content + "");
                paraInserted.ApplyStyle(numberToBuitinStyle[depth - 1]);
            }

            for (int i = 0; i < myNode.Child.Count; i++)
            {
                saveNode(doc, myNode.Child[i], depth + 1);
            }
        }
示例#23
0
        public void printWord(string path)
        {
            Spire.Doc.Document doc = new Spire.Doc.Document();
            doc.LoadFromFile(path);

            //PrintDialog dialog = new PrintDialog();
            //dialog.AllowPrintToFile = true;
            //dialog.AllowCurrentPage = true;
            //dialog.AllowSomePages = true;
            //dialog.UseEXDialog = true;
            //doc.PrintDialog = dialog;

            //System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;
            //printDoc.Print();
        }
示例#24
0
        /// <summary>
        /// 使用com设置文本格式
        /// </summary>
        public void FormatSet(Spire.Doc.Document mydoc, List <Paragraphs> listp, Format f)
        {
            for (int i = 0; i < listp.Count; i++)
            {
                //字体名称
                listp[i].Last.Range.Font.Name = f.fontname;
                //字体大小
                listp[i].Last.Range.Font.Size = f.fontsize;
                //设置行距
                switch (f.lstype)
                {
                case "单倍行距":
                    listp[i].Last.Range.Paragraphs.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;
                    break;

                case "1.5倍行距":
                    listp[i].Last.Range.Paragraphs.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpace1pt5;
                    break;

                case "2倍行距":
                    listp[i].Last.Range.Paragraphs.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceDouble;
                    break;

                default:
                    listp[i].Last.Range.Paragraphs.LineSpacing = f.lsvalue;
                    break;
                }
                //首行缩进
                listp[i].Last.Range.Paragraphs.CharacterUnitFirstLineIndent = f.suojin; //首行缩进
                                                                                        //加粗
                listp[i].Last.Range.Font.Bold = f.bold;                                 //黑体字
                                                                                        //设置居中
                switch (f.juzhong)
                {
                case "左对齐":
                    listp[i].Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;    //居中
                    break;

                case "居中":
                    listp[i].Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;    //居中
                    break;

                case "右对齐":
                    listp[i].Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;    //居中
                    break;
                }
            }
        }
示例#25
0
        /// <summary>
        /// <see cref="https://www.e-iceblue.com/Tutorials/Spire.Doc/Spire.Doc-Program-Guide/Print-a-Word-Document-Programmatically-in-5-Steps.html"/>
        /// <see cref="https://www.e-iceblue.com/Tutorials/Spire.Doc/Spire.Doc-Program-Guide/Document-Operation/Print-word-document-without-showing-print-processing-dialog.html"/>
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="printer"></param>
        public static void PrintWithSpire(string filename, string printer, bool isLandscape = false, PaperSize paperSize = null, Margins margins = null)
        {
            if (REF.Constants.postcardIDs.Any(t => filename.ContainsString(t)))
            {
                PrintPostCards_Spire(filename, printer);
                return;
            }

            if (paperSize == null)
            {
                paperSize = PaperSizes["A4"];
            }

            Spire.Doc.Document doc = new Spire.Doc.Document();
            //Load word document
            doc.LoadFromFile(filename);
            // Instantiated System.Windows.Forms.PrintDialog object .
            //PrintDialog dialog = new PrintDialog();
            //dialog.AllowPrintToFile = true;
            //dialog.AllowCurrentPage = true;
            //dialog.AllowSomePages = true;
            //dialog.UseEXDialog = true;
            //// associate System.Windows.Forms.PrintDialog object with Spire.Doc.Document
            //doc.PrintDialog = dialog;
            System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;
            doc.PrintDocument.PrinterSettings.PrinterName = printer;
            if (doc.PrintDocument.PrinterSettings.CanDuplex)
            {
                doc.PrintDocument.PrinterSettings.Duplex = Duplex.Vertical;
            }
            System.Drawing.Printing.PrintController printController = new System.Drawing.Printing.StandardPrintController();
            printDoc.PrintController = printController;
            printDoc.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;
            if (isLandscape)
            {
                printDoc.PrinterSettings.DefaultPageSettings.Landscape = true;
            }
            if (margins != null)
            {
                printDoc.PrinterSettings.DefaultPageSettings.Margins = margins;
            }

            //Background printing
            printDoc.Print();
        }
示例#26
0
 public static bool SaveFile1(string filePath, MyNode myNode)
 {
     try
     {
         Spire.Doc.Document doc = new Spire.Doc.Document();
         doc.LoadFromFile(filePath);
         while (doc.Sections[0].Paragraphs.Count != 0)
         {
             doc.Sections[0].Paragraphs.RemoveAt(0);
         }
         saveNode(doc, myNode, 1);
         doc.SaveToFile(filePath);
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
示例#27
0
        static void Main(string[] args)
        {
            // var word_file = args[0];
            // var pdf_file = args[1];

            var word_file = "./result/result.docx";
            var pdf_file  = "./result/result.pdf";

            Console.WriteLine(word_file);
            Console.WriteLine(pdf_file);

            var watch = System.Diagnostics.Stopwatch.StartNew();

            Spire.Doc.Document pdfdoc = new Spire.Doc.Document(word_file, Spire.Doc.FileFormat.Auto);
            pdfdoc.SaveToFile(pdf_file, Spire.Doc.FileFormat.PDF);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Console.WriteLine($"Completed in {elapsedMs / 1000} seconds {elapsedMs % 1000} milliseconds");
        }
示例#28
0
        public static string ToHTML(string fBase64, string nomeoriginal)
        {
            using (var doc = new Spire.Doc.Document())
            {
                using (Stream stream = new MemoryStream(Convert.FromBase64String(fBase64)))
                {
                    doc.LoadFromStream(stream, Path.GetExtension(nomeoriginal).ToUpper().Contains("DOCX") ? Spire.Doc.FileFormat.Docx : Spire.Doc.FileFormat.Doc);
                    doc.HtmlExportOptions.ImageEmbedded              = true;
                    doc.HtmlExportOptions.IsExportDocumentStyles     = false;
                    doc.HtmlExportOptions.CssStyleSheetType          = Spire.Doc.CssStyleSheetType.Internal;
                    doc.HtmlExportOptions.HasHeadersFooters          = false;
                    doc.HtmlExportOptions.IsTextInputFormFieldAsText = true;

                    var outstr = new MemoryStream();
                    doc.SaveToStream(outstr, Spire.Doc.FileFormat.Html);
                    var rethtml = Encoding.GetEncoding("utf-8").GetString(outstr.ToArray()); //basicamente funciona com HTML

                    return(rethtml);
                }
            }
        }
        public IEnumerable <Spire.Doc.Fields.Field> ReadLeapForm(string myFilePath)
        {
            // Use spire to get a collection of all mergefield names
            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(myFilePath);

            var             merge       = document.MailMerge;
            FieldCollection fields      = document.Fields;
            var             mergeFields = from Spire.Doc.Fields.Field f in fields
                                          where f.DocumentObjectType.ToString() == "MergeField"
                                          select f;

            mergeFields = mergeFields.ToList();

            var mergeFieldNames = document.MailMerge.GetMergeFieldNames().ToList();

            //foreach (var f in mergeFields)
            //{
            //    Console.Write($"{f.Code.Substring(12, f.Code.Length - 12)}, {f.Text}\n");
            //}
            return(mergeFields);
        }
示例#30
0
        /// <summary>
        /// Method that searches all the employees in a file
        /// </summary>
        /// <param name="file">
        /// File to be searched and added to the sql database
        /// </param>
        /// <param name="connectionString">
        /// Azure blob storage connection string
        /// </param>
        /// <param name="containerName">
        /// Azure blob storage container name
        /// </param>
        /// <returns>
        /// Dictionary with the results found
        /// </returns>
        public Dictionary <string, int> SearchEmployees(D.Models.File file, string connectionString, string containerName)
        {
            string filePath  = GeneratePath(file.Name);
            string extension = Path.GetExtension(file.Name).ToLower();
            string text;

            DownloadFile(file.Name, filePath, connectionString, containerName);

            if (extension == ".pdf")
            {
                PdfDocument doc = new PdfDocument();
                doc.LoadFromFile(filePath);
                StringBuilder buffer = new StringBuilder();
                foreach (PdfPageBase page in doc.Pages)
                {
                    buffer.Append(page.ExtractText());
                }

                doc.Close();
                text = buffer.ToString();
                text = text.Replace(Environment.NewLine, " ");
                text = DeleteRepeatedSpaces(text);
                return(SearchEmployeesAux1(file, filePath, text));
            }
            else if (extension == ".docx")
            {
                Spire.Doc.Document doc = new Spire.Doc.Document();
                doc.LoadFromFile(filePath);
                text = doc.GetText();
                doc.Close();
                return(SearchEmployeesAux1(file, filePath, text));
            }
            else
            {
                text = File.ReadAllText(filePath);
                return(SearchEmployeesAux1(file, filePath, text));
            }
        }
示例#31
0
        private MemoryStream PrepareCommonOrderPrintData(IOrdersManager ordersManager, int id, string path, PrintTypes type,
            IInvoicesManager invoicesManager, ITaxesManager taxesManager, IInvoiceStornosManager invoiceStornosManager = null,
            ITransportOrdersManager transportOrdersManager = null,
            ITermsManager termsManager = null)
        {
            var result = new MemoryStream();
            try
            {
                Package pkg;
                PackagePart part;
                XmlReader xmlReader;
                XDocument xmlMainXMLDoc;
                GetXmlDoc(path, result, out pkg, out part, out xmlReader, out xmlMainXMLDoc);


                var images = new List<Image>();

                if (type == PrintTypes.DeliveryNote)
                {
                    var term = termsManager.GetById(id);
                    for (var i = 0; i < term.DeliveryNoteSignatures.Count; i++)
                    {
                        var deliveryNoteSignature = term.DeliveryNoteSignatures.ElementAt(term.DeliveryNoteSignatures.Count - i - 1);
                        //TODO doesnt work ((
                        //pkg.CreateRelationship(uri, TargetMode.Internal,
                        //    "Http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
                        //    "barcodeImageId");


                        byte[] bytes = Convert.FromBase64String(deliveryNoteSignature.Signature.Replace("data:image/png;base64,", ""));

                        Image image;
                        using (MemoryStream ms = new MemoryStream(bytes))
                        {
                            image = Image.FromStream(ms);
                        }

                        images.Add(image);
                    }
                }

                //replace fields
                var templateBody = ReplaceFields(ordersManager, id, type, xmlMainXMLDoc.Root.ToString(),
                    invoicesManager, taxesManager, null, invoiceStornosManager, transportOrdersManager, termsManager, images);

                xmlMainXMLDoc = SaveDoc(result, pkg, part, xmlReader, xmlMainXMLDoc, templateBody);

                InsertImages(result, images);

                var doc = new Spire.Doc.Document();
                doc.LoadFromStream(result, Spire.Doc.FileFormat.Docx);
                doc.JPEGQuality = 100;

                result = new MemoryStream();
                doc.SaveToStream(result, Spire.Doc.FileFormat.PDF);
            }
            catch
            {
            }

            return result;
        }