/// <summary> /// Search for Ghostscript instances in the application folder /// </summary> /// <returns>A GhostscriptVersion if an internal instance exists, null otherwise</returns> public GhostscriptVersion FindInternalInstance() { string[] paths = { ApplicationPath }; foreach (var path in paths) { string dllPath; if (Environment.Is64BitOperatingSystem) { dllPath = _pathSafe.Combine(path, @"gsdll64.dll"); } else { dllPath = _pathSafe.Combine(path, @"gsdll32.dll"); } if (_file.Exists(dllPath)) { return(new GhostscriptVersion("<internal>", dllPath)); } } return(null); }
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"); string title = _translator.GetTranslation("Application", "RepairPrinterNoPrintersInstalled", "No printers installed"); string message = _translator.GetFormattedTranslation("Application", "RepairPrinterAskUser", "You do not have any PDFCreator printers installed. Most likely there was a problem during the setup or the installation has been altered afterwards.\r\nDo you want to fix this by reinstalling the PDFCreator printers?\r\n\r\nNote: You might be asked twice to grant admin privileges while fixing the problem."); Logger.Debug("Asking to start repair.."); if (MessageWindow.ShowTopMost(message, title, MessageWindowButtons.YesNo, MessageWindowIcon.Exclamation) == MessageWindowResponse.Yes) { var applicationPath = _assemblyHelper.GetCurrentAssemblyDirectory(); var printerHelperPath = _pathSafe.Combine(applicationPath, "PrinterHelper.exe"); if (!File.Exists(printerHelperPath)) { Logger.Error("PrinterHelper.exe does not exist!"); title = _translator.GetTranslation("Application", "Error", "Error"); message = _translator.GetFormattedTranslation("Application", "SetupFileMissing", "An important PDFCreator file is missing ('{0}'). Please reinstall PDFCreator!", _pathSafe.GetFileName(printerHelperPath)); MessageWindow.ShowTopMost(message, title, MessageWindowButtons.OK, MessageWindowIcon.Error); return(false); } var shellExecuteHelper = new ShellExecuteHelper(); Logger.Debug("Uninstalling Printers..."); var uninstallResult = shellExecuteHelper.RunAsAdmin(printerHelperPath, "/UninstallPrinter"); Logger.Debug("Done: {0}", uninstallResult); Logger.Debug("Reinstalling Printers..."); var pdfcreatorPath = _pathSafe.Combine(applicationPath, "PDFCreator.exe"); string printerNameString = GetPrinterNameString(printerNames); var installParams = $"/InstallPrinter {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.Info("The printer could not be repaired."); title = _translator.GetTranslation("Application", "Error", "Error"); message = _translator.GetFormattedTranslation("Application", "RepairPrinterFailed", "PDFCreator was not able to repair your printers. Please contact your administrator or the support to assist you in with this problem."); MessageWindow.ShowTopMost(message, title, MessageWindowButtons.OK, MessageWindowIcon.Exclamation); return(false); } Logger.Info("The printer was repaired successfully"); return(true); }
private static string CreateJobFolderInSpool(string psFile, string spoolFolder) { var psFilename = PathSafe.GetFileName(psFile); var jobFolder = PathSafe.Combine(spoolFolder, psFilename); jobFolder = new UniqueDirectory(jobFolder).MakeUniqueDirectory(); Directory.CreateDirectory(jobFolder); Logger.Trace("Created spool directory for ps-file job: " + jobFolder); return(jobFolder); }
public bool SendTestEmail(EmailClientSettings clientSettings) { var emailClient = _emailClientFactory.CreateEmailClient(); if (emailClient == null) { return(false); } var eMail = new Email(); var tokenReplacer = _tokenHelper.TokenReplacerWithPlaceHolders; clientSettings.Recipients = tokenReplacer.ReplaceTokens(clientSettings.Recipients); foreach (var recipient in clientSettings.Recipients.Replace(',', ';').Split(';')) { if (!string.IsNullOrWhiteSpace(recipient)) { eMail.To.Add(recipient.Trim()); } } eMail.Subject = tokenReplacer.ReplaceTokens(clientSettings.Subject); eMail.Html = clientSettings.Html; eMail.Body = tokenReplacer.ReplaceTokens(clientSettings.Content); if (clientSettings.AddSignature) { var signature = _mailSignatureHelper.ComposeMailSignature(); if (clientSettings.Html) { signature = signature.Replace(Environment.NewLine, "<br/>"); } eMail.Body += signature; } try { var tempFolder = _path.GetTempPath(); var tmpTestFolder = _pathSafe.Combine(tempFolder, "PDFCreator-Test\\SendSmtpTestmail"); _directory.CreateDirectory(tmpTestFolder); var tmpFile = _pathSafe.Combine(tmpTestFolder, "PDFCreator Mail Client Test.pdf"); _file.WriteAllText(tmpFile, ""); eMail.Attachments.Add(new Attachment(tmpFile)); emailClient.ShowEmailClient(eMail); } catch (Exception ex) { _logger.Warn(ex, "Exception while creating mail"); return(false); } return(true); }
public string ComposeTargetFileName(Job job) { if (!string.IsNullOrWhiteSpace(job.JobInfo.OutputFileParameter)) { if (_pathUtil.IsValidRootedPath(job.JobInfo.OutputFileParameter)) { return(job.JobInfo.OutputFileParameter); } } var tr = job.TokenReplacer; var outputFolder = ValidName.MakeValidFolderName(tr.ReplaceTokens(job.Profile.TargetDirectory)); var fileName = ComposeOutputFilename(job); var filePath = _pathSafe.Combine(outputFolder, fileName); if (!job.Profile.AutoSave.Enabled) { return(filePath); } try { filePath = _pathUtil.EllipsisForTooLongPath(filePath); _logger.Debug("FilePath after ellipsis: " + filePath); } catch (ArgumentException) { throw new WorkflowException("Filepath is only a directory or the directory itself is already too long to append a usefull filename under the limits of Windows (max " + _pathUtil.MAX_PATH + " characters): " + filePath); } return(filePath); }
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 = _translator.GetTranslation("Application", "RepairPrinterNoPrintersInstalled"); var message = _translator.GetTranslation("Application", "RepairPrinterAskUserUac"); Logger.Debug("Asking to start repair.."); var response = ShowMessage(message, title, MessageOptions.YesNo, MessageIcon.Exclamation); if (response == MessageResponse.Yes) { var applicationPath = _assemblyHelper.GetPdfforgeAssemblyDirectory(); var printerHelperPath = _pathSafe.Combine(applicationPath, "PrinterHelper.exe"); if (!_file.Exists(printerHelperPath)) { Logger.Error("PrinterHelper.exe does not exist!"); title = _translator.GetTranslation("Application", "Error"); message = _translator.GetFormattedTranslation("Application", "SetupFileMissing", _pathSafe.GetFileName(printerHelperPath)); ShowMessage(message, title, MessageOptions.OK, MessageIcon.Error); return(false); } Logger.Debug("Reinstalling Printers..."); var pdfcreatorPath = _pathSafe.Combine(applicationPath, "PDFCreator.exe"); var printerNameString = GetPrinterNameString(printerNames); var installParams = $"/RepairPrinter {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); }
private string DetermineOutfileBody() { var outputDir = PathSafe.GetDirectoryName(OutputFilenameTemplate) ?? ""; var filenameBase = PathSafe.GetFileNameWithoutExtension(OutputFilenameTemplate) ?? "output"; //var outfilebody = PathSafe.Combine(outputDir, filenameBase); return(PathSafe.Combine(outputDir, filenameBase)); }
public GhostscriptVersion GetGhostscriptInstance() { foreach (var path in GetPathCandidates()) { var testPath = _pathSafe.Combine(path, @"packages\setup\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); }
/// <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") + ';' + _pathSafe.Combine(path, @"Fonts"); if (_file.Exists(exePath)) { return(new GhostscriptVersion("<internal>", exePath, libPath)); } } return(null); }
public void SetLanguage(string languageName) { var applicationDir = _assemblyHelper.GetPdfforgeAssemblyDirectory(); var candidates = new[] { _pathSafe.Combine(applicationDir, $"PDFCreator_{languageName}.chm"), _pathSafe.Combine(applicationDir, "PDFCreator_english.chm") }; foreach (var candidate in candidates) { if (!_fileWrap.Exists(candidate)) { continue; } _userGuideLauncher.SetUserGuide(candidate); break; } }
public PrinterPort ReadPrinterPort(string portName) { var subKey = _pathSafe.Combine(RegistryBaseKey, portName); var key = _registry.LocalMachine.OpenSubKey(subKey); if (key == null) { return(null); } var printerPort = new PrinterPort(); try { printerPort.Name = portName; printerPort.Description = key.GetValue("Description").ToString(); printerPort.Program = key.GetValue("Program").ToString(); var portTypeString = key.GetValue("Type", "PS").ToString(); if (portTypeString.Equals("XPS", StringComparison.OrdinalIgnoreCase)) { printerPort.Type = PortType.Xps; } printerPort.TempFolderName = key.GetValue("TempFolderName", DefaultTempFolderName).ToString(); var serverValue = (int?)key.GetValue("Server"); if (serverValue == 1) { printerPort.IsServerPort = true; } if (string.IsNullOrWhiteSpace(printerPort.TempFolderName)) { printerPort.TempFolderName = DefaultTempFolderName; } var jobCounter = (int)key.GetValue("JobCounter", 0); printerPort.JobCounter = jobCounter; } catch (NullReferenceException) { printerPort = null; } key.Close(); return(printerPort); }
/// <summary> /// Creates a file path for a file 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>A unique filename</returns> public string CreateUniqueFileName() { while (UniqueCondition(LastUniqueFilename)) { LastUniqueFilename = _pathSafe.Combine(_directory, _fileBody + "_" + _appendix + _extension); _appendix++; if (LastUniqueFilename.Length > _pathUtil.MAX_PATH) { throw new PathTooLongException("Can not create useful unique filename for too long path: " + LastUniqueFilename); } } return(LastUniqueFilename); }
/// <summary> /// Creates a file path for a file 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>A unique filename</returns> public string CreateUniqueFileName() { while (UniqueCondition(LastUniqueFilename)) { LastUniqueFilename = _pathSafe.Combine(_directory, _fileBody + "_" + _appendix + _extension); _appendix++; if (LastUniqueFilename.Length > _pathUtil.MAX_PATH) { LastUniqueFilename = _pathUtil.EllipsisForTooLongPath(LastUniqueFilename); } } return(LastUniqueFilename); }
/// <summary> /// Creates a file path for a file 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>A unique filename</returns> public string CreateUniqueFileName() { while (_fileWrap.Exists(LastUniqueFilename) || _directoryWrap.Exists(LastUniqueFilename)) { LastUniqueFilename = _pathSafe.Combine(_directory, _fileBody + "_" + _appendix + _extension); _appendix++; if (LastUniqueFilename.Length > FileUtil.MAX_PATH) { LastUniqueFilename = FileUtil.Instance.EllipsisForTooLongPath(LastUniqueFilename); } } return(LastUniqueFilename); }
/// <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); }
private void StartDownload(string downloadUrl) { _webClient = new WebClient(); _webClient.DownloadProgressChanged += WebClientOnDownloadProgressChanged; _webClient.DownloadFileCompleted += WebClientOnDownloadFileCompleted; var uri = new Uri(downloadUrl); var filename = _pathSafe.GetFileName(uri.LocalPath); _downloadSpeed = new DownloadSpeed(_webClient); _downloadLocation = _tempFolderProvider.TempFolder; _directory.CreateDirectory(_downloadLocation); _downloadLocation = _pathSafe.Combine(_downloadLocation, filename); _webClient.DownloadFileAsync(uri, _downloadLocation); }
/// <summary> /// Search for Ghostscript instances in the application folder /// </summary> /// <returns>A GhostscriptVersion if an internal instance exists, null otherwise</returns> public GhostscriptVersion FindInternalInstance() { string[] paths = { _pathSafe.Combine(ApplicationPath, "Ghostscript"), _pathSafe.Combine(ApplicationPath, @"..\..\Ghostscript") }; foreach (string path in paths) { string exePath = _pathSafe.Combine(path, @"Bin\gswin32c.exe"); string libPath = _pathSafe.Combine(path, @"Bin") + ';' + _pathSafe.Combine(path, @"Lib") + ';' + _pathSafe.Combine(path, @"Fonts"); if (_file.Exists(exePath)) { return(new GhostscriptVersion("<internal>", exePath, libPath)); } } return(null); }
private string ComposeFilename(Job job) { var filePath = _targetFileNameComposer.ComposeTargetFileName(job); var folderName = _pathSafe.GetDirectoryName(filePath); if (string.IsNullOrEmpty(folderName)) { folderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } var filename = _pathSafe.GetFileName(filePath); if (string.IsNullOrEmpty(filename)) { filename = "document.pdf"; } return(_pathSafe.Combine(folderName, filename)); }
/// <summary> /// Adds ellipsis "(...)" to a path with a length longer than 255. /// </summary> /// <param name="filePath">full path to file</param> /// <param name="length">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 EllipsisForPath(string filePath, int length) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } if (filePath.EndsWith("\\")) { throw new ArgumentException("The path has to be a file", nameof(filePath)); } if ((length < 10) || (length > MAX_PATH)) { throw new ArgumentException($"The desired length must be between 10 and {MAX_PATH}", nameof(length)); } if (filePath.Length > length) { const string ellipsis = "(...)"; var path = GetLongDirectoryName(filePath) ?? ""; var file = _pathSafe.GetFileNameWithoutExtension(filePath); var ext = _pathSafe.GetExtension(filePath); var remainingLength = length - path.Length - ellipsis.Length - ext.Length - 1; // substract -1 to account for the slash between path and filename if (remainingLength < 4) { throw new ArgumentException(filePath); } var partLength = remainingLength / 2; file = file.Substring(0, partLength) + ellipsis + file.Substring(file.Length - partLength, partLength); filePath = _pathSafe.Combine(path, file + ext); } return(filePath); }
protected override void QueryTargetFile() { if (!Job.Profile.SkipPrintDialog) { Job.ApplyMetadata(); var w = new PrintJobWindow(); var model = new PrintJobViewModel(Job.JobInfo, Job.Profile); w.DataContext = model; if ((TopMostHelper.ShowDialogTopMost(w, true) != true) || model.PrintJobAction == PrintJobAction.Cancel) { Cancel = true; WorkflowStep = WorkflowStep.AbortedByUser; return; } if (model.PrintJobAction == PrintJobAction.ManagePrintJobs) { throw new ManagePrintJobsException(); } Job.Profile = model.SelectedProfile.Copy(); Job.ApplyMetadata(); if (model.PrintJobAction == PrintJobAction.EMail) { Job.SkipSaveFileDialog = true; Job.Profile.EmailClient.Enabled = true; Job.Profile.AutoSave.Enabled = false; Job.Profile.OpenViewer = false; } } if (Job.SkipSaveFileDialog) { ITempFolderProvider tempFolderProvider = JobInfoQueue.Instance; var sendFilesFolder = _pathSafe.Combine(tempFolderProvider.TempFolder, "Job" + Job.JobInfo.SourceFiles[0].JobId + "_SendFiles"); Directory.CreateDirectory(sendFilesFolder); var filePath = _pathSafe.Combine(sendFilesFolder, Job.ComposeOutputFilename()); filePath = FileUtil.Instance.EllipsisForTooLongPath(filePath); Job.OutputFilenameTemplate = filePath; } else { var saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = _translator.GetTranslation("InteractiveWorkflow", "SelectDestination", "Select destination"); saveFileDialog.Filter = _translator.GetTranslation("InteractiveWorkflow", "PdfFile", "PDF file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfA1bFile", "PDF/A-1b file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfA2bFile", "PDF/A-2b file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfXFile", "PDF/X file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "JpegFile", "JPEG file") + @" (*.jpg)|*.jpg;*.jpeg;"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PngFile", "PNG file") + @" (*.png)|*.png;"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "TiffFile", "TIFF file") + @" (*.tif)|*.tif;*.tiff"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "TextFile", "Text file") + @" (*.txt)|*.txt;"; saveFileDialog.FilterIndex = ((int)Job.Profile.OutputFormat) + 1; saveFileDialog.OverwritePrompt = true; if (Job.Profile.SaveDialog.SetDirectory) { var saveDirectory = FileUtil.Instance.MakeValidFolderName(Job.TokenReplacer.ReplaceTokens(Job.Profile.SaveDialog.Folder)); DirectoryHelper = new DirectoryHelper(saveDirectory); if (DirectoryHelper.CreateDirectory()) { saveFileDialog.RestoreDirectory = true; saveFileDialog.InitialDirectory = saveDirectory; Logger.Debug("Set directory in save file dialog: " + saveDirectory); } else { Logger.Warn("Could not create directory for save file dialog. It will be opened with default save location."); } } Cancel = !LaunchSaveFileDialog(saveFileDialog); } }
/// <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>(); parameters.Add("gs"); parameters.Add("-sFONTPATH=" + OsHelper.WindowsFontsFolder); parameters.Add("-dNOPAUSE"); parameters.Add("-dBATCH"); if (!HasValidExtension(Job.OutputFilenameTemplate, Job.Profile.OutputFormat)) { MakeValidExtension(Job.OutputFilenameTemplate, Job.Profile.OutputFormat); } AddOutputfileParameter(parameters); AddDeviceSpecificParameters(parameters); // Add user-defined parameters if (!string.IsNullOrEmpty(Job.Profile.Ghostscript.AdditionalGsParameters)) { var args = FileUtil.Instance.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); parameters.Add(stampFileName); } if (Job.Profile.CoverPage.Enabled) { parameters.Add(Job.Profile.CoverPage.File); } foreach (var sfi in Job.JobInfo.SourceFiles) { parameters.Add(sfi.Filename); } if (Job.Profile.AttachmentPage.Enabled) { parameters.Add(Job.Profile.AttachmentPage.File); } //Compose name of the pdfmark file based on the location and name of the inf file var pdfMarkFileName = PathSafe.Combine(Job.JobTempFolder, "metadata.mtd"); Directory.CreateDirectory(Job.JobTempFolder); Directory.CreateDirectory(Job.JobTempFolder + @"\tempoutput"); CreatePdfMarksFile(pdfMarkFileName); // Add pdfmark file as input file to set metadata parameters.Add(pdfMarkFileName); return(parameters); }