Java Code Examples for javax.print.Doc

The following examples show how to use javax.print.Doc. These examples are extracted from open source projects.
Example 1
Project: escpos-coffee   File: PrinterOutputStream.java    License: 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 2
Project: openjdk-jdk9   File: DummyPrintTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void print(Doc doc,
                  PrintRequestAttributeSet printRequestAttributeSet)
      throws PrintException {
    System.out.println("job name: " + printRequestAttributeSet.get(JobName.class));
    System.out.println("copies: " + printRequestAttributeSet.get(Copies.class));
    if(printRequestAttributeSet.get(JobName.class) == null ||
        printRequestAttributeSet.get(Copies.class) == null) {
        throw new RuntimeException("Copies and JobName is not passed correctly");
    }
}
 
Example 3
Project: opensim-gui   File: ChartPanel.java    License: 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 4
Project: nordpos   File: DevicePrinterPrinter.java    License: 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 5
Project: birt   File: PrintUtility.java    License: 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 6
Project: jqm   File: PrintServiceImpl.java    License: 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);
}