
import javax.swing.*;
import java.awt.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.io.FileOutputStream;

public class GradientColor extends JComponent {

    boolean once = true;
    final int width = 400;
    final int height = 300;

    public static void main(String[] args) {
        GradientColor gd = new GradientColor();
    }

    public GradientColor() {
        JFrame frame = new JFrame("GradientPaint & Transparency");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(this);
        frame.setSize(width, height);
        frame.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        // Draw the white background
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        // Draw the content
        draw((Graphics2D) g);
        // Make the PDF only once
        if (once) {
            makePDF();
            once = false;
        }
    }

    public void draw(Graphics2D g2) {
        // Firstly draw a red rectangle
        g2.setColor(Color.RED);
        g2.fillRect(150, 75, 200, 100);

        // Create a black fully transparent colour
        Color transparent = new Color(0, 0, 0, 0);
        GradientPaint gradient = new GradientPaint(100, 100, Color.GREEN, 300, 100, transparent);
        g2.setPaint(gradient);
        g2.fillRect(100, 100, 200, 100);
    }

    public void makePDF() {
        // step 1: creation of a document-object
        Document document = new Document(new com.lowagie.text.Rectangle(width, height), 0, 0, 0, 0);
        try {
            // step 2: creation of the writer
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("graphics2D.pdf"));
            // step 3: we open the document
            document.open();
            // step 4: we grab the ContentByte and do some stuff with it
            PdfContentByte cb = writer.getDirectContent();
            Graphics2D g2pdf = cb.createGraphics(width, height);
            draw(g2pdf);
            g2pdf.dispose();
        } catch (Exception ex) {
        }
        // step 5: we close the document
        document.close();
    }
}