title: Draw image at mid position using pdfbox Java
body: <p>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 <a href="https://stackoverflow.com/questions/28093537/in-pdfbox-how-to-change-the-origin-0-0-point-of-a-pdrectangle-object/28114320">In PDFBox, how to change the origin (0,0) point of a PDRectangle object?</a> to get the correct position but still image is off from the midpoint position?</p>
  
  <pre><code>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();
              }
          }
  }
  </code></pre>