package siprp.ficha;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.evolute.utils.print.A4ContinuoPage;
import com.evolute.utils.print.AbstractPrintHandler;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;

public class PDFFilePrinter extends AbstractPrintHandler
{
	protected byte pdf[];
	protected PDFFile pdffile;
	
	public PDFFilePrinter(byte pdf[], boolean printDialog )
		throws Exception
	{
		super( new A4ContinuoPage(), printDialog );
		
		this.pdf = pdf;
		ByteBuffer buffer = ByteBuffer.allocate( pdf.length );
		buffer.put( pdf );
//		
		
//		File file = new File("/home/fpalma/Desktop/icons_op.pdf");
//
//		// set up the PDF reading
//		RandomAccessFile raf = new RandomAccessFile(file, "r");
//		FileChannel channel = raf.getChannel();
//		ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
		pdffile = new PDFFile(buffer);
		setNumberOfPages( pdffile.getNumPages() );
		print();
	}
	
	protected void paintGraphics( Graphics g, PageFormat pf, int index )
	{
		try
		{
			PDFPage page = pdffile.getPage( index );
			PDFRenderer renderer = new PDFRenderer(page, ( Graphics2D ) g, 
				    new Rectangle(0, 0,(int) page.getWidth(), (int) page.getHeight()), null, Color.RED);
			page.waitForFinish();
			renderer.run();
		}
		catch( Exception ex )
		{
			ex.printStackTrace();
		}
	}
}
