Ejemplo n.º 1
0
        public void OpenInOffice(IDocTemplate template, bool readOnly, FileEditMode mode, bool silentPrint = false)
        {
            logger.Info ("Сохраняем временный файл...");
            OdtWorks odt;
            odt = new OdtWorks (template.File);
            odt.DocParser = template.DocParser;
            odt.DocParser.UpdateFields();
            odt.UpdateFields ();
            if(odt.DocParser.FieldsHasValues)
            {
                odt.FillValues();
            }
            var file = odt.GetArray ();
            odt.Close ();

            var opened = openedFiles.FirstOrDefault(x => x.Template == template);

            if (opened == null)
            {
                opened = new OpenedFile(this, template, mode);
                openedFiles.Add(opened);
            }
            else
                opened.StopWatch();

            if (File.Exists (opened.TempFilePath))
                File.SetAttributes (opened.TempFilePath, FileAttributes.Normal);

            try
            {
                File.WriteAllBytes (opened.TempFilePath, file);
            }
            catch (UnauthorizedAccessException)
            {
                string tempName = opened.TempFilePath;
                FileInfo fi = new FileInfo (opened.TempFilePath);
                int tryesCount = 0;
                bool error = true;

                while (error)
                {
                    tryesCount++;
                    tempName = string.Format("{0}{1}({2}){3}",
                        fi.Directory + Path.DirectorySeparatorChar.ToString(),
                        Path.GetFileNameWithoutExtension(fi.Name),
                        tryesCount,
                        fi.Extension);
                    try
                    {
                        File.WriteAllBytes (tempName, file);
                        error = false;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        error = true;
                    }
                }
                opened.TempFilePath = tempName;
            }

            if (readOnly)
                File.SetAttributes(opened.TempFilePath, FileAttributes.ReadOnly);
            else
                opened.StartWatch();

            if (silentPrint)
            {
                string officeName = "soffice";
                string args = "-p \"" + opened.TempFilePath + "\"";

                logger.Info("Печатаем файл...");
                System.Diagnostics.Process.Start(officeName, args).WaitForExit();
            }
            else
            {
                logger.Info("Открываем файл во внешнем приложении...");
                System.Diagnostics.Process.Start(opened.TempFilePath).WaitForExit();
            }
        }