javax.print.SimpleDoc Java Examples

The following examples show how to use javax.print.SimpleDoc. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Java14PrintUtilTest.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testPrintDirectly() throws Exception {
  MasterReport report = mockReport( PageFormat.LANDSCAPE );
  PrintService printService = mock( PrintService.class );
  DocPrintJob job = mock( DocPrintJob.class );

  ArgumentCaptor<SimpleDoc> docCaptor = ArgumentCaptor.forClass( SimpleDoc.class );
  ArgumentCaptor<PrintRequestAttributeSet> attrsCaptor = ArgumentCaptor.forClass( PrintRequestAttributeSet.class );

  doReturn( true ).when( printService ).isDocFlavorSupported( DocFlavor.SERVICE_FORMATTED.PAGEABLE );
  doReturn( job ).when( printService ).createPrintJob();
  doNothing().when( job ).print( docCaptor.capture(), attrsCaptor.capture() );

  Java14PrintUtil.printDirectly( report, printService );

  verify( job ).print( any( SimpleDoc.class ), any( PrintRequestAttributeSet.class ) );
  assertThat( docCaptor.getValue().getPrintData(), is( instanceOf( PrintReportProcessor.class ) ) );
  assertThat( docCaptor.getValue().getDocFlavor(), is( instanceOf( DocFlavor.SERVICE_FORMATTED.class ) ) );
  assertThat( attrsCaptor.getValue().size(), is( equalTo( 5 ) ) );
}
 
Example #2
Source File: PrintImageOutput.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public static boolean out(BufferedImage image) {
	try {
		DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
		PrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet();
		requestAttributeSet.add(MediaSizeName.ISO_A4);
		requestAttributeSet.add(new JobName(LSystem.applicationName + LSystem.getTime(), Locale.ENGLISH));
		PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, requestAttributeSet);
		PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
		PrintService service = ServiceUI.printDialog(null, 100, 100, services, defaultService, flavor,
				requestAttributeSet);
		if (service != null) {
			DocPrintJob job = service.createPrintJob();
			SimpleDoc doc = new SimpleDoc(new BufferedImagePrintable(image), flavor, null);
			job.print(doc, requestAttributeSet);
		}
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example #3
Source File: PrinterOutputStream.java    From escpos-coffee with MIT License 6 votes vote down vote up
/**
 * creates one instance of PrinterOutputStream.
 * <p>
 * Create one print based on print service. Start print job linked (this)
 * output stream.
 *
 * @param printService value used to create the printer job
 * @exception IOException if an I/O error occurs.
 * @see #getPrintServiceByName(java.lang.String)
 * @see #getDefaultPrintService()
 */
public PrinterOutputStream(PrintService printService) throws IOException {

    UncaughtExceptionHandler uncaughtException = (Thread t, Throwable e) -> {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(),e);
    };

    pipedInputStream = new PipedInputStream();
    super.connect(pipedInputStream);

    Runnable runnablePrint = () -> {
        try {
            DocFlavor df = DocFlavor.INPUT_STREAM.AUTOSENSE;
            Doc d = new SimpleDoc(pipedInputStream, df, null);

            DocPrintJob job = printService.createPrintJob();
            job.print(d, null);
        } catch (PrintException ex) {
            throw new RuntimeException(ex);
        }
    };

    threadPrint = new Thread(runnablePrint);
    threadPrint.setUncaughtExceptionHandler(uncaughtException);
    threadPrint.start();
}
 
Example #4
Source File: PrintSEUmlauts.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #5
Source File: Java14PrintUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean print( final MasterReport report, final ReportProgressListener progressListener )
  throws PrintException, ReportProcessingException {
  final PrintService[] services = PrintServiceLookup.lookupPrintServices( DocFlavor.SERVICE_FORMATTED.PAGEABLE, null );
  if ( services.length == 0 ) {
    throw new PrintException( "Unable to find a matching print service implementation." );
  }
  PrintRequestAttributeSet attributes = Java14PrintUtil.copyConfiguration( null, report );
  attributes = Java14PrintUtil.copyAuxillaryAttributes( attributes, report );

  final PrintService service =
      ServiceUI.printDialog( null, 50, 50, services, lookupPrintService(), DocFlavor.SERVICE_FORMATTED.PAGEABLE,
          attributes );
  if ( service == null ) {
    return false;
  }

  final PrintReportProcessor reportPane = new PrintReportProcessor( report );
  if ( progressListener != null ) {
    reportPane.addReportProgressListener( progressListener );
  }

  try {
    reportPane.fireProcessingStarted();

    final DocPrintJob job = service.createPrintJob();
    final SimpleDoc document = new SimpleDoc( reportPane, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null );

    job.print( document, attributes );
  } finally {
    reportPane.fireProcessingFinished();
    reportPane.close();

    if ( progressListener != null ) {
      reportPane.removeReportProgressListener( progressListener );
    }
  }
  return true;
}
 
Example #6
Source File: Java14PrintUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void printDirectly( final MasterReport report, PrintService printService ) throws PrintException,
  ReportProcessingException {
  // with that method we do not use the PrintService UI ..
  // it is up to the user to supply a valid print service that
  // supports the Pageable printing.
  if ( printService == null ) {
    printService = lookupPrintService();
  } else {
    if ( printService.isDocFlavorSupported( DocFlavor.SERVICE_FORMATTED.PAGEABLE ) == false ) {
      throw new PrintException( "The print service implementation does not support the Pageable Flavor." );
    }
  }

  PrintRequestAttributeSet attributes = Java14PrintUtil.copyConfiguration( null, report );
  attributes = Java14PrintUtil.copyAuxillaryAttributes( attributes, report );

  final PrintReportProcessor reportPane = new PrintReportProcessor( report );
  final DocPrintJob job = printService.createPrintJob();
  final SimpleDoc document = new SimpleDoc( reportPane, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null );

  try {
    job.print( document, attributes );
  } finally {
    reportPane.close();
  }

}
 
Example #7
Source File: PrintSEUmlauts.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #8
Source File: PrintSEUmlauts.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #9
Source File: PrintSEUmlauts.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #10
Source File: PrintSEUmlauts.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #11
Source File: PrintSEUmlauts.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #12
Source File: PrintSEUmlauts.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #13
Source File: PrintSEUmlauts.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #14
Source File: PrintSEUmlauts.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #15
Source File: PrintSEUmlauts.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #16
Source File: PrintSEUmlauts.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        GraphicsEnvironment.getLocalGraphicsEnvironment();

        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.
                        lookupStreamPrintServiceFactories(flavor, mime);
        if (factories.length == 0) {
            System.out.println("No print service found.");
            return;
        }

        FileOutputStream output = new FileOutputStream("out.ps");
        StreamPrintService service = factories[0].getPrintService(output);

        SimpleDoc doc =
             new SimpleDoc(new PrintSEUmlauts(),
                           DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                           new HashDocAttributeSet());
        DocPrintJob job = service.createPrintJob();
        job.addPrintJobListener(new PrintJobAdapter() {
            @Override
            public void printJobCompleted(PrintJobEvent pje) {
                testPrintAndExit();
            }
        });

        job.print(doc, new HashPrintRequestAttributeSet());
    }
 
Example #17
Source File: ChartPanel.java    From opensim-gui with Apache License 2.0 4 votes vote down vote up
private void createChartPrintPostScriptJob() {
// Use the pre-defined flavor for a Printable from an InputStream 
	DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;

		// Specify the type of the output stream 
	String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

	// Locate factory which can export a GIF image stream as Postscript 
	StreamPrintServiceFactory[] factories =
	StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
				flavor, psMimeType);
	if (factories.length == 0) {
		System.err.println("No suitable factories");
		System.exit(0); // FIXME too
	}
               // Obtain file name from user
               JFileChooser fileChooser = new JFileChooser();
               ExtensionFileFilter filter = new ExtensionFileFilter(
                       localizationResources.getString("PostScript_Files"), ".eps");
               fileChooser.addChoosableFileFilter(filter);
               String filename="";
               int option = fileChooser.showSaveDialog(this);
               if (option == JFileChooser.APPROVE_OPTION) {
                  filename = fileChooser.getSelectedFile().getPath();
                  if (isEnforceFileExtensions()) {
                     if (!filename.endsWith(".eps")) {
                        filename = filename + ".eps";
                     }
                  } else
                     return;
               }

	try {
		// Create a file for the exported postscript
		FileOutputStream fos = new FileOutputStream(filename);

		// Create a Stream printer for Postscript 
		StreamPrintService sps = factories[0].getPrintService(fos);

		// Create and call a Print Job 
		DocPrintJob pj = sps.createPrintJob();
		PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

		Doc doc = new SimpleDoc(this, flavor, null);

		pj.print(doc, aset);
		fos.close();

	} catch (PrintException pe) { 
		System.err.println(pe);
	} catch (IOException ie) { 
		System.err.println(ie);
	}

  }
 
Example #18
Source File: DevicePrinterPrinter.java    From nordpos with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Method that is responsible for ending and printing a ticket<br>
 * It manages to get a printerJob, set the name of the job, get a Book object<br>
 * and print the receipt
 */
@Override
public void endReceipt() {

    try {

        PrintService ps;

        if (printservice == null) {
            String[] printers = ReportUtils.getPrintNames();
            if (printers.length == 0) {
                logger.warning(AppLocal.getIntString("message.noprinters"));
                ps = null;
            } else {
                SelectPrinter selectprinter = SelectPrinter.getSelectPrinter(parent, printers);
                selectprinter.setVisible(true);
                if (selectprinter.isOK()) {
                    ps = ReportUtils.getPrintService(selectprinter.getPrintService());
                } else {
                    ps = null;
                }
            }
        } else {
            ps = printservice;
        }

        if (ps != null)  {

            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(OrientationRequested.PORTRAIT);
            aset.add(new JobName(AppLocal.APP_NAME + " - Document", null));
            aset.add(media);

            DocPrintJob printjob = ps.createPrintJob();
            Doc doc = new SimpleDoc(new PrintableBasicTicket(m_ticketcurrent, imageable_x, imageable_y, imageable_width, imageable_height), DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

            printjob.print(doc, aset);
        }

    } catch (PrintException ex) {
        logger.log(Level.WARNING, AppLocal.getIntString("message.printererror"), ex);
        JMessageDialog.showMessage(parent, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.printererror"), ex));
    }

    //ticket is not needed any more
    m_ticketcurrent = null;
}
 
Example #19
Source File: PrintUtility.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Execuate Print Job
 * 
 * @param inputStream
 * @param printer
 * @throws ViewerException
 */
public static void execPrint( InputStream inputStream, Printer printer )
		throws RemoteException
{
	if ( inputStream == null || printer == null )
		return;

	// Create print request attribute set
	PrintRequestAttributeSet pas = new HashPrintRequestAttributeSet( );

	// Copies
	if ( printer.isCopiesSupported( ) )
		pas.add( new Copies( printer.getCopies( ) ) );

	// Collate
	if ( printer.isCollateSupported( ) )
		pas.add( printer.isCollate( )
				? SheetCollate.COLLATED
				: SheetCollate.UNCOLLATED );

	// Duplex
	if ( printer.isDuplexSupported( ) )
	{
		switch ( printer.getDuplex( ) )
		{
			case Printer.DUPLEX_SIMPLEX :
				pas.add( Sides.ONE_SIDED );
				break;
			case Printer.DUPLEX_HORIZONTAL :
				pas.add( Sides.DUPLEX );
				break;
			case Printer.DUPLEX_VERTICAL :
				pas.add( Sides.TUMBLE );
				break;
			default :
				pas.add( Sides.ONE_SIDED );
		}
	}

	// Mode
	if ( printer.isModeSupported( ) )
	{
		switch ( printer.getMode( ) )
		{
			case Printer.MODE_MONOCHROME :
				pas.add( Chromaticity.MONOCHROME );
				break;
			case Printer.MODE_COLOR :
				pas.add( Chromaticity.COLOR );
				break;
			default :
				pas.add( Chromaticity.MONOCHROME );
		}
	}

	// Media
	if ( printer.isMediaSupported( ) && printer.getMediaSize( ) != null )
	{
		MediaSizeName mediaSizeName = (MediaSizeName) printer
				.getMediaSizeNames( ).get( printer.getMediaSize( ) );
		if ( mediaSizeName != null )
			pas.add( mediaSizeName );
	}

	try
	{
		PrintService service = printer.getService( );
		synchronized ( service )
		{
			DocPrintJob job = service.createPrintJob( );
			Doc doc = new SimpleDoc( inputStream,
					DocFlavor.INPUT_STREAM.POSTSCRIPT, null );
			job.print( doc, pas );
		}
	}
	catch ( PrintException e )
	{
		AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e );
		fault.setFaultCode( new QName( "PrintUtility.execPrint( )" ) ); //$NON-NLS-1$
		fault.setFaultString( e.getLocalizedMessage( ) );
		throw fault;
	}
}
 
Example #20
Source File: PrintServiceImpl.java    From jqm with Apache License 2.0 4 votes vote down vote up
@Override
public void print(String printQueueName, String jobName, Object data, DocFlavor flavor, String endUserName) throws PrintException
{
    // Arguments tests
    if (printQueueName == null || printQueueName.isEmpty())
    {
        throw new IllegalArgumentException("printQueueName must be non null and non empty");
    }
    if (data == null)
    {
        throw new IllegalArgumentException("data must be non null");
    }
    if (flavor == null)
    {
        throw new IllegalArgumentException("flavor must be non null");
    }
    if (jobName == null || jobName.isEmpty())
    {
        throw new IllegalArgumentException("job name must be non null and non empty");
    }
    if (endUserName != null && endUserName.isEmpty())
    {
        throw new IllegalArgumentException("endUserName can be null but cannot be empty is specified");
    }

    // Find the queue
    AttributeSet set = new HashPrintServiceAttributeSet();
    set.add(new PrinterName(printQueueName, null));
    javax.print.PrintService[] services = PrintServiceLookup.lookupPrintServices(null, set);

    if (services.length == 0 || services[0] == null)
    {
        throw new IllegalArgumentException("There is no printer queue defined with name " + printQueueName
                + " supporting document flavour " + flavor.toString());
    }
    javax.print.PrintService queue = services[0];

    // Create job
    DocPrintJob job = queue.createPrintJob();
    PrintRequestAttributeSet jobAttrs = new HashPrintRequestAttributeSet();
    jobAttrs.add(new JobName(jobName, null));
    if (endUserName != null && queue.isAttributeCategorySupported(RequestingUserName.class))
    {
        jobAttrs.add(new RequestingUserName(endUserName, null));
    }

    // Create payload
    Doc doc = new SimpleDoc(data, flavor, null);

    // Do it
    job.print(doc, jobAttrs);
}