try {
System.out.println("Optional content");
// step 1: creation of a document-object
LwgDocument document = new LwgDocument(LwgPageSize.A4, 50, 50, 50, 50);
// step 2: creation of the writer
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("optionalcontent.pdf"));
writer.setPdfVersion(PdfWriter.VERSION_1_5);
writer.setViewerPreferences(PdfWriter.PageModeUseOC);
// step 3: opening the document
document.open();
// step 4: content
PdfContentByte cb = writer.getDirectContent();
LwgPhrase explanation = new LwgPhrase("Automatic layers, form fields, images, templates and actions", new LwgFont(LwgFont.HELVETICA, 18, LwgFont.BOLD, Color.red));
ColumnText.showTextAligned(cb, LwgElement.ALIGN_LEFT, explanation, 50, 650, 0);
PdfLayer l1 = new PdfLayer("Layer 1", writer);
PdfLayer l2 = new PdfLayer("Layer 2", writer);
PdfLayer l3 = new PdfLayer("Layer 3", writer);
PdfLayer l4 = new PdfLayer("Form and XObject Layer", writer);
PdfLayerMembership m1 = new PdfLayerMembership(writer);
m1.addMember(l2);
m1.addMember(l3);
LwgPhrase p1 = new LwgPhrase("Text in layer 1");
LwgPhrase p2 = new LwgPhrase("Text in layer 2 or layer 3");
LwgPhrase p3 = new LwgPhrase("Text in layer 3");
cb.beginLayer(l1);
ColumnText.showTextAligned(cb, LwgElement.ALIGN_LEFT, p1, 50, 600, 0f);
cb.endLayer();
cb.beginLayer(m1);
ColumnText.showTextAligned(cb, LwgElement.ALIGN_LEFT, p2, 50, 550, 0);
cb.endLayer();
cb.beginLayer(l3);
ColumnText.showTextAligned(cb, LwgElement.ALIGN_LEFT, p3, 50, 500, 0);
cb.endLayer();
TextField ff = new TextField(writer, new LwgRectangle(200, 600, 300, 620), "field1");
ff.setBorderColor(Color.blue);
ff.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
ff.setBorderWidth(TextField.BORDER_WIDTH_THIN);
ff.setText("I'm a form field");
PdfFormField form = ff.getTextField();
form.setLayer(l4);
writer.addAnnotation(form);
LwgImage img = LwgImage.getInstance("pngnow.png");
img.setLayer(l4);
img.setAbsolutePosition(200, 550);
cb.addImage(img);
PdfTemplate tp = cb.createTemplate(100, 20);