Ejemplo n.º 1
0
        /// <summary>
        ///     Creates a directory that does not exist yet. It takes a path and appends a counting number (_2, _3, etc) to ensure
        ///     this in a readable way.
        /// </summary>
        /// <returns>The uniqified directory path</returns>
        public string MakeUniqueDirectory()
        {
            var directory = PathSafe.GetDirectoryName(_path) ?? "";
            var fileBody  = PathSafe.GetFileName(_path);

            var i = 2;

            while (_directoryWrap.Exists(_path) || _fileWrap.Exists(_path))
            {
                _path = PathSafe.Combine(directory, fileBody + "_" + i);
                i++;
            }

            return(_path);
        }
Ejemplo n.º 2
0
        private void SetPdfAParameters(IList <string> parameters)
        {
            var shortenedTempPath = Job.JobTempFolder;

            if (Job.Profile.OutputFormat == OutputFormat.PdfA1B)
            {
                parameters.Add("-dPDFA=1");
            }
            else
            {
                parameters.Add("-dPDFA=2");
            }
            //parameters.Add("-dNOOUTERSAVE"); //Set in pdf-A example, but is not documented in the distiller parameters

            Logger.Debug("Shortened Temppath from\r\n\"" + Job.JobTempFolder + "\"\r\nto\r\n\"" + shortenedTempPath +
                         "\"");

            //Add ICC profile
            var iccFile = PathSafe.Combine(shortenedTempPath, "profile.icc");

            //Set ICC Profile according to the color model
            switch (Job.Profile.PdfSettings.ColorModel)
            {
            case ColorModel.Cmyk:
                FileWrap.WriteAllBytes(iccFile, CoreResources.WebCoatedFOGRA28);
                break;

            case ColorModel.Gray:
                FileWrap.WriteAllBytes(iccFile, CoreResources.ISOcoated_v2_grey1c_bas);
                break;

            default:
            case ColorModel.Rgb:
                FileWrap.WriteAllBytes(iccFile, CoreResources.eciRGB_v2);
                break;
            }

            parameters.Add("-sPDFACompatibilityPolicy=1");

            parameters.Add("-sOutputICCProfile=\"" + iccFile + "\"");

            var defFile = PathSafe.Combine(Job.JobTempFolder, "pdfa_def.ps");
            var sb      = new StringBuilder(CoreResources.PdfaDefinition);

            sb.Replace("[ICC_PROFILE]", "(" + EncodeGhostscriptParametersOctal(iccFile.Replace('\\', '/')) + ")");
            FileWrap.WriteAllText(defFile, sb.ToString());
            parameters.Add(defFile);
        }
Ejemplo n.º 3
0
        private string CreateJobFolderInSpool(string file)
        {
            var psFilename = PathSafe.GetFileName(file);

            if (psFilename.Length > 23)
            {
                psFilename = psFilename.Substring(0, 23);
            }
            var jobFolder = PathSafe.Combine(_spoolerProvider.SpoolFolder, psFilename);

            jobFolder = new UniqueDirectory(jobFolder).MakeUniqueDirectory();
            _directory.CreateDirectory(jobFolder);
            Logger.Trace("Created spool directory for ps-file job: " + jobFolder);

            return(jobFolder);
        }
Ejemplo n.º 4
0
        public bool TryRepairPrinter(IEnumerable <string> printerNames)
        {
            Logger.Error("It looks like the printers are broken. This needs to be fixed to allow PDFCreator to work properly");

            var title   = _translation.RepairPrinterNoPrintersInstalled;
            var message = _translation.RepairPrinterAskUserUac;

            Logger.Debug("Asking to start repair..");

            var response = ShowMessage(message, title, MessageOptions.YesNo, MessageIcon.Exclamation);

            if (response == MessageResponse.Yes)
            {
                var applicationPath   = _assemblyHelper.GetAssemblyDirectory();
                var printerHelperPath = PathSafe.Combine(applicationPath, "PrinterHelper.exe");

                if (!_file.Exists(printerHelperPath))
                {
                    Logger.Error("PrinterHelper.exe does not exist!");
                    title   = _translation.Error;
                    message = _translation.GetSetupFileMissingMessage(PathSafe.GetFileName(printerHelperPath));

                    ShowMessage(message, title, MessageOptions.OK, MessageIcon.Error);
                    return(false);
                }

                Logger.Debug("Reinstalling Printers...");
                var pdfcreatorPath = _nameProvider.GetPortApplicationPath();

                var printerNameString = GetPrinterNameString(printerNames);

                var installParams = $"RepairPrinter -name={printerNameString} -PortApplication=\"{pdfcreatorPath}\"";
                var installResult = _shellExecuteHelper.RunAsAdmin(printerHelperPath, installParams);
                Logger.Debug("Done: {0}", installResult);
            }

            Logger.Debug("Now we'll check again, if the printer is installed");
            if (IsRepairRequired())
            {
                Logger.Warn("The printer could not be repaired.");
                return(false);
            }

            Logger.Info("The printer was repaired successfully");

            return(true);
        }
Ejemplo n.º 5
0
        public GhostscriptVersion GetGhostscriptInstance()
        {
            foreach (var path in GetPathCandidates())
            {
                var testPath = PathSafe.Combine(path, @"packages\Ghostscript");

                var exePath = PathSafe.Combine(testPath, @"Bin\gswin32c.exe");
                var libPath = PathSafe.Combine(testPath, @"Bin") + ';' + PathSafe.Combine(testPath, @"Lib") + ';' +
                              PathSafe.Combine(testPath, @"Fonts");

                if (File.Exists(exePath))
                {
                    return(new GhostscriptVersion("<internal>", exePath, libPath));
                }
            }

            return(null);
        }
Ejemplo n.º 6
0
        public LoadScriptResult LoadScriptWithValidation(string scriptFilename)
        {
            var actionResult = new ActionResult();

            if (string.IsNullOrWhiteSpace(scriptFilename))
            {
                actionResult.Add(ErrorCode.CustomScript_NoScriptFileSpecified);
                return(new LoadScriptResult(actionResult, null, ""));
            }

            var scriptFile = PathSafe.Combine(ScriptFolder, scriptFilename);

            if (!_file.Exists(scriptFile))
            {
                actionResult.Add(ErrorCode.CustomScript_FileDoesNotExistInScriptFolder);
                return(new LoadScriptResult(actionResult, null, ""));
            }

            return(LoadScript(scriptFile));
        }
        public List <HistoricJob> Load()
        {
            var oldHistoryDir = PathSafe.Combine(_environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PDFCreator");
            var oldSavePath   = PathSafe.Combine(oldHistoryDir, "PDFCreatorHistory.json");

            if (!_file.Exists(_savePath))
            {
                if (_file.Exists(oldSavePath))
                {
                    _file.Copy(oldSavePath, _savePath);
                    _logger.Debug($"Migrated job history from '{oldSavePath}' to '{_savePath}'.");
                }
                else
                {
                    return(new List <HistoricJob>());
                }
            }

            return(ReadHistoryJobsFile());
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Get the internal instance if it exists, otherwise the installed instance in the given version
        /// </summary>
        /// <returns>The best matching Ghostscript instance</returns>
        public GhostscriptVersion GetGhostscriptInstance()
        {
            var applicationPath = _assemblyHelper.GetAssemblyDirectory();

            var paths = PossibleGhostscriptPaths
                        .Select(path => PathSafe.Combine(applicationPath, path));

            foreach (var path in paths)
            {
                var exePath = PathSafe.Combine(path, @"Bin\gswin32c.exe");
                var libPath = PathSafe.Combine(path, @"Bin") + ';' + PathSafe.Combine(path, @"Lib");

                if (_file.Exists(exePath))
                {
                    return(new GhostscriptVersion("<internal>", exePath, libPath));
                }
            }

            return(null);
        }
Ejemplo n.º 9
0
        public FolderProvider(IPrinterPortReader printerPortReader, IPath path)
        {
            _printerPortReader = printerPortReader;
            _path = path;

            var tempFolderBase           = GetTempFolderBase();
            var localAppDataFolderBase   = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var roamingAppDataFolderBase = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            TempFolder = PathSafe.Combine(tempFolderBase, "Temp");
            _logger.Debug("Temp folder is '{0}'", TempFolder);

            SpoolFolder = PathSafe.Combine(tempFolderBase, "Spool");
            _logger.Debug("Spool folder is '{0}'", SpoolFolder);

            LocalAppDataFolder = PathSafe.Combine(localAppDataFolderBase, "pdfforge", "PDFCreator");
            _logger.Debug("LocalAppData folder is '{0}'", LocalAppDataFolder);

            RoamingAppDataFolder = PathSafe.Combine(roamingAppDataFolderBase, "pdfforge", "PDFCreator");
            _logger.Debug("RoamingAppData folder is '{0}'", RoamingAppDataFolder);
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     Create a new GhostscriptJob instance
        /// </summary>
        /// <param name="jobInfo">JobInfo of the job to convert</param>
        /// <param name="profile">Profile that determines the conversion process</param>
        /// <param name="tempFolder">TempFolderProvider that gives the full Temp path, i.e. C:\Users\Admin\Local Settings\Temp\PDFCreator</param>
        /// <param name="jobTranslations">Translations needed for the job</param>
        /// <param name="fileWrap">Only for testing</param>
        /// <param name="directoryWrap">Only for testing</param>
        public GhostscriptJob(IJobInfo jobInfo, ConversionProfile profile, JobTranslations jobTranslations, ITempFolderProvider tempFolder, IFile fileWrap, IDirectory directoryWrap)
            : base(jobInfo, profile, jobTranslations, fileWrap, directoryWrap)
        {
            var gsVersion = new GhostscriptDiscovery().GetBestGhostscriptInstance();

            if (gsVersion == null)
            {
                Logger.Error("No valid Ghostscript version found.");
                throw new InvalidOperationException("No valid Ghostscript version found.");
            }
            Logger.Debug("Ghostscript Version: " + gsVersion.Version + " loaded from " + gsVersion.ExePath);
            _ghostScript = new GhostScript(gsVersion);

            JobTempFolder       = PathSafe.Combine(tempFolder.TempFolder, "Job_" + PathSafe.GetFileNameWithoutExtension(PathSafe.GetRandomFileName()));
            JobTempOutputFolder = PathSafe.Combine(JobTempFolder, "tempoutput");
            DirectoryWrap.CreateDirectory(JobTempFolder);
            DirectoryWrap.CreateDirectory(JobTempOutputFolder);

            // Shorten the temp folder for GS compatibility
            JobTempFolder = PathHelper.GetShortPathName(JobTempFolder);
        }
Ejemplo n.º 11
0
        private void SetPdfXParameters(IList <string> parameters)
        {
            var shortenedTempPath = PathHelper.GetShortPathName(Job.JobTempFolder);

            parameters.Add("-dPDFX");

            Logger.Debug("Shortened Temppath from\r\n\"" + Job.JobTempFolder + "\"\r\nto\r\n\"" + shortenedTempPath + "\"");

            //Add ICC profile
            string iccFile = PathSafe.Combine(shortenedTempPath, "profile.icc");

            FileWrap.WriteAllBytes(iccFile, CoreResources.ISOcoated_v2_300_eci);
            parameters.Add("-sOutputICCProfile=\"" + iccFile + "\"");
            //parameters.Add("-dNOOUTERSAVE"); //Set in pdf-X example, but is not documented in the distiller parameters

            string defFile = PathSafe.Combine(shortenedTempPath, "pdfx_def.ps");
            var    sb      = new StringBuilder(CoreResources.PdfxDefinition);

            sb.Replace("%/ICCProfile (ISO Coated sb.icc)", "/ICCProfile (" + EncodeGhostscriptParametersOctal(iccFile.Replace('\\', '/')) + ")");
            FileWrap.WriteAllText(defFile, sb.ToString());
            parameters.Add(defFile);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Adds ellipsis to a path with a length longer than 255.
        /// </summary>
        /// <param name="filePath">full path to file</param>
        /// <param name="maxLength">maximum length of the string. This must be between 10 and MAX_PATH (260)</param>
        /// <returns>file path with ellipsis to ensure length under the max length </returns>
        public string EllipsisForFilename(string filePath, int maxLength)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (filePath.EndsWith("\\"))
            {
                throw new ArgumentException("The path has to be a file", nameof(filePath));
            }

            if (maxLength < 10 || maxLength > MAX_PATH)
            {
                throw new ArgumentException($"The desired length must be between 10 and {MAX_PATH}", nameof(maxLength));
            }

            if (filePath.Length > maxLength)
            {
                int minUsefulFileLength = 4;

                var directory = PathSafe.GetDirectoryName(filePath) ?? "";
                var file      = PathSafe.GetFileNameWithoutExtension(filePath);
                var extension = PathSafe.GetExtension(filePath);

                var remainingLengthForFile = maxLength - directory.Length - extension.Length - ELLIPSIS.Length - 1; // substract -1 to account for the slash between path and filename
                if (remainingLengthForFile < minUsefulFileLength)
                {
                    throw new ArgumentException("The path is too long", nameof(filePath)); //!
                }

                var partLength = remainingLengthForFile / 2;

                file     = file.Substring(0, partLength) + ELLIPSIS + file.Substring(file.Length - partLength, partLength);
                filePath = PathSafe.Combine(directory, file + extension);
            }

            return(filePath);
        }
Ejemplo n.º 13
0
        private void SetTempFolders(Job job)
        {
            job.JobTempFolder = PathSafe.Combine(_tempFolderProvider.TempFolder,
                                                 "Job_" + PathSafe.GetFileNameWithoutExtension(Path.GetRandomFileName()));
            _directory.CreateDirectory(job.JobTempFolder);
            job.JobTempOutputFolder = PathSafe.Combine(job.JobTempFolder, "tempoutput");
            _directory.CreateDirectory(job.JobTempOutputFolder);
            job.IntermediateFolder = PathSafe.Combine(job.JobTempFolder, "intermediate");
            _directory.CreateDirectory(job.IntermediateFolder);

            // Shorten the temp folder for GS compatibility
            job.JobTempFolder = PathHelper.GetShortPathName(job.JobTempFolder);
            //TODO remove this after upgrade to GS 9.19

            if (job.Profile.SaveFileTemporary)
            {
                var tempPath = PathSafe.Combine(_tempFolderProvider.TempFolder,
                                                "Job_tempsave_" + PathSafe.GetFileNameWithoutExtension(Path.GetRandomFileName()));

                job.OutputFileTemplate = PathSafe.Combine(tempPath, PathSafe.GetFileNameWithoutExtension(job.OutputFileTemplate));
            }
        }
Ejemplo n.º 14
0
        private void EmailExecute(object obj)
        {
            var tempDirectory = PathSafe.Combine(_tempFolderProvider.TempFolder,
                                                 Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

            Directory.CreateDirectory(tempDirectory);

            Job.OutputFileTemplate = PathSafe.Combine(tempDirectory, OutputFilename);

            if (!_interactiveProfileChecker.CheckWithErrorResultInOverlay(Job))
            {
                try
                {
                    Directory.Delete(tempDirectory);
                }
                catch { }
            }

            Job.Profile.EmailClientSettings.Enabled = true;
            Job.Profile.OpenViewer = false;

            CallFinishInteraction();
        }
Ejemplo n.º 15
0
        private bool CheckIfFileExistsElseNotifyUser()
        {
            var filePath = PathSafe.Combine(OutputFolder, OutputFilename);

            //Do not inform user, if SaveFileDialog already did
            if (filePath == _latestDialogFilePath)
            {
                return(true);
            }

            if (!_file.Exists(filePath))
            {
                return(true);
            }

            var title = Translation.ConfirmSaveAs.ToUpper(CultureInfo.CurrentCulture);
            var text  = Translation.GetFileAlreadyExists(filePath);

            var interaction = new MessageInteraction(text, title, MessageOptions.YesNo, MessageIcon.Exclamation);

            _interactionRequest.Raise(interaction, NotifyFileExistsCallback);

            return(false);
        }
Ejemplo n.º 16
0
 private void SetOutputFilePathInJob()
 {
     Job.OutputFileTemplate = PathSafe.Combine(OutputFolder, OutputFilename);
 }
Ejemplo n.º 17
0
 protected override void AddOutputfileParameter(IList <string> parameters)
 {
     parameters.Add("-sOutputFile=" + PathSafe.Combine(Job.IntermediateFolder, ComposeOutputFilename()));
 }
Ejemplo n.º 18
0
 public string GetCacheFilePath(string filename)
 {
     return(PathSafe.Combine(CacheDirectory, filename));
 }
Ejemplo n.º 19
0
        /// <summary>
        ///     Get the list of Ghostscript Parameters. This List contains of a basic set of parameters together with some
        ///     device-specific
        ///     parameters that will be added by the device implementation
        /// </summary>
        /// <param name="ghostscriptVersion"></param>
        /// <returns>A list of parameters that will be passed to Ghostscript</returns>
        public IList <string> GetGhostScriptParameters(GhostscriptVersion ghostscriptVersion)
        {
            IList <string> parameters = new List <string>();

            var outputFormatHelper = new OutputFormatHelper();

            parameters.Add("gs");
            parameters.Add("-I" + ghostscriptVersion.LibPaths);
            parameters.Add("-sFONTPATH=" + _osHelper.WindowsFontsFolder);

            parameters.Add("-dNOPAUSE");
            parameters.Add("-dBATCH");

            if (!outputFormatHelper.HasValidExtension(Job.OutputFileTemplate, Job.Profile.OutputFormat))
            {
                outputFormatHelper.EnsureValidExtension(Job.OutputFileTemplate, Job.Profile.OutputFormat);
            }

            AddOutputfileParameter(parameters);

            AddDeviceSpecificParameters(parameters);

            // Add user-defined parameters
            if (!string.IsNullOrEmpty(Job.Profile.Ghostscript.AdditionalGsParameters))
            {
                var args = _commandLineUtil.CommandLineToArgs(Job.Profile.Ghostscript.AdditionalGsParameters);
                foreach (var s in args)
                {
                    parameters.Add(s);
                }
            }

            //Dictonary-Parameters must be the last Parameters
            if (DistillerDictonaries.Count > 0)
            {
                parameters.Add("-c");
                foreach (var parameter in DistillerDictonaries)
                {
                    parameters.Add(parameter);
                }
            }

            //Don't add further paramters here, since the distiller-parameters should be the last!

            parameters.Add("-f");

            if (Job.Profile.Stamping.Enabled)
            {
                // Compose name of the stamp file based on the location and name of the inf file
                var stampFileName = PathSafe.Combine(Job.JobTempFolder,
                                                     PathSafe.GetFileNameWithoutExtension(Job.JobInfo.InfFile) + ".stm");
                CreateStampFile(stampFileName, Job.Profile, Job.TokenReplacer);
                parameters.Add(stampFileName);
            }

            SetCover(Job, parameters);

            foreach (var sfi in Job.JobInfo.SourceFiles)
            {
                parameters.Add(PathHelper.GetShortPathName(sfi.Filename));
            }

            SetAttachment(Job, parameters);

            // Compose name of the pdfmark file based on the location and name of the inf file
            var pdfMarkFileName = PathSafe.Combine(Job.JobTempFolder, "metadata.mtd");

            CreatePdfMarksFile(pdfMarkFileName);

            // Add pdfmark file as input file to set metadata
            parameters.Add(pdfMarkFileName);

            return(parameters);
        }
Ejemplo n.º 20
0
 protected virtual void AddOutputfileParameter(IList <string> parameters)
 {
     parameters.Add("-sOutputFile=" + PathSafe.Combine(PathHelper.GetShortPathName(Job.JobTempOutputFolder), ComposeOutputFilename()));
 }
Ejemplo n.º 21
0
        private string GetTempFolderBase()
        {
            var tempFolderName = ReadTempFolderName();

            return(PathSafe.Combine(_path.GetTempPath(), tempFolderName));
        }