Java 使用pdfbox将矩阵移动到右上角

Java 使用pdfbox将矩阵移动到右上角,java,matrix,pdfbox,Java,Matrix,Pdfbox,上下文: 我是一个新生成pdf的人,我正在缩放一个矩阵,但我的问题是,当矩阵被缩放时,它会将缩放后的矩阵放在pdf的左下角 我的问题: float titleWidth = font.getStringWidth(title) / 1000 * fontSize; float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; float width = page.g

上下文:

我是一个新生成pdf的人,我正在缩放一个矩阵,但我的问题是,当矩阵被缩放时,它会将缩放后的矩阵放在pdf的左下角

我的问题:

float titleWidth = font.getStringWidth(title) / 1000 * fontSize;
float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
float ratio = Math.min(maxWidth/width, maxHeight /height);
float scaledWidth = width * ratio;
float scaledHeight = height * ratio;
page.setCropBox(PDRectangle.A4);

matrix.scale(sx = width / scaledWidth, height / scaledHeight);
contentStream.transform(matrix);

contentStream.beginText();
contentStream.newLineAtOffset(((page.getMediaBox().getWidth() - titleWidth) / 2), page.getMediaBox().getHeight() - marginTop - titleHeight);
contentStream.setFont(font, (float) (fontSize));
contentStream.showText(title);
contentStream.endText();
ByteArrayOutputStream os = new ByteArrayOutputStream();

contentStream.close();
document.save(os);
document.close();

return  os.toByteArray();
我的问题是,实际上,当我缩放pdf时,它会卡在页面的左下角,我找不到方法将它放在右上角,无论缩放矩阵的大小如何

我的代码:

float titleWidth = font.getStringWidth(title) / 1000 * fontSize;
float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
float ratio = Math.min(maxWidth/width, maxHeight /height);
float scaledWidth = width * ratio;
float scaledHeight = height * ratio;
page.setCropBox(PDRectangle.A4);

matrix.scale(sx = width / scaledWidth, height / scaledHeight);
contentStream.transform(matrix);

contentStream.beginText();
contentStream.newLineAtOffset(((page.getMediaBox().getWidth() - titleWidth) / 2), page.getMediaBox().getHeight() - marginTop - titleHeight);
contentStream.setFont(font, (float) (fontSize));
contentStream.showText(title);
contentStream.endText();
ByteArrayOutputStream os = new ByteArrayOutputStream();

contentStream.close();
document.save(os);
document.close();

return  os.toByteArray();
这是缩放矩阵的屏幕截图(如果我的解释不清楚):


转换为页面高度减去你的图像的高度,因为y 0在底部。我已经尝试过了,但是奇怪的是,我的矩阵没有移动到顶部,就像在Page添加的中间一样,你首先缩放坐标系,然后翻译它,翻译是按比例缩放的。因此,必须为平移使用反向缩放值。例如,如果初始比例为0.5,则必须将根据未缩放数据确定的平移值加倍。我真的不明白您的解释,请您给我一个公式,使其符合您的意思吗?将newLineAtOffset值除以比例。