Printing a bufferedImage

Hi Zac

I did mange to figure it out. I mostly used the java library instead of ignition because I couldn’t get the screen capture to work quite right.

from java.awt import Robot, Rectangle
from javax.imageio import ImageIO
from java.io import File, ByteArrayOutputStream
from javax.print import Doc, DocFlavor, DocPrintJob, PrintService, PrintServiceLookup, SimpleDoc, ServiceUI 
from javax.print.attribute import HashPrintRequestAttributeSet, HashDocAttributeSet
from javax.print.attribute.standard import Copies, OrientationRequested

#Obtain custom property from header Monitor Number
monNum = str(event.source.parent.monNum)

#Obtain the X cordinate offset
xOffset = system.gui.getParentWindow(event).parent.getTopLevelAncestor().x
#Obtain the Y cordinate offset
yOffset = system.gui.getParentWindow(event).parent.getTopLevelAncestor().y

#Gets the monitor size from the Client Tags (x,y,width,height)
monX = system.tag.read('[Client]GraphicsInfo/Display'+monNum+'/monitorX')
monY = system.tag.read('[Client]GraphicsInfo/Display'+monNum+'/monitorY')
monW = system.tag.read('[Client]GraphicsInfo/Display'+monNum+'/monitorW')
monH = system.tag.read('[Client]GraphicsInfo/Display'+monNum+'/monitorH')

#Message Box for testing 
#system.gui.messageBox("Monitor Num:" + monNum + "\n mon X: %d \n mon Y: %d \n mon H: %d \n mon W: %d \n x Offset: %d \n y Offset: %d \n" %(monX.value,monY.value,monW.value,monH.value,xOffset,yOffset))

#creates a rectangle (x,y,width,height)
rec = Rectangle((monX.value+xOffset),(monY.value+yOffset),monW.value,monH.value)

#Creates a screen Capture and returns a BufferedImage
bot = Robot()
bimage = bot.createScreenCapture(rec)

#Converts Screen Capture to Byte Array so we can print it.
baos=ByteArrayOutputStream()                     
ImageIO.write(bimage, "png", baos)
baos.flush
byteArray=baos.toByteArray()
baos.close

#Set Default Print job Attributes
DocAttributeSet = HashDocAttributeSet()
printJobAttributeSet = HashPrintRequestAttributeSet()
printJobAttributeSet.add(Copies(1))
printJobAttributeSet.add(OrientationRequested.LANDSCAPE)

#Gets a list avaliable printers
services = PrintServiceLookup.lookupPrintServices( DocFlavor.BYTE_ARRAY.PNG, None )

#Creates Print Setting Dialogue Box 
#(graphics, x, y , list of printers, default printer, flavor, attributes)
service = ServiceUI.printDialog(None,(monX.value+xOffset)+ 150 ,(monY.value +yOffset) + 150 , services, PrintServiceLookup.lookupDefaultPrintService() , None, printJobAttributeSet)

#Do nothing if the Print Dialogue is Cancelled 
if (service != None):

	#Create document
	doc=SimpleDoc(byteArray, DocFlavor.BYTE_ARRAY.PNG, DocAttributeSet)
	
	#Prints that document
	job=service.createPrintJob()
	job.print(doc,printJobAttributeSet)
3 Likes