Using PDFBox
i am try to set signature
to center on the box of rectacle
, assume the rectacle
size is 120x60
and can be customized and image signature can vary, examples 1000*1000
or 640x320
etc. I am try with resize the signature like the box :
// save and restore graphics if the image is too large and needs to be scaled
cs.saveGraphicsState();
cs.transform(Matrix.getScaleInstance(0.85f, 0.85f));
PDImageXObject img = PDImageXObject.createFromFileByExtension(imageFile, doc);
float wpercent = (rect.getWidth() / img.getWidth());
float newHeight = img.getHeight() * wpercent;
cs.drawImage(img, 0,0, rect.getWidth(), newHeight); //Resize image signature fit to rectangle and resize the height by percent to avoid stretch image
cs.restoreGraphicsState();
try to calculate coordinate inside the box
cs.drawImage(img, rect.getWidth()*0.10,rect.getHeight()*0.10, rect.getWidth(), newHeight);
example image got success set on center image size 1880x1000
if the signature just QR size 1000x1000
the QR got cut off
how to fix that ?
CodePudding user response:
Solved refers to Auto resized image
by adding this function to scale image fit to rectangle
public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
return new Dimension(new_width, new_height);
}
then add to this function
Dimension scaledDim = getScaledDimension(new Dimension(img.getWidth(), img.getHeight()), new Dimension((int)rect.getWidth(), (int)rect.getHeight()));
int x = ((int) rect.getWidth() - scaledDim.width) / 2;
int y = ((int) rect.getHeight() - scaledDim.height) / 2;
cs.drawImage(img, x, y, scaledDim.width, scaledDim.height);