I want to drag an image to my pdf file using itext java

757 views Asked by At

I have a requirement to perform drag and drop functionality using iText jar file. and also I want to set the image width and height any help grately appriciated.

I am using the following code but unable to set the size of the image(Hint: Half of my PDF page will contain Image but I am unable to do that)

below is my code:

        String imgLoc = "E:/iText/Image1.jpg";
        Image image = Image.getInstance(imgLoc);
        image.setAbsolutePosition(100, 140);

        image.scaleToFit(100f, 70f);
        // image.setAbsolutePosition(280, 10);
        // image.setAbsolutePosition(absoluteX, absoluteY);
        // writer.getDirectContent().addImage(image);

        document.add(preface1);
2

There are 2 answers

0
robcalvo On

Try with .scalePercent() method. For example, if you want to reduce the size at 50% you can do:

    image.setAbsolutePosition(100, 140);
    image.scalePercent(50f); 

Try different values until you get the one that fits you.

3
Bruno Lowagie On

This question is more or less unanswerable because you want the image to cover "half of the page", but you don't tell us how you defined the page size.

If you created your Document like this:

Document document = new Document();

Then you implicitly defined the page size: the default page size is A4. In other words: what you're doing is equivalent to this:

Rectangle pagesize = new Rectangle(595, 842);
Document document = Document(pagesize);

Hence, if you want an image to cover half of the page, you need something like this:

image.scaleToFit(pagesize.getWidth(), pagesize.getHeight() / 2);

Note that the scaleToFit() method respects the aspect ratio of the image, so it is possible that the image is smaller than half the page size. If you really want to use the exact half of the page, you need:

image.scaleAbsolute(pagesize.getWidth(), pagesize.getHeight() / 2);

However: this may result in an ugly result with an image that looks unnatural because it's stretched to fit absolute dimension.

Depending on whether you want to add the image to the upper half of the page or the lower half, you need:

  • Lower half: image.setAbsolutePosition(0, 0);
  • Upper half: image.setAbsolutePosition(0, pagesize.getHeight() / 2);

In your code, you are using hard-coded dimensions and positions. It would be very surprising if those values correspond with half of the page.