Есть ли способ получить доступ к причине каждый раз, когда я выполняю это, статус задания — PrintJobStatus.Deleted? Это всегда происходит при печати чего-либо или это ошибка?
using System;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
namespace PrintTest
{
class Program
{
static void Main(string[] args)
{
try
{
// Definir la ruta del archivo a imprimir
string filePath = @"C:\Downloads\prueba.pdf";
// Verificar si el archivo existe
if (!File.Exists(filePath))
{
Console.WriteLine("El archivo no existe.");
return;
}
// Leer el contenido del archivo
string textToPrint = File.ReadAllText(filePath);
Console.WriteLine("Archivo leído correctamente.");
// Llamar al método estático GetDefaultPrintQueue directamente desde LocalPrintServer
PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
Console.WriteLine("Impresora predeterminada obtenida.");
// Verificar si la impresora está en línea
if (defaultPrintQueue.IsOffline)
{
Console.WriteLine("La impresora está fuera de línea. Asegúrate de que esté encendida y conectada.");
return;
}
// Verificar si la impresora tiene errores
if (defaultPrintQueue.IsBusy)
{
Console.WriteLine("La impresora está ocupada. Espera a que termine el trabajo anterior.");
return;
}
// Verificar si hay trabajos en la cola que puedan indicar un error
if (defaultPrintQueue.GetPrintJobInfoCollection().Count() > 0)
{
Console.WriteLine("Hay trabajos en la cola de impresión. Esperando a que se libere.");
return;
}
// Crear un trabajo de impresión en la cola predeterminada
PrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob("Impresión de archivo");
Console.WriteLine("Trabajo de impresión agregado a la cola.");
// Escribir en el flujo del trabajo de impresión
Stream myStream = myPrintJob.JobStream;
byte[] myByteBuffer = Encoding.Unicode.GetBytes(textToPrint);
// Escribir los datos en el flujo del trabajo de impresión
myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
myStream.Close();
// Verificar el estado del trabajo de impresión
CheckPrintJobStatus(myPrintJob);
Console.WriteLine("Trabajo de impresión enviado correctamente.");
// Esperar una tecla antes de cerrar
Console.WriteLine("Presiona cualquier tecla para salir...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("Error al crear el trabajo de impresión: " + ex.Message);
}
}
// Método para verificar el estado del trabajo de impresión
static void CheckPrintJobStatus(PrintSystemJobInfo printJob)
{
try
{
// Obtener el estado del trabajo de impresión
printJob.Refresh(); // Actualiza el estado del trabajo de impresión
// Imprimir varios atributos para obtener más detalles
Console.WriteLine($"Job ID: {printJob.JobIdentifier}");
Console.WriteLine($"Estado del trabajo: {printJob.JobStatus}");
// Verificar el estado del trabajo
switch (printJob.JobStatus)
{
case PrintJobStatus.Completed:
Console.WriteLine("El trabajo de impresión se completó correctamente.");
break;
case PrintJobStatus.Paused:
Console.WriteLine("El trabajo de impresión está en pausa.");
break;
case PrintJobStatus.Error:
Console.WriteLine("Hubo un error durante el proceso de impresión.");
break;
case PrintJobStatus.Deleted:
Console.WriteLine("El documento ha sido borrado.");
break;
default:
Console.WriteLine($"El trabajo de impresión está en estado: {printJob.JobStatus}");
break;
}
}
catch (IOException ioEx)
{
Console.WriteLine($"Error de entrada/salida: {ioEx.Message}");
}
catch (InvalidOperationException invalidOpEx)
{
Console.WriteLine($"Error de operación no válida: {invalidOpEx.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error inesperado: {ex.Message}");
}
}
}
}
Я хочу знать, как узнать, есть ли в принтере бумага и чернила. Я попытался отправить его на принтер в поисках ошибки, но не могу продолжить
Есть ли способ получить доступ к причине каждый раз, когда я выполняю это, статус задания — PrintJobStatus.Deleted? Это всегда происходит при печати чего-либо или это ошибка? [code]using System; using System.IO; using System.Linq; using System.Printing; using System.Text;
namespace PrintTest { class Program { static void Main(string[] args) { try { // Definir la ruta del archivo a imprimir string filePath = @"C:\Downloads\prueba.pdf";
// Verificar si el archivo existe if (!File.Exists(filePath)) { Console.WriteLine("El archivo no existe."); return; }
// Leer el contenido del archivo string textToPrint = File.ReadAllText(filePath); Console.WriteLine("Archivo leído correctamente.");
// Llamar al método estático GetDefaultPrintQueue directamente desde LocalPrintServer PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); Console.WriteLine("Impresora predeterminada obtenida.");
// Verificar si la impresora está en línea if (defaultPrintQueue.IsOffline) { Console.WriteLine("La impresora está fuera de línea. Asegúrate de que esté encendida y conectada."); return; }
// Verificar si la impresora tiene errores if (defaultPrintQueue.IsBusy) { Console.WriteLine("La impresora está ocupada. Espera a que termine el trabajo anterior."); return; }
// Verificar si hay trabajos en la cola que puedan indicar un error if (defaultPrintQueue.GetPrintJobInfoCollection().Count() > 0) { Console.WriteLine("Hay trabajos en la cola de impresión. Esperando a que se libere."); return; }
// Crear un trabajo de impresión en la cola predeterminada PrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob("Impresión de archivo"); Console.WriteLine("Trabajo de impresión agregado a la cola.");
// Escribir en el flujo del trabajo de impresión Stream myStream = myPrintJob.JobStream; byte[] myByteBuffer = Encoding.Unicode.GetBytes(textToPrint);
// Escribir los datos en el flujo del trabajo de impresión myStream.Write(myByteBuffer, 0, myByteBuffer.Length); myStream.Close();
// Verificar el estado del trabajo de impresión CheckPrintJobStatus(myPrintJob);
Console.WriteLine("Trabajo de impresión enviado correctamente.");
// Esperar una tecla antes de cerrar Console.WriteLine("Presiona cualquier tecla para salir..."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("Error al crear el trabajo de impresión: " + ex.Message); } }
// Método para verificar el estado del trabajo de impresión static void CheckPrintJobStatus(PrintSystemJobInfo printJob) { try { // Obtener el estado del trabajo de impresión printJob.Refresh(); // Actualiza el estado del trabajo de impresión
// Imprimir varios atributos para obtener más detalles Console.WriteLine($"Job ID: {printJob.JobIdentifier}"); Console.WriteLine($"Estado del trabajo: {printJob.JobStatus}");
// Verificar el estado del trabajo switch (printJob.JobStatus) { case PrintJobStatus.Completed: Console.WriteLine("El trabajo de impresión se completó correctamente."); break; case PrintJobStatus.Paused: Console.WriteLine("El trabajo de impresión está en pausa."); break; case PrintJobStatus.Error: Console.WriteLine("Hubo un error durante el proceso de impresión."); break; case PrintJobStatus.Deleted: Console.WriteLine("El documento ha sido borrado."); break; default: Console.WriteLine($"El trabajo de impresión está en estado: {printJob.JobStatus}"); break; } } catch (IOException ioEx) { Console.WriteLine($"Error de entrada/salida: {ioEx.Message}"); } catch (InvalidOperationException invalidOpEx) { Console.WriteLine($"Error de operación no válida: {invalidOpEx.Message}"); } catch (Exception ex) { Console.WriteLine($"Error inesperado: {ex.Message}"); } } } } [/code] Я хочу знать, как узнать, есть ли в принтере бумага и чернила. Я попытался отправить его на принтер в поисках ошибки, но не могу продолжить
Проблема в том, что когда я использую System.Drawing.Printing, я получаю сообщение об ошибке при инициализации PrinterSettings, которое должно находиться внутри System.Drawing.Printing. Это проект с .NET Framework 4.7.2 .
Сообщение об ошибке:...
Я создал приложение C# для редактирования страницы и ее печати, а также сохранения в формате PDF. У меня возникла проблема с отображением изображения на странице. Ниже приведен снимок экрана с элементами управления моего приложения:
У меня возникла следующая проблема при использовании бета-версии Visual Studio 2010 Team System Beta 1:
Во время работы над кодом печати я попытался объявить переменную типа System.Printing. PrintTicket, но Visual Studio, похоже, не распознает...
Я работаю над приложением, в котором мне нужно отслеживать задания на печать. Он работал над примером проекта WinForms, но не работал в проекте WPF.
void pqm_OnJobStatusChange(object Sender, PrintJobChangeEventArgs e)
{
try
{
PrintSystemJobInfo job...