1

I'm trying to add an image to the center of pdf using pdfbox. Below is my code but I'm unable to get the correct position of image in pdf. I followed the following link In PDFBox, how to change the origin (0,0) point of a PDRectangle object? to get the correct position but still image is off from the midpoint position?

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;

public class imageAppend {
     public static void main (String[] args){

            File file = new File("...pdf file location");
            PDDocument doc = null;
            try 
            {
                doc = PDDocument.load(file);
                PDImageXObject pdImage = PDImageXObject.createFromFile("image file location", doc);

                PDPage page = doc.getPage(0);
                PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);

               float x_pos = page.getCropBox().getWidth();
               float y_pos = page.getCropBox().getHeight();

                float x_adjusted = ( x_pos - w ) / 2;
                float y_adjusted = ( y_pos - h ) / 2;

                Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
            contentStream.transform(mt);
            contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);

                doc.save("new pdf file location");
                doc.close();

            } catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
}
shanky
  • 751
  • 1
  • 16
  • 46

1 Answers1

5

I reproduced your problem, with my test data (unfortunately you did not share yours) I get

screenshot

The fix is simple, I removed the two lines

Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
contentStream.transform(mt);

and now get

screenshot

For the general case you should also add the coordinates of the lower left corner of the crop box to your x_adjusted and y_adjusted

float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX();
float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY();

(AddImage test method testImageAppendNoMirror)

mkl
  • 90,588
  • 15
  • 125
  • 265