package org.khelekore.jsizer;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFrame;

/** An action that exports a pdf image of the current graph. */
class PDFAction extends ExportImageAction {
    private static final long serialVersionUID = 1;
    public PDFAction (SizePanel sp, JFrame f) {
	super ("Save pdf...", sp, f);
    }

    @Override protected String getFileExtension () {
	return "pdf";
    }

    @Override protected void writeImage (SizePanel sp, File out) 
	throws IOException {
	Graphics2D g2 = null;
        Document document = null;
	FileOutputStream fos = null;
	try {
	    document = new Document (PageSize.A4, 50, 50, 50, 50);
	    fos = new FileOutputStream (out);
            PdfWriter writer = PdfWriter.getInstance (document, fos);
            document.open ();
            PdfContentByte cb = writer.getDirectContent ();
	    
	    g2 = cb.createGraphics (PageSize.A4.getWidth (), 
				    PageSize.A4.getHeight ());
	    g2.translate (PageSize.A4.getWidth (), 0);
	    AffineTransform at = g2.getTransform ();
	    at.quadrantRotate (1);
	    g2.setTransform (at);
	    double s = Math.min (PageSize.A4.getHeight () / sp.getWidth (),
				 PageSize.A4.getWidth () / sp.getHeight ());
	    g2.scale (s, s);
	    sp.paint (g2);
	} catch (DocumentException e) {
	    throw new IOException ("Failed to create pdf", e);
	} finally {
	    if (g2 != null)
		g2.dispose ();
	    // document closes fos as well...
	    document.close ();
	}
    }    
}
