alvgarvilla
alvgarvilla

Reputation: 1086

How to locate position in pdf generated with jasperreport to place a signature?

I generate a PDF file with JAVA and jasper. Such jasper file is designed with iReport. Once the pdf file is created, I would like to place a signature with PdfStamper in a concrete position in the pdf. Possible solutions that I have found:

Use PdfSignatureAppearance.setVisibleSignature method. This does not fit my needs since it locates the signature in coordinates based position.

PdfStamper stp = PdfStamper.createSignature(reader, outStream, '\0', fileTmp);
PdfSignatureAppearance sap = stp.getSignatureAppearance();
sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);

Use PdfReader.getAcroFields() and then go through the AcroFields, get the coordinates of a predifined form field and insert the signature as shown in the previous option. The problem is that I am not able to define AcroFields with iReport, so I cannot use it either.

My question: is there any way to define fields with iReport and read after the PDF is created with Java?

Upvotes: 2

Views: 2451

Answers (1)

Petter Friberg
Petter Friberg

Reputation: 21710

You can use the PdfReaderContentParser to find image and text inside the pdf.

Example (showing how to find location of both text and image in pdf)

PdfReader reader = new PdfReader(src);
int pageILikeToCheck =reader.getNumberOfPages(); //set the page or loop them all        
final String matchStr = "FIND THIS TEXT";

PdfReaderContentParser parser = new PdfReaderContentParser(reader);
parser.processContent(pageILikeToCheck, new RenderListener() {  

    @Override
    public void renderImage(ImageRenderInfo renderInfo) {
        PdfImageObject image;
        try {
            image = renderInfo.getImage();
            if (image == null) return;
            System.out.println("Found image");
            System.out.println(renderInfo.getStartPoint());
        } catch (IOException e) {
            e.printStackTrace();
        }     
    }

    @Override
    public void renderText(TextRenderInfo renderInfo) {

        if(renderInfo.getText().length()>0 && matchStr.contains(renderInfo.getText())){
            System.out.println("FOUND MY TEXT");
            System.out.println(renderInfo.getBaseline().getStartPoint());
            System.out.println(renderInfo.getBaseline().getEndPoint());
        }
    }

    @Override
    public void endTextBlock() {
    }

    @Override
    public void beginTextBlock() {
    }
});

However I normally add the signature in pdf to a pre-defined space (using pageFooter or lastPageFooter band) using the PdfStamper

PdfReader reader = new PdfReader(src);
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
int pageSignature=1;
stamper.addSignature("Signature", pageSignature, 320, 570, 550, 620);

and then write baos to file.

Upvotes: 3

Related Questions