Conversão de PDF para PostScript
O seguinte trecho de código também funciona com a biblioteca Aspose.PDF.Drawing .
PDF Para Postscript em C#
A classe PdfViewer fornece a capacidade de imprimir documentos PDF e, com a ajuda dessa classe, também podemos converter arquivos PDF para o formato PostScript. Para converter um arquivo PDF em PostScript, primeiro instale qualquer impressora PS e apenas imprima para arquivo com a ajuda do PdfViewer. Para instalar uma impressora PS, consulte as instruções fornecidas pelo fornecedor da sua impressora. O seguinte trecho de código mostra como imprimir e converter um PDF para o formato PostScript.
Verificando o Status do Trabalho de Impressão
Um arquivo PDF pode ser impresso em uma impressora física, bem como no Microsoft XPS Document Writer, sem mostrar uma caixa de diálogo de impressão, usando a classe PdfViewer . Ao imprimir arquivos PDF grandes, o processo pode demorar um pouco, então o usuário pode não ter certeza se o processo de impressão foi concluído ou encontrou um problema. Para determinar o status de um trabalho de impressão, use a propriedade PrintStatus . O seguinte trecho de código mostra como imprimir o arquivo PDF em um arquivo XPS e obter o status da impressão.
.NET Core 3.1
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void CheckingPrintJobStatus ()
{
// The path to the documents directory
var dataDir = RunExamples . GetDataDir_AsposePdfFacades_Printing ();
// Instantiate PdfViewer object
using ( var viewer = new Aspose . Pdf . Facades . PdfViewer ())
{
// Bind PDF document
viewer . BindPdf ( dataDir + "PrintDocument.pdf" );
// Print the file with adjusted size
viewer . AutoResize = true ;
// Hide printing dialog
viewer . PrintPageDialog = false ;
// Create Printer Settings object
var ps = new Aspose . Pdf . Printing . PrinterSettings ();
var pgs = new Aspose . Pdf . Printing . PageSettings ();
// Specify the printer name
ps . PrinterName = "Microsoft XPS Document Writer" ;
// Resultant Printout name
ps . PrintFileName = dataDir + "CheckingPrintJobStatus_out.xps" ;
// Print the output to file
ps . PrintToFile = true ;
// Set a range of pages to print
ps . FromPage = 1 ;
ps . ToPage = 2 ;
ps . PrintRange = Aspose . Pdf . Printing . PrintRange . SomePages ;
// Specify the page size of printout
pgs . PaperSize = Aspose . Pdf . Printing . PaperSizes . A4 ;
ps . DefaultPageSettings . PaperSize = pgs . PaperSize ;
// Specify page margins
pgs . Margins = new Aspose . Pdf . Devices . Margins ( 0 , 0 , 0 , 0 );
// Print the document with settings specified above
viewer . PrintDocumentWithSettings ( pgs , ps );
// Check the print status
if ( viewer . PrintStatus != null )
{
// An exception was thrown
if ( viewer . PrintStatus is Exception ex )
{
// Get exception message
Console . WriteLine ( ex . Message );
}
}
else
{
// No errors were found. Printing job has completed successfully
Console . WriteLine ( "Printing completed without any issue." );
}
}
}
.NET 8
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void CheckingPrintJobStatus ()
{
// The path to the documents directory
var dataDir = RunExamples . GetDataDir_AsposePdfFacades_Printing ();
// Instantiate PdfViewer object
using var viewer = new Aspose . Pdf . Facades . PdfViewer ();
// Bind PDF document
viewer . BindPdf ( dataDir + "PrintDocument.pdf" );
// Print the file with adjusted size
viewer . AutoResize = true ;
// Hide printing dialog
viewer . PrintPageDialog = false ;
// Create Printer Settings object
var ps = new Aspose . Pdf . Printing . PrinterSettings ();
var pgs = new Aspose . Pdf . Printing . PageSettings ();
// Specify the printer name
ps . PrinterName = "Microsoft XPS Document Writer" ;
// Resultant Printout name
ps . PrintFileName = dataDir + "CheckingPrintJobStatus_out.xps" ;
// Print the output to file
ps . PrintToFile = true ;
// Set a range of pages to print
ps . FromPage = 1 ;
ps . ToPage = 2 ;
ps . PrintRange = Aspose . Pdf . Printing . PrintRange . SomePages ;
// Specify the page size of printout
pgs . PaperSize = Aspose . Pdf . Printing . PaperSizes . A4 ;
ps . DefaultPageSettings . PaperSize = pgs . PaperSize ;
// Specify page margins
pgs . Margins = new Aspose . Pdf . Devices . Margins ( 0 , 0 , 0 , 0 );
// Print the document with settings specified above
viewer . PrintDocumentWithSettings ( pgs , ps );
// Check the print status
if ( viewer . PrintStatus != null )
{
// An exception was thrown
if ( viewer . PrintStatus is Exception ex )
{
// Get exception message
Console . WriteLine ( ex . Message );
}
}
else
{
// No errors were found. Printing job has completed successfully
Console . WriteLine ( "Printing completed without any issue." );
}
}
Obter/Definir Nome do Proprietário do Trabalho de Impressão
Às vezes, há a necessidade de obter ou definir o nome do proprietário do trabalho de impressão (ou seja, o usuário real que pressionou o botão de impressão em uma página da web). Essa informação é necessária ao imprimir o arquivo PDF. Para atender a essa necessidade, a propriedade PrinterJobName é utilizada.
Usando Impersonação
Outra abordagem para obter o nome do proprietário do trabalho de impressão é usar impersonação (executar rotinas de impressão em outro contexto de usuário) ou o usuário pode alterar o nome do proprietário diretamente usando a rotina SetJob.
Por favor, note que não há possibilidade de definir o valor do proprietário usando a API de impressão Aspose.PDF por considerações de segurança. A propriedade PrinterJobName pode ser usada para definir o valor da coluna do nome do documento na aplicação de impressão spooler. O trecho de código compartilhado acima apenas mostra como o usuário pode juntar o nome do usuário na coluna do nome do documento (por exemplo, usando a sintaxe UserName\documentName). Mas a configuração das colunas do Proprietário pode ser implementada das seguintes maneiras diretamente pelo usuário:
Impersonação. Como o valor da coluna do proprietário contém o valor do usuário que executa o código de impressão, há uma maneira de invocar a API de impressão Aspose.PDF dentro de outro contexto de usuário. Por exemplo, veja a solução descrita aqui. Usando esta classe Impersonator , o usuário pode alcançar o objetivo:
Usando a API Spooler e a rotina SetJob
O seguinte trecho de código mostra como imprimir algumas páginas de um arquivo PDF em modo Simples e algumas páginas em modo Duplex.
.NET Core 3.1
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
struct PrintingJobSettings
{
public int ToPage { get ; set ; }
public int FromPage { get ; set ; }
public string OutputFile { get ; set ; }
public Aspose . Pdf . Printing . Duplex Mode { get ; set ; }
}
private static void PrintUsingSpoolerApi ()
{
// The path to the documents directory
var dataDir = RunExamples . GetDataDir_AsposePdfFacades_Printing ();
int printingJobIndex = 0 ;
string outputDir = dataDir ;
var printingJobs = new List < PrintingJobSettings >();
// Create multiple printing jobs to print different page ranges with different duplex settings
var printingJob1 = new PrintingJobSettings ();
printingJob1 . FromPage = 1 ;
printingJob1 . ToPage = 3 ;
printingJob1 . OutputFile = outputDir + "PrintUsingSpoolerApi_p1-3_out.xps" ;
printingJob1 . Mode = Aspose . Pdf . Printing . Duplex . Default ;
printingJobs . Add ( printingJob1 );
PrintingJobSettings printingJob2 = new PrintingJobSettings ();
printingJob2 . FromPage = 4 ;
printingJob2 . ToPage = 6 ;
printingJob2 . OutputFile = outputDir + "PrintUsingSpoolerApi_p4-6_out.xps" ;
printingJob2 . Mode = Aspose . Pdf . Printing . Duplex . Simplex ;
printingJobs . Add ( printingJob2 );
PrintingJobSettings printingJob3 = new PrintingJobSettings ();
printingJob3 . FromPage = 7 ;
printingJob3 . ToPage = 7 ;
printingJob3 . OutputFile = outputDir + "PrintUsingSpoolerApi_p7_out.xps" ;
printingJob3 . Mode = Aspose . Pdf . Printing . Duplex . Default ;
printingJobs . Add ( printingJob3 );
// Create PdfViewer object
using ( var viewer = new Aspose . Pdf . Facades . PdfViewer ())
{
// Bind PDF document
viewer . BindPdf ( dataDir + "Print-PageRange.pdf" );
// Set attributes for printing
// Print the file with adjusted size
viewer . AutoResize = true ;
// Print the file with adjusted rotation
viewer . AutoRotate = true ;
// Do not produce the page number dialog when printing
viewer . PrintPageDialog = false ;
// Create objects for printer and page settings
var ps = new Aspose . Pdf . Printing . PrinterSettings ();
var pgs = new Aspose . Pdf . Printing . PageSettings ();
// Set printer name
ps . PrinterName = "Microsoft XPS Document Writer" ;
// Set output file name and PrintToFile attribute
ps . PrintFileName = Path . GetFullPath ( printingJobs [ printingJobIndex ]. OutputFile );
ps . PrintToFile = true ;
// Set parameters for the first print job
ps . FromPage = printingJobs [ printingJobIndex ]. FromPage ;
ps . ToPage = printingJobs [ printingJobIndex ]. ToPage ;
ps . Duplex = printingJobs [ printingJobIndex ]. Mode ;
ps . PrintRange = Aspose . Pdf . Printing . PrintRange . SomePages ;
// Set paper size and margins
pgs . PaperSize = Aspose . Pdf . Printing . PaperSizes . A4 ;
ps . DefaultPageSettings . PaperSize = pgs . PaperSize ;
pgs . Margins = new Aspose . Pdf . Devices . Margins ( 0 , 0 , 0 , 0 );
// Chain other print jobs at the end of the finished job
viewer . EndPrint += ( sender , args ) =>
{
if (++ printingJobIndex < printingJobs . Count )
{
// Set the next print job parameters
ps . PrintFileName = Path . GetFullPath ( printingJobs [ printingJobIndex ]. OutputFile );
ps . FromPage = printingJobs [ printingJobIndex ]. FromPage ;
ps . ToPage = printingJobs [ printingJobIndex ]. ToPage ;
ps . Duplex = printingJobs [ printingJobIndex ]. Mode ;
// Run the next print job
viewer . PrintDocumentWithSettings ( pgs , ps );
}
};
// Run the first print job
viewer . PrintDocumentWithSettings ( pgs , ps );
}
}
.NET 8
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
struct PrintingJobSettings
{
public int ToPage { get ; set ; }
public int FromPage { get ; set ; }
public string OutputFile { get ; set ; }
public Aspose . Pdf . Printing . Duplex Mode { get ; set ; }
}
private static void PrintUsingSpoolerApi ()
{
// The path to the documents directory
var dataDir = RunExamples . GetDataDir_AsposePdfFacades_Printing ();
int printingJobIndex = 0 ;
var printingJobs = new List < PrintingJobSettings >();
// Create multiple printing jobs to print different page ranges with different duplex settings
var printingJob1 = new PrintingJobSettings ();
printingJob1 . FromPage = 1 ;
printingJob1 . ToPage = 3 ;
printingJob1 . OutputFile = dataDir + "PrintUsingSpoolerApi_p1-3_out.xps" ;
printingJob1 . Mode = Aspose . Pdf . Printing . Duplex . Default ;
printingJobs . Add ( printingJob1 );
PrintingJobSettings printingJob2 = new PrintingJobSettings ();
printingJob2 . FromPage = 4 ;
printingJob2 . ToPage = 6 ;
printingJob2 . OutputFile = dataDir + "PrintUsingSpoolerApi_p4-6_out.xps" ;
printingJob2 . Mode = Aspose . Pdf . Printing . Duplex . Simplex ;
printingJobs . Add ( printingJob2 );
PrintingJobSettings printingJob3 = new PrintingJobSettings ();
printingJob3 . FromPage = 7 ;
printingJob3 . ToPage = 7 ;
printingJob3 . OutputFile = dataDir + "PrintUsingSpoolerApi_p7_out.xps" ;
printingJob3 . Mode = Aspose . Pdf . Printing . Duplex . Default ;
printingJobs . Add ( printingJob3 );
// Create PdfViewer object
using var viewer = new Aspose . Pdf . Facades . PdfViewer ();
// Bind PDF document
viewer . BindPdf ( dataDir + "Print-PageRange.pdf" );
// Set attributes for printing
// Print the file with adjusted size
viewer . AutoResize = true ;
// Print the file with adjusted rotation
viewer . AutoRotate = true ;
// Do not produce the page number dialog when printing
viewer . PrintPageDialog = false ;
// Create objects for printer and page settings
var ps = new Aspose . Pdf . Printing . PrinterSettings ();
var pgs = new Aspose . Pdf . Printing . PageSettings ();
// Set printer name
ps . PrinterName = "Microsoft XPS Document Writer" ;
// Set output file name and PrintToFile attribute
ps . PrintFileName = Path . GetFullPath ( printingJobs [ printingJobIndex ]. OutputFile );
ps . PrintToFile = true ;
// Set parameters for the first print job
ps . FromPage = printingJobs [ printingJobIndex ]. FromPage ;
ps . ToPage = printingJobs [ printingJobIndex ]. ToPage ;
ps . Duplex = printingJobs [ printingJobIndex ]. Mode ;
ps . PrintRange = Aspose . Pdf . Printing . PrintRange . SomePages ;
// Set paper size and margins
pgs . PaperSize = Aspose . Pdf . Printing . PaperSizes . A4 ;
ps . DefaultPageSettings . PaperSize = pgs . PaperSize ;
pgs . Margins = new Aspose . Pdf . Devices . Margins ( 0 , 0 , 0 , 0 );
// Chain other print jobs at the end of the finished job
viewer . EndPrint += ( sender , args ) =>
{
if (++ printingJobIndex < printingJobs . Count )
{
// Set the next print job parameters
ps . PrintFileName = Path . GetFullPath ( printingJobs [ printingJobIndex ]. OutputFile );
ps . FromPage = printingJobs [ printingJobIndex ]. FromPage ;
ps . ToPage = printingJobs [ printingJobIndex ]. ToPage ;
ps . Duplex = printingJobs [ printingJobIndex ]. Mode ;
// Run the next print job
viewer . PrintDocumentWithSettings ( pgs , ps );
}
};
// Run the first print job
viewer . PrintDocumentWithSettings ( pgs , ps );
}