|
|
@@ -9,7 +9,9 @@ import org.apache.pdfbox.Loader;
|
|
|
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.PDImageXObject;
|
|
|
+import org.apache.pdfbox.util.Matrix;
|
|
|
import sun.misc.BASE64Decoder;
|
|
|
|
|
|
import javax.swing.*;
|
|
|
@@ -144,13 +146,50 @@ public class PDFFileUtil {
|
|
|
document.setAllSecurityToBeRemoved(true);
|
|
|
byte[] imageBytes = Base64.getDecoder().decode(base64FileData);
|
|
|
PDImageXObject image = PDImageXObject.createFromByteArray(document, imageBytes, "image");
|
|
|
- // 获取图片的宽度和高度并存储在变量中
|
|
|
float imageWidth = image.getWidth();
|
|
|
float imageHeight = image.getHeight();
|
|
|
- // 获取第一页并添加图片
|
|
|
+
|
|
|
PDPage page = document.getPage(0);
|
|
|
+ PDRectangle mediaBox = page.getMediaBox();
|
|
|
+ float width = mediaBox.getWidth();
|
|
|
+ float height = mediaBox.getHeight();
|
|
|
+ int rotation = page.getRotation();
|
|
|
+
|
|
|
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
|
|
|
- contentStream.drawImage(image, 400, 750, imageWidth / 2, imageHeight / 2);
|
|
|
+ contentStream.saveGraphicsState(); // 保存当前图形状态
|
|
|
+
|
|
|
+ // 根据页面旋转角度调整坐标系 正常的PDF长宽841.0:595.0 横向排版的是反过来的,需要动态调整插入图片的坐标位置
|
|
|
+ switch (rotation) {
|
|
|
+ case 90:
|
|
|
+ // 逆时针旋转90度,并平移到正确位置
|
|
|
+ contentStream.transform(Matrix.getTranslateInstance(0, height));
|
|
|
+ contentStream.transform(Matrix.getRotateInstance(Math.toRadians(-90), 0, 0));
|
|
|
+ break;
|
|
|
+ case 180:
|
|
|
+ contentStream.transform(Matrix.getTranslateInstance(width, height));
|
|
|
+ contentStream.transform(Matrix.getRotateInstance(Math.toRadians(-180), 0, 0));
|
|
|
+ break;
|
|
|
+ case 270:
|
|
|
+ contentStream.transform(Matrix.getTranslateInstance(width, 0));
|
|
|
+ contentStream.transform(Matrix.getRotateInstance(Math.toRadians(-270), 0, 0));
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ // 无旋转,无需调整
|
|
|
+ break;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 动态计算图片位置(右上角,边距10)
|
|
|
+ float margin = 10f;
|
|
|
+ float x = width - imageWidth - margin;
|
|
|
+ float y = height - imageHeight - margin;
|
|
|
+
|
|
|
+ // 确保坐标在页面范围内
|
|
|
+ x = Math.max(x, margin);
|
|
|
+ y = Math.max(y, margin);
|
|
|
+
|
|
|
+ contentStream.drawImage(image, x, y, imageWidth/2, imageHeight/2);
|
|
|
+ contentStream.restoreGraphicsState(); // 恢复图形状态
|
|
|
+
|
|
|
contentStream.close();
|
|
|
document.save(outputStream);
|
|
|
document.close();
|