Show hide text with layer : Layer « PDF « Java Tutorial






import java.io.FileOutputStream;
import java.util.ArrayList;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfLayer;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass {
  public static void main(String[] args) throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    writer.setPdfVersion(PdfWriter.VERSION_1_5);
    document.open();
    PdfLayer a1 = new PdfLayer("answer 1", writer);
    a1.setOn(false);

    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    PdfContentByte cb = writer.getDirectContent();
    cb.beginText();
    cb.setTextMatrix(50, 790);
    cb.setLeading(24);
    cb.setFontAndSize(bf, 18);
    cb.newlineShowText("This is a question?");
    cb.beginLayer(a1);
    cb.setRGBColorFill(0xFF, 0x00, 0x00);
    cb.newlineShowText("This is the answer");
    cb.resetRGBColorFill();
    cb.endLayer();
    cb.endText();

    ArrayList stateOn = new ArrayList();
    stateOn.add("ON");
    stateOn.add(a1);
    PdfAction actionOn = PdfAction.setOCGstate(stateOn, true);
    ArrayList stateOff = new ArrayList();
    stateOff.add("OFF");
    stateOff.add(a1);
    PdfAction actionOff = PdfAction.setOCGstate(stateOff, true);
    ArrayList stateToggle = new ArrayList();
    stateToggle.add("Toggle");
    stateToggle.add(a1);
    PdfAction actionToggle = PdfAction.setOCGstate(stateToggle, true);
    Phrase p = new Phrase("Change the state of the answers:");
    Chunk on = new Chunk(" on ").setAction(actionOn);
    p.add(on);
    Chunk off = new Chunk("/ off ").setAction(actionOff);
    p.add(off);
    Chunk toggle = new Chunk("/ toggle").setAction(actionToggle);
    p.add(toggle);
    document.add(p);
    document.close();
  }
}








29.70.Layer
29.70.1.Using Layer
29.70.2.Text on layer
29.70.3.Create PdfLayer
29.70.4.Show hide text with layer
29.70.5.Nested Layers
29.70.6.Grouped layers
29.70.7.Radio Group
29.70.8.not printed layer