一、PDF 页面坐标系

  • PDF 页面的原点 (0, 0) 位于页面的左下角,X 轴向右为正,Y 轴向上为正

二、PDF 页面尺寸获取

PDPage page = new PDPage();

PDRectangle mediaBox = page.getMediaBox();

float width = mediaBox.getWidth();
float height = mediaBox.getHeight();

System.out.println("mediaBox: " + mediaBox);
System.out.println("width: " + width);
System.out.println("height: " + height);
# 输出结果

mediaBox: [0.0,0.0,612.0,792.0]
width: 612.0
height: 792.0
try (PDDocument document = PDDocument.load(new File("pdf/example.pdf"))) {
    PDPage page = document.getPage(0);

    PDRectangle mediaBox = page.getMediaBox();

    float width = mediaBox.getWidth();
    float height = mediaBox.getHeight();

    System.out.println("mediaBox: " + mediaBox);
    System.out.println("width: " + width);
    System.out.println("height: " + height);
} catch (Exception e) {
    e.printStackTrace();
}
# 输出结果

mediaBox: [0.0,0.0,612.0,792.0]
width: 612.0
height: 792.0

三、PDF 页面位置计算

1、使图片位于 PDF 页面的左上角
try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage();
    document.addPage(page);

    PDImageXObject pdImage = PDImageXObject.createFromFile("pdf/dzs.jpeg", document);

    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

        // 获取 PDF 页面的尺寸
        PDRectangle mediaBox = page.getMediaBox();
        float pdfWidth = mediaBox.getWidth();
        float pdfHeight = mediaBox.getHeight();

        // 获取图片的尺寸
        float imgWidth = pdImage.getWidth() * 0.25f;
        float imgHeight = pdImage.getHeight() * 0.25f;

        float x = 0;
        float y = pdfHeight - imgHeight;

        contentStream.drawImage(pdImage, x, y, imgWidth, imgHeight);
    } catch (IOException e) {
        e.printStackTrace();
    }

    document.save("pdf/image_position_example.pdf");
} catch (IOException e) {
    e.printStackTrace();
}
2、使图片位于 PDF 页面的左下角
...

float x = 0;
float y = 0;

...
3、使图片位于 PDF 页面的右上角
...

float x = pdfWidth - imgWidth;
float y = pdfHeight - imgHeight;

...
4、使图片位于 PDF 页面的右下角
...

float x = pdfWidth - imgWidth;
float y = 0;

...
5、使图片靠左垂直居中
...

float x = 0;
float y = (pdfHeight - imgHeight) / 2;

...
6、使图片靠右垂直居中
...

float x = pdfWidth - imgWidth;
float y = (pdfHeight - imgHeight) / 2;

...
7、使图片靠上水平居中
...

float x = (pdfWidth - imgWidth) / 2;
float y = pdfHeight - imgHeight;

...
8、使图片靠下水平居中
...

float x = (pdfWidth - imgWidth) / 2;
float y = 0;

...
9、使图片居中
...

float x = (pdfWidth - imgWidth) / 2;
float y = (pdfHeight - imgHeight) / 2;

...
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐