LayersPDF.java Source code

Java tutorial

Introduction

Here is the source code for LayersPDF.java

Source

import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfLayer;
import com.lowagie.text.pdf.PdfLayerMembership;
import com.lowagie.text.pdf.PdfWriter;

public class LayersPDF {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("LayersPDF.pdf"));
            writer.setPdfVersion(PdfWriter.VERSION_1_5);

            writer.setViewerPreferences(PdfWriter.PageModeUseOC);
            document.open();

            PdfContentByte cb = writer.getDirectContent();

            PdfLayer l1 = new PdfLayer("Layer 1", writer);
            PdfLayer l2 = new PdfLayer("Layer 2", writer);
            PdfLayer l3 = new PdfLayer("Layer 3", writer);
            PdfLayerMembership m1 = new PdfLayerMembership(writer);
            m1.addMember(l1);
            m1.addMember(l2);
            m1.addMember(l3);

            cb.beginLayer(l1);
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("Text in layer 1"), 50, 600, 0);
            cb.endLayer();
            cb.beginLayer(l2);
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("Text in layer 2"), 50, 550, 0);
            cb.endLayer();
            cb.beginLayer(l3);
            ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase("Text in layer 3"), 50, 500, 0);
            cb.endLayer();

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        document.close();
    }
}