[英]How to center a scaled page in PDFBox
I am trying to center the content of my page after scaling it by a factor X. I have tried using the Matrix.translate function but I always end up getting the wrong position, except when scaling with a factor of 0.5 (which makes totally sense to me).我试图在将页面内容缩放 X 倍后将其居中。我尝试使用 Matrix.translate function 但我最终总是得到错误的 position,除非以 0.5 倍缩放(这完全有意义大部头书)。 My current code:
我当前的代码:
for (int i = 0; i < doc.getNumberOfPages(); i++) {
pdfBuilder.addPage(doc.getPage(i));
PDPage p = pdfBuilder.getDocument().getPage(i);
Matrix matrix = new Matrix();
float scaleFactor = 0.7f;
float pageHeight = p.getMediaBox().getHeight();
float pageWidth = p.getMediaBox().getWidth();
float translateX = pageWidth * (1 - scaleFactor);
float translateY = pageHeight * (1 - scaleFactor);
matrix.scale(scaleFactor, scaleFactor);
matrix.translate(translateX, translateY);
PDPageContentStream str = new PDPageContentStream(pdfBuilder.getDocument(), p, AppendMode.PREPEND,
false);
str.beginText();
str.transform(matrix);
str.endText();
str.close();
}
I have also tried other boxes like the cropBox and bBox but I think I am totally wrong in what I do right now.我也尝试过其他盒子,比如cropBox和bBox,但我认为我现在所做的完全错了。 Please help me: :)
请帮我: :)
Update I finally found a solution.更新我终于找到了解决方案。 The new translation values I am using now look like the following.
我现在使用的新翻译值如下所示。
float translateX = (pageWidth * (1- scaleFactor)) / scaleFactor / 2;
float translateY = (pageHeight * (1- scaleFactor)) / scaleFactor / 2;
Update I finally found a solution.更新我终于找到了解决方案。 The new translation values I am using now look like the following.
我现在使用的新翻译值如下所示。
float translateX = (pageWidth * (1- scaleFactor)) / scaleFactor / 2;
float translateY = (pageHeight * (1- scaleFactor)) / scaleFactor / 2;
First of all, it is important to note what @mkl said.首先,重要的是要注意@mkl 所说的内容。
Now the explanation of the translation (eG translation for the page height).现在解释翻译(页面高度的eG翻译)。 PLEASE NOTE THAT I AM NOT A MATHEMATICIAN AND I JUST TRIED DIFFERENT WAYS AND THIS IS THE ONE THAT WORKED FOR ME
请注意,我不是数学家,我只是尝试了不同的方法,这对我有用
pageHeight * (1 - scaleFactor)
.pageHeight * (1 - scaleFactor)
的相反值。 We need the opposite because the smaller we scale something the more it needs to move from a given position. If you know why this works, feel free to edit this answer:)如果您知道为什么会这样,请随时编辑此答案:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.