Ian
Ian

Reputation: 33

Adding image layers to a pdf using iText 5 or 7

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

I know that iText offers a class PdfLayer for that purpose but they don't explain how to use it. Surprisingly tutorials in the web don't cover this question.

This is a little 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 for your help, thanks!

Upvotes: 3

Views: 7355

Answers (1)

mkl
mkl

Reputation: 96064

You add an image to a layer by starting that layer in the PdfCanvas to draw on, adding the image, and ending the layer therein again.

Depending on whether you want to do the content layout work yourself, you can do the image adding part directly or via a 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)

According to your question title you look for a solution for either iText 5 or iText 7. The code above is for iText 7, I used the current development version 7.1.4-SNAPSHOT.

Upvotes: 4

Related Questions