Java – Use iText 5 or 7 to add image layers to pdf

Use iText 5 or 7 to add image layers to pdf… here is a solution to the problem.

Use iText 5 or 7 to add image layers to pdf

I need to create a pdf document with images that should be included in the layer. Each image should be included in a layer so that we can choose to make each image visible or not.

I know that iText provides a class PdfLayer for this purpose, but they don’t explain how to use it. Surprisingly, the tutorials on the web do not cover this issue.

It’s a small start :

    // Creating a PdfWriter 
    String dest = "export.pdf"; 
    PdfWriter writer = new PdfWriter(dest);

 Creating a PdfDocument  
    PdfDocument pdfDoc = new PdfDocument(writer);

 Adding an empty page 
    pdfDoc.addNewPage(); 

 Creating a Document   
    Document document = new Document(pdfDoc); 

/////////////////////////////////////////////////////////

 Creating an ImageData object 
    String imageFile = "map.png"; 
    ImageData data = ImageDataFactory.create(imageFile);

 Creating an Image object 
    Image img = new Image(data);

PdfLayer pdflayer = new PdfLayer("main layer", pdfDoc);
    pdflayer.setOn(true); 

/* normally, here where the image should be added to the layer */

Hope to get your help, thank you!

Solution

You can add an image to a layer by starting it in PdfCanvas to draw, adding an image, and ending the layer in it again.

Depending on whether you want to do the content layout work yourself, you can add parts of the image directly or through Canvas.

For example:

try (   PdfWriter writer = new PdfWriter(...);
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document document = new Document(pdfDoc)   ) {
    ImageData data = ImageDataFactory.create(IMAGE_DATA);
    Image img = new Image(data);

PdfLayer pdflayer = new PdfLayer("main layer", pdfDoc);
    pdflayer.setOn(true); 

 using a Canvas, to allow iText layout'ing the image
    PdfCanvas pdfCanvas = new PdfCanvas(pdfDoc.addNewPage());
    try (   Canvas canvas = new Canvas(pdfCanvas, pdfDoc, document.getPageEffectiveArea(pdfDoc.getDefaultPageSize()))   ) {
        canvas.add(new Paragraph("This image is added using a Canvas:"));
        pdfCanvas.beginLayer(pdflayer);
        canvas.add(img);
        pdfCanvas.endLayer();
        canvas.add(new Paragraph("And this image is added immediately:"));
    }

 or directly 
    pdfCanvas.beginLayer(pdflayer);
    pdfCanvas.addImage(data, 100, 100, false);
    pdfCanvas.endLayer();
}

( AddImageToLayer Test testAddLikeIan).

Depending on your question title, you are looking for a solution for iText 5 or iText 7. The above code works for iText 7, and I’m using the current development version 7.1.4-SNAPSHOT.

Related Problems and Solutions