Пример #1
0
        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();
        }
        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);
        }
Пример #3
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("要替换的新旧字符串数量不同,取消操作");
            }
        }
Пример #4
0
        public void readFile()
        {
            //加载一个现有Word文档
            doc.LoadFromFile(filePath);
            if (doc.Sections[0].Paragraphs[0].Text
                .Equals("Evaluation Warning: The document was created with Spire.Doc for .NET."))
            {
                doc.Sections[0].Paragraphs.RemoveAt(0);
            }

            int sectionLength = 0;

            foreach (Spire.Doc.Section section in doc.Sections)
            {
                sectionLength++;
            }

            for (int i = 0; i < sectionLength; i++)
            {
                //每一个Section的每一个段落
                section1   = doc.Sections[i];
                paraLength = 0;
                foreach (Spire.Doc.Documents.Paragraph paragraph in section1.Paragraphs)
                {
                    paraLength++;
                }
                for (n = 0; n < paraLength;)
                {
                    generateNode(null, 0);
                }
            }
        }
Пример #5
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);
        }
Пример #6
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();
        }
Пример #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);
        }
        /// <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);
        }
Пример #9
0
        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();
        }
Пример #10
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);
        }
Пример #11
0
 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());
 }
Пример #12
0
 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_);
 }
Пример #13
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);
            }
        }///////////Печать документа
 /// <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);
 }
Пример #15
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();
        }
Пример #16
0
 /// <summary>
 /// Word转换PDF
 /// </summary>
 /// <param name="fileName">文件名称</param>
 public static void WordToPDF(string fileName)
 {
     try
     {
         if (!FileHelper.IsExistFile(fileName.Substring(0, fileName.LastIndexOf(".")) + ".pdf"))
         {
             Stream stream   = File.OpenRead(fileName);
             var    document = new Spire.Doc.Document();
             document.LoadFromFile(fileName);
             document.SaveToFile(fileName.Substring(0, fileName.LastIndexOf(".")) + ".pdf", Spire.Doc.FileFormat.PDF);
         }
     }
     catch (Exception ex)
     {
         throw ExceptionEx.Throw(ex);
     }
 }
Пример #17
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();
        }
Пример #18
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);
     }
 }
Пример #19
0
        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);
        }
Пример #20
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));
            }
        }
Пример #21
0
        public static bool InsertTextInPlaceholders_spire(string templatePath, string outputDocumentPath, Object obj)
        {
            try
            {
                if (!File.Exists(templatePath))
                {
                    throw new FileNotFoundException();
                }

                //Creates Document instance
                Spire.Doc.Document document = new Spire.Doc.Document();

                //Loads the word document
                document.LoadFromFile(templatePath);

                // Gets the collection of all the merge field names
                string[] MergeFieldNames    = document.MailMerge.GetMergeFieldNames();
                var      myMergeFieldValues = new List <string>();
                foreach (var reqField in MergeFieldNames)
                {
                    myMergeFieldValues.Add(obj.GetPropertyStringValue(reqField));
                }

                //var myMergeFieldNames = obj.GetPublicStringPropertiesNames();
                document.MailMerge.Execute(MergeFieldNames, myMergeFieldValues.ToArray());

                document.SaveToFile(outputDocumentPath);

                return(true);
            }
            catch (Exception x)
            {
                XLogger.Error(x);
                return(false);
            }
        }
Пример #22
0
        public IEnumerable <Spire.Doc.Fields.Field> ReadSmokeballForm(string filePath)
        {
            // Use spire to get a collection of fields in the smokeball document
            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile($"{filePath}");

            var             merge       = document.MailMerge;
            FieldCollection fields      = document.Fields;
            var             mergeFields = from Spire.Doc.Fields.Field f in fields
                                          select f;

            mergeFields = mergeFields.Where(x => !x.Code.Contains("CHECKBOX") && !x.Code.Contains("AUTOMATIONIF") && !x.Code.Contains("AUTOMATIONELSE") && !x.Code.Contains("AUTOMATIONENDIF") && !x.Code.Contains("AUTOMATIONENDELSE")).ToList();

            // To see all mergefields in the document, uncomment the following lines
            foreach (var f in mergeFields)
            {
                int matchIndex = GetMatchIndex(f);
                Console.WriteLine($"{f.Code.Substring(matchIndex)}");
            }

            var cleanMergefields = new List <Spire.Doc.Fields.Field>();

            foreach (var f in mergeFields)
            {
                if (f.FieldText != string.Empty && !cleanMergefields.Contains(f))
                {
                    cleanMergefields.Add(f);
                }
            }

            foreach (var f in cleanMergefields)
            {
                var mergeFieldNameStartIndex = GetMatchIndex(f);
            }
            return(cleanMergefields);
        }
Пример #23
0
        /// <summary>
        /// 对Word文档进行拆分
        /// </summary>
        /// <param name="wordPath">要拆分的Word文档路径</param>
        /// <param name="savePath">拆分后的Word存储路径</param>
        private void SplitWord(string wordPath, string savePath)
        {
            object missing = System.Reflection.Missing.Value; //作为方法传参中的缺省值

            if (!Directory.Exists(savePath))                  //判断Word存储路径是否存在
            {
                Directory.CreateDirectory(savePath);          //如果路径不存在,则创建
            }
            try
            {
                //判断拆分方式:0表示按书签拆分,1表示按分页符拆分,默认为按书签拆分
                switch (flag)
                {
                    #region  书签拆分
                case 0:
                default:
                    Document doc = null;                    //声明一个Word文档对象
                    if (doc == null)                        //判断Word文档对象是否为空
                    {
                        doc = ReadDocument(wordPath);       //调用方法读取指定Word内容,并实例化Word文档对象
                    }
                    int[,] positions = GetPosition(doc);    //获取指定Word中的所有书签的开始和结束位置
                    object oStart = 0;                      //定义变量,表示要拆分的开始位置
                    object oEnd   = 0;                      //定义变量,表示要拆分的结束位置
                    int    row    = positions.GetLength(0); //获取二维数组的行数
                    for (int i = 0; i < row; i++)           //遍历二维数组的所有行
                    {
                        if (i != row - 1)                   //判断是否为最后一行
                        {
                            oEnd = positions[i, 1];         //如果不是最后一行,记录值,作为拆分的结束位置
                        }
                        else
                        {
                            oEnd = doc.Content.End;                     //如果是最后一行,则直接将Word文档的最后位置作为拆分的结束位置
                        }
                        Range tocopy = doc.Range(ref oStart, ref oEnd); //使用开始和结束位置锁定要拆分的范围
                        tocopy.Copy();                                  //复制要拆分范围内容的所有内容
                        Document docto = CreateDocument(textBox1.Text); //调用自定义方法创建一个新的Word文档
                        docto.Content.Paste();                          //将复制的内容粘贴到新创建的Word文档中
                        //设置Word文档的保存路径及文件名(以编号命名)
                        object filename = savePath + "\\" + i.ToString("000") + ".docx";
                        //保存Word文档
                        docto.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref missing, ref missing);
                        docto.Close(ref missing, ref missing, ref missing); //关闭Word文档
                        oStart = oEnd;                                      //将本次拆分的结束位置作为下一次拆分的开始位置
                    }
                    break;
                    #endregion

                    #region  分页符拆分
                case 1:
                    Spire.Doc.Document original = new Spire.Doc.Document();             //使用Spire插件创建Word文档对象
                    original.LoadFromFile(wordPath);                                    //加载要拆分的Word文档
                    Spire.Doc.Document newWord = new Spire.Doc.Document(textBox1.Text); //使用选择的模板创建一个新的Word文档对象
                    Spire.Doc.Section  section = newWord.AddSection();                  //为新创建的Word文档添加一节
                    int index = 0;                                                      //根据分页来拆分文档
                    foreach (Spire.Doc.Section sec in original.Sections)                //遍历文档所有节
                    {
                        //遍历文档所有子对象
                        foreach (Spire.Doc.DocumentObject obj in sec.Body.ChildObjects)
                        {
                            if (obj is Spire.Doc.Documents.Paragraph)    //判断是否为段落
                            {
                                //创建Word文档中的段落对象
                                Spire.Doc.Documents.Paragraph para = obj as Spire.Doc.Documents.Paragraph;
                                //复制并添加原有段落对象到新文档
                                section.Body.ChildObjects.Add(para.Clone());
                                //遍历所有段落子对象
                                foreach (Spire.Doc.DocumentObject parobj in para.ChildObjects)
                                {
                                    //判断是否为分页符
                                    if (parobj is Spire.Doc.Break && (parobj as Spire.Doc.Break).BreakType == Spire.Doc.Documents.BreakType.PageBreak)
                                    {
                                        //获取段落分页并移除,保存新文档到文件夹
                                        int i = para.ChildObjects.IndexOf(parobj);
                                        section.Body.LastParagraph.ChildObjects.RemoveAt(i);
                                        newWord.SaveToFile(savePath + "\\" + index.ToString("000") + ".docx", Spire.Doc.FileFormat.Docx);
                                        index++;
                                        //实例化Document类对象,添加section,将原文档段落的子对象复制到新文档
                                        newWord = new Spire.Doc.Document(textBox1.Text);
                                        section = newWord.AddSection();
                                        section.Body.ChildObjects.Add(para.Clone());
                                        if (section.Paragraphs[0].ChildObjects.Count == 0)
                                        {
                                            section.Body.ChildObjects.RemoveAt(0);    //移除第一个空白段落
                                        }
                                        else
                                        {
                                            //删除分页符前的子对象
                                            while (i >= 0)
                                            {
                                                section.Paragraphs[0].ChildObjects.RemoveAt(i);
                                                i--;
                                            }
                                        }
                                    }
                                }
                            }
                            //若对象为表格,则添加表格对象到新文档
                            if (obj is Spire.Doc.Table)
                            {
                                section.Body.ChildObjects.Add(obj.Clone());
                            }
                        }
                    }
                    //拆分后的新文档保存至指定文档
                    newWord.SaveToFile(savePath + "\\" + index.ToString("00") + ".docx", Spire.Doc.FileFormat.Docx);
                    original.Close();
                    original.Dispose();
                    newWord.Close();
                    newWord.Dispose();
                    foreach (string file in Directory.GetFiles(savePath)) //遍历拆分完的所有Word文档
                    {
                        deletePagesInFile(file, 1, 1);                    //删除第一页
                    }
                    break;
                    #endregion
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }//异常跳过
        }
Пример #24
0
        /// <summary>
        /// 文件上传
        /// </summary>
        public void UploadFiles()
        {
            bool result = false;

            if (Request.Form["option"].ToString() == "update")
            {
                string fn      = Request.Form["filename"].ToString();
                string keyword = Request.Form["keyword"].ToString();
                string status  = Request.Form["ispublic"].ToString() == "checked" ? "1" : "0";
                string id      = Request.Form["id"].ToString();
                string sql     = string.Format("update fileinfo set filename='{0}',keyword='{1}',status='{2}' where keyid={3}", fn, keyword, status, id);
                int    i       = DAL.Commons.Instance.chooseFactory("sql").ExecuteNonQuery(sql);
                result = i > 0 ? true : false;
            }
            else
            {
                if (Request.Files.Count > 0)
                {
                    loginUser lu  = Session["user"] as loginUser;
                    string    dir = string.Format("{0}//{1}//{2}", "upload", DateTime.Now.ToString("yyyy-MM-dd"), lu.LoginName);

                    string extName = Path.GetExtension(Request.Files[0].FileName);//.Split('.')[1].ToLower();
                    extName = extName.Substring(1);
                    string filename = DAL.Commons.Instance.GetUploadFileName(dir, extName);
                    Request.Files[0].SaveAs(AppDomain.CurrentDomain.BaseDirectory + filename);
                    string fn       = Request.Form["filename"].ToString();
                    string keyword  = Request.Form["keyword"].ToString();
                    string dirid    = Request.Form["dirid"].ToString();
                    string userid   = lu.ID;
                    string status   = Request.Form["ispublic"].ToString() == "checked" ? "1" : "0";
                    string f1       = "doc,docx";
                    string f2       = "xls,xlsx";
                    string f3       = "txt,jpeg,png";
                    string f4       = "pdf";
                    int    viewmode = 3;
                    string viewdir  = "";
                    if (f1.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        Spire.Doc.Document doc = new Spire.Doc.Document();
                        doc.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + filename);
                        string newname = DAL.Commons.Instance.GetUploadFileName(dir, "pdf");
                        doc.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + newname, Spire.Doc.FileFormat.PDF);
                        viewdir = newname;
                        doc.Close();
                    }
                    else if (f2.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        Spire.Xls.Workbook book = new Spire.Xls.Workbook();
                        book.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + filename);
                        string newname = DAL.Commons.Instance.GetUploadFileName(dir, "pdf");
                        book.ConverterSetting.SheetFitToPage = true;
                        book.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + newname, Spire.Xls.FileFormat.PDF);
                        viewdir = newname;
                    }
                    else if (f3.IndexOf(extName) >= 0)
                    {
                        viewmode = 2;
                        viewdir  = filename;
                    }
                    else if (f4.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        viewdir  = filename;
                    }
                    Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();


                    string sql = string.Format("insert into fileinfo (filename,keyword,dirid,userid,status,localdir,viewdir,viewmode,extname) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", fn, keyword, dirid, userid, status, filename, viewdir, viewmode, extName);
                    int    i   = DAL.Commons.Instance.chooseFactory("sql").ExecuteNonQuery(sql);
                    result = i > 0 ? true : false;
                }
            }
            var par = new { sucess = result };

            Response.Write(DAL.Commons.Instance.ToJson(par));
        }
Пример #25
0
        public static byte[] ConvertToPdf(string fileName)
        {
            string       contentType = MimeMapping.GetMimeMapping(fileName);
            MemoryStream mem         = new MemoryStream();

            switch (contentType.ToLower())
            {
            case "image/gif":
            case "image/jpg":
            case "image/png":
            case "image/jpeg":
            case "application/BMP":
            case "image/bmp":
            case "image/tiff":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Document document = new Document(PageSize.LETTER, 10, 10, 10, 10);
                    //using ( var stream = new MemoryStream() )
                    //{
                    PdfWriter.GetInstance(document, mem);

                    document.Open();
                    using (var imageStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var image = Image.GetInstance(imageStream);
                        image.ScaleAbsolute(585, 750);
                        //image.ScaleAbsoluteHeight(PageSize.A4.Height - 20);
                        //image.ScaleToFit(PageSize.LETTER);

                        document.Add(image);
                    }
                    document.Close();

                    // return stream.ToArray();
                    //}
                }

                break;

            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            case "application/vnd.ms-excel":
            case "application/xlsx":
            case "application/xls":
            case "application/vnd.ms-excel.sheet.macroEnabled.12":
            case "application/XLSM":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
                    workbook.LoadFromFile(fileName, true);
                    workbook.SaveToStream(mem, Spire.Xls.FileFormat.PDF);
                }

                break;

            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            case "application/msword":
            case "application/docx":
            case "application/doc":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Doc.Document document = new Spire.Doc.Document();
                    document.LoadFromFile(fileName, Spire.Doc.FileFormat.Auto);
                    document.SaveToStream(mem, Spire.Doc.FileFormat.PDF);
                    document.Close();
                }

                break;

            case "application/html":
            case "application/txt":
            case "application/htm":
            case "text/html":
            case "application/xml":
            case "text/plain":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
                    PdfHtmlLayoutFormat   htmlLayoutFormat = new PdfHtmlLayoutFormat
                    {
                        Layout          = PdfLayoutType.Paginate,
                        FitToPage       = Clip.Width,
                        LoadHtmlTimeout = 60 * 1000
                    };
                    htmlLayoutFormat.IsWaiting = true;
                    PdfPageSettings setting = new PdfPageSettings();
                    setting.Size = PdfPageSize.A4;
                    Thread thread = new Thread(() => { pdf.LoadFromHTML(fileName, true, true, true); });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                    pdf.SaveToStream(mem, Spire.Pdf.FileFormat.PDF);
                }
                break;

            case "application/msg":
            case "application/octet-stream":
            case "multipart/related":
            case "application/ZIP":
            case "application/VCF":
            default:
                break;
            }

            return(mem.ToArray());
        }
Пример #26
0
        public ActionResult CreateDocumentsFromTemplate(ContractDetails details)
        {
            //Get data from db for current user
            DSGVOEntities1 db = new DSGVOEntities1();


            kunden CurrentUser = db.kundens.Where(t => t.plz == details.UserZip.ToString().Trim() && t.seriennr.Substring(15).Trim() == details.SerialNo.ToString().Trim()).First();

            ////Update contractuser in db
            //CurrentUser.contractuser = details.ContractUser.ToString().Trim();

            ////Change email if it is changed
            //if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim())
            //{
            //    CurrentUser.email = details.Email.ToString().Trim();
            //}

            //db.SaveChanges();


            //Check if changes in data exist and send it in email
            StringBuilder dataChanges = new StringBuilder();

            bool ChangesExist = false;

            dataChanges.Append("<table>");
            dataChanges.Append(" <tr><th>Previous data</th><th>Changed data from user</th></tr>");


            if (CurrentUser.name1.ToString().Trim() != details.Name1.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.name1.ToString().Trim() + " </td><td>" + details.Name1.ToString().Trim() + "</td></tr>");
                CurrentUser.name1 = details.Name1.ToString().Trim();
            }

            if (CurrentUser.name2.ToString().Trim() != details.Name2.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.name2.ToString().Trim() + " </td><td>" + details.Name2.ToString().Trim() + "</td></tr>");
                CurrentUser.name2 = details.Name2.ToString().Trim();
            }

            if (CurrentUser.strasse.ToString().Trim() != details.Street.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.strasse.ToString().Trim() + " </td><td>" + details.Street.ToString().Trim() + "</td></tr>");
                CurrentUser.strasse = details.Street.ToString().Trim();
            }

            if (CurrentUser.plz.ToString().Trim() != details.Zip.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.plz.ToString().Trim() + " </td><td>" + details.Zip.ToString().Trim() + "</td></tr>");
                CurrentUser.plz = details.Zip.ToString().Trim();
            }

            if (CurrentUser.ort.ToString().Trim() != details.City.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.ort.ToString().Trim() + " </td><td>" + details.City.ToString().Trim() + "</td></tr>");
                CurrentUser.ort = details.City.ToString().Trim();
            }

            //if (CurrentUser.land.ToString().Trim() != details.Country.ToString().Trim())
            //{
            //    ChangesExist = true;
            //    dataChanges.Append(" <tr><td>" + CurrentUser.land.ToString().Trim() + " </td><td>" + details.Country.ToString().Trim() + "</td></tr>");

            //}

            if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.email.ToString().Trim() + " </td><td>" + details.Email.ToString().Trim() + "</td></tr>");
                CurrentUser.email = details.Email.ToString().Trim();
            }

            //if (CurrentUser.contractuser == null)
            //{
            //    ChangesExist = true;
            //    dataChanges.Append(" <tr><td>Empty</td><td>" + details.ContractUser.ToString().Trim() + "</td></tr>");

            //}



            ////Adding user data to viewbag
            //if (CurrentUser.name1 != null)
            //{
            //    details.Name1 = CurrentUser.name1.ToString().Trim();
            //}

            //if (CurrentUser.name2 != null)
            //{
            //    details.Name2 = CurrentUser.name2.ToString().Trim();
            //}

            //if (CurrentUser.strasse != null)
            //{
            //    details.Street= CurrentUser.strasse.ToString().Trim() + " " ;
            //}



            //if (CurrentUser.ort != null)
            //{
            //    details.City= CurrentUser.ort.ToString().Trim();
            //}

            //if (CurrentUser.land != null)
            //{
            //    //Set country
            //    switch (CurrentUser.land.ToString().Trim())
            //    {
            //        case "D":
            //            CurrentUser.land = "Deutschland";
            //            break;
            //        case "A":
            //            CurrentUser.land = "Österreich";
            //            break;
            //        case "CH":
            //            CurrentUser.land = "Schweiz";
            //            break;
            //        default:
            //            break;
            //    }


            //    details.Country = CurrentUser.land.ToString().Trim();
            //}

            //if (CurrentUser.email != null)
            //{
            //    details.Contact = CurrentUser.email.ToString().Trim();
            //}


            // Set country
            switch (details.Country.ToString().Trim())
            {
            case "D":
                details.Country = "Deutschland";
                break;

            case "A":
                details.Country = "Österreich";
                break;

            case "CH":
                details.Country = "Schweiz";
                break;

            default:
                break;
            }


            string Result, Name;

            //Generating strong name as word and pdf name
            string HashName = UserInfo.CalculateMD5Hash(details.SerialNo + "-" + details.UserZip);


            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                document.LoadFromFile(Server.MapPath("~/Template/template.docx").ToString());


                if (details.Name1 != null && details.Name1.ToString().Trim() != "")
                {
                    document.Replace("##AGName1##", details.Name1, false, true);
                }

                else
                {
                    document.Replace("##AGName1##", "", false, true);
                }

                if (details.Name2 != null && details.Name2.ToString().Trim() != "")
                {
                    document.Replace("##AGName2##", details.Name2, false, true);
                }

                else
                {
                    document.Replace("##AGName2##", "", false, true);
                }

                if (details.Street != null && details.Street.ToString().Trim() != "")
                {
                    document.Replace("##AGStreet##", details.Street, false, true);
                }

                else
                {
                    document.Replace("##AGStreet##", "", false, true);
                }


                if (details.Zip != null && details.Zip.ToString().Trim() != "")
                {
                    document.Replace("##AGZIP##", details.Zip, false, true);
                }

                else
                {
                    document.Replace("##AGZIP##", "", false, true);
                }


                if (details.City != null && details.City.ToString().Trim() != "")
                {
                    document.Replace("##AGCITY##", details.City, false, true);
                    document.Replace("##City##", details.City, false, true);
                }

                else
                {
                    document.Replace("##AGCITY##", "", false, true);
                    document.Replace("##City##", "", false, true);
                }

                if (details.Country != null && details.Country.ToString().Trim() != "")
                {
                    document.Replace("##AGCountry##", details.Country, false, true);
                }

                else
                {
                    document.Replace("##AGCountry##", "", false, true);
                }

                if (details.ContractUser != null && details.ContractUser.ToString().Trim() != "")
                {
                    document.Replace("##ContractUser##", details.ContractUser, false, true);
                }


                if (details.Email != null && details.Email.ToString().Trim() != "")
                {
                    document.Replace("##AGCONTACT##", details.Email, false, true);
                }

                else
                {
                    document.Replace("##AGCONTACT##", "", false, true);
                }


                document.Replace("##DayDate##", DateTime.Now.ToString("dd.MM.yyyy"), false, true);

                document.SaveToFile(Server.MapPath("~/Word/").ToString() + HashName + ".docx", Spire.Doc.FileFormat.Docx);


                //Code for making connection with existing word template
                Microsoft.Office.Interop.Word._Application wApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Documents    wDocs = wApp.Documents;
                Microsoft.Office.Interop.Word._Document    wDoc  = wDocs.Open(Server.MapPath("~/Word/").ToString() + HashName + ".docx", ReadOnly: false, Visible: false);
                wDoc.Activate();

                string pdfName = @Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf";

                //wDoc.ExportAsFixedFormat(OutputFileName: pdfName, ExportFormat: WdExportFormat.wdExportFormatPDF, UseISO19005_1: true);
                wDoc.ExportAsFixedFormat(
                    pdfName,
                    WdExportFormat.wdExportFormatPDF,
                    OptimizeFor: WdExportOptimizeFor.wdExportOptimizeForPrint,
                    BitmapMissingFonts: true,
                    DocStructureTags: false,
                    UseISO19005_1: true);

                wDoc.Close();


                //Update fields into db
                CurrentUser.contractuser   = details.ContractUser;
                CurrentUser.contactperson  = details.ContractUser;
                CurrentUser.contractsigned = true;
                CurrentUser.signeddate     = DateTime.Now;
                CurrentUser.contractname   = HashName + ".pdf";



                //Send email with pdf as attachment to office
                SmtpClient        smtpClient      = new SmtpClient();
                NetworkCredential basicCredential =
                    new NetworkCredential("*****@*****.**", "hopeDSGVO");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                MailAddress fromAddress             = new MailAddress("*****@*****.**");

                smtpClient.Host = "smtp.1und1.de";
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials           = basicCredential;

                smtpClient.Port      = 587;
                smtpClient.EnableSsl = true;

                message.From    = fromAddress;
                message.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1;

                message.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf"));

                //[email protected]

                message.To.Add(new MailAddress("*****@*****.**"));


                smtpClient.Send(message);


                //Send email to customer
                SmtpClient        smtpCustomer            = new SmtpClient();
                NetworkCredential basicCredentialCustomer =
                    new NetworkCredential("*****@*****.**", "hopeDSGVO");
                System.Net.Mail.MailMessage messageCustomer = new System.Net.Mail.MailMessage();
                MailAddress fromAddressCompany = new MailAddress("*****@*****.**");

                smtpCustomer.Host = "smtp.1und1.de";
                smtpCustomer.UseDefaultCredentials = false;
                smtpCustomer.Credentials           = basicCredential;

                smtpCustomer.Port      = 587;
                smtpCustomer.EnableSsl = true;

                messageCustomer.From    = fromAddressCompany;
                messageCustomer.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1;

                messageCustomer.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf"));

                //[email protected]

                messageCustomer.To.Add(new MailAddress(CurrentUser.email.ToString().Trim()));

                smtpCustomer.Send(messageCustomer);



                //Send email if user changed data on html form [email protected]

                if (ChangesExist)
                {
                    //Send email with pdf as attachemnt
                    SmtpClient        smtpClientSecond      = new SmtpClient();
                    NetworkCredential basicCredentialSecond =
                        new NetworkCredential("*****@*****.**", "hopeDSGVO");
                    System.Net.Mail.MailMessage messageSecond = new System.Net.Mail.MailMessage();
                    MailAddress fromAddressSecond             = new MailAddress("*****@*****.**");

                    smtpClientSecond.Host = "smtp.1und1.de";
                    smtpClientSecond.UseDefaultCredentials = false;
                    smtpClientSecond.Credentials           = basicCredential;

                    smtpClientSecond.Port      = 587;
                    smtpClientSecond.EnableSsl = true;

                    messageSecond.From    = fromAddress;
                    messageSecond.Subject = "hope-DSGVO - Kundendaten geändert: " + details.UserZip + " - hotel: " + details.Name1;


                    messageSecond.IsBodyHtml = true;

                    messageSecond.Body = dataChanges.ToString();
                    //[email protected]

                    messageSecond.To.Add(new MailAddress("*****@*****.**"));


                    smtpClientSecond.Send(message);

                    //Update field in database
                    CurrentUser.datachanged = true;
                }



                //Update field in database
                db.SaveChanges();



                return(Json(new { Result = "true", Name = HashName }));
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error occured:", ex.ToString());
                return(Json(Result = ex.ToString()));
            }

            finally
            {
                Dispose();
            }
        }
Пример #27
0
        protected Dictionary <string, string> convierteArchivoA(string ruta, string nombreArchivo, string formato, string cliente)
        {
            Dictionary <string, string> res = new Dictionary <string, string>();

            res.Add("estatus", "error");
            Document    document         = null;
            Application applicationclass = null;

            applicationclass = new Application();

            object missingType       = Type.Missing;
            object readOnly          = true;
            object isVisible         = false;
            object rutaArchivo       = ruta + nombreArchivo;
            object formatoConversion = tipoArchivo(formato);
            object rutaArchivoConver = ruta + Path.GetFileNameWithoutExtension(ruta + nombreArchivo) + "." + formato;
            string archivoNomFinal   = Path.GetFileNameWithoutExtension(ruta + nombreArchivo) + "." + formato;

            if (formato.Equals("xml"))
            {
                ProcesaDocumento pd = new ProcesaDocumento(ruta + nombreArchivo, ruta, parametrosXML);
                if (pd.procesa())
                {
                    if (!pd.generaXMLV4())
                    {
                        res.Add("mensaje", pd.Mensaje);
                    }
                }
                else
                {
                    res.Add("mensaje", pd.Mensaje);
                }
            }
            else if (formato.Equals("epub"))
            {
                Spire.Doc.Document documento = new Spire.Doc.Document();
                documento.LoadFromFile(rutaArchivo.ToString());
                documento.SaveToFile(rutaArchivoConver.ToString(), Spire.Doc.FileFormat.EPub);
            }
            else
            {
                applicationclass.Documents.Open(ref rutaArchivo,
                                                ref readOnly,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType, ref isVisible,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType);

                applicationclass.Visible = false;
                document = applicationclass.ActiveDocument;


                document.SaveAs(ref rutaArchivoConver, ref formatoConversion, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType);

                document.Close(ref missingType, ref missingType, ref missingType);
                applicationclass.Quit();
            }

            if (formato.Equals("html"))
            {
                aplicaFormato(rutaArchivoConver.ToString(), Path.GetFileNameWithoutExtension(ruta + nombreArchivo));
            }

            if (File.Exists(rutaArchivoConver.ToString()))
            {
                bool comprimido = comprime(ruta, archivoNomFinal, formato);
                if (comprimido)
                {
                    string nombreArchivoZip = Path.GetFileNameWithoutExtension(nombreArchivo) + ".zip";
                    string urlServidor      = urlServer + "descargar.ashx?cliente=" + cliente + "&archivo=" + nombreArchivoZip;
                    res.Add("downloadURL", urlServidor);
                    res["estatus"] = "exito";
                    res.Add("zipFileName", nombreArchivoZip);
                    res.Add("fileName", Path.GetFileNameWithoutExtension(ruta + nombreArchivo) + "." + formato);
                    res.Add("imageFolder", "images");
                    res.Add("convertionType", formato);
                    ;
                }
                else
                {
                    res.Add("mensaje", "No se puede comprimir el archivo");
                }
            }

            return(res);
        }