/*
 * This example was written based on code provided on the mailing list
 * by Mark Storer. It was adapted by Bruno Lowagie, author of the book
 * 'iText in Action' by Manning Publications (ISBN: 1932394796).
 * You can use this example as inspiration for your own applications.
 * The following license applies:
 * http://www.1t3xt.com/about/copyright/index.php?page=MIT
 */
 
package questions.images;
 
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
 
public class TransparentGradient {
	public static final String RESULT = "results/questions/images/transparent_gradient.pdf";
 
    public static void main(String[] args) {
 
        Document document = new Document(PageSize.POSTCARD);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            // Background BLUE Box
            cb.setColorFill(Color.BLUE);
            cb.rectangle(50, 0, 100, 100);
            cb.fill();
            cb.newPath();
            
            // Clipping Square
            cb.rectangle(0, 0, 100, 100);
            cb.clip();
            cb.newPath();

            //Create template
            PdfTemplate template = cb.createTemplate(100, 100);

            //Prepare transparent group
            PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
            transGroup.put(PdfName.CS, PdfName.DEVICERGB);
            transGroup.setIsolated(true);
            transGroup.setKnockout(false);
            template.setGroup(transGroup);

            //Prepare graphic state
            PdfGState gState = new PdfGState();
            PdfDictionary maskDict = new PdfDictionary();
            maskDict.put(PdfName.TYPE, PdfName.MASK);
            maskDict.put(PdfName.S, new PdfName("Luminosity"));
            maskDict.put(new PdfName("G"), template.getIndirectReference());
            gState.put(PdfName.SMASK, maskDict);
            //gState.setBlendMode(PdfGState.BM_NORMAL);
            //gState.setFillOpacity(1f);
            //gState.setAlphaIsShape(false);
            cb.setGState(gState);

            // Create a gradient to use as the mask
            PdfShading shading = PdfShading.simpleAxial(cb.getPdfWriter(), 0, 0, 0, 100, Color.RED, Color.WHITE);
            template.paintShading(shading);
            //Place template
            cb.addTemplate(template, 0, 0);
            
        }
        catch(DocumentException de) {
            System.err.println(de.getMessage());
        }
        catch(IOException ioe) {
            System.err.println(ioe.getMessage());
        }
 
        document.close();
    }
}