You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFBox插入PDF文本出现倒置问题,求解决方案

PDFBox插入文本倒置问题解决方法

我正在使用PDFBox向PDF中插入文本,使用以下代码执行操作,但出现了文本倒置的情况:

try (PDDocument doc = PDDocument.load(new ByteArrayInputStream(decodedBytes))) {
        PDPage firstPage = doc.getPage(0);

        try (PDPageContentStream contentStream = new PDPageContentStream(doc, firstPage, PDPageContentStream.AppendMode.APPEND, true, true)) {
            contentStream.setFont(PDType1Font.HELVETICA, 48);
            contentStream.setStrokingColor(Color.BLACK);
            contentStream.beginText();
            contentStream.newLineAtOffset(3000, 1500);
            contentStream.showText(timestampText);
            contentStream.endText();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        doc.save(baos);
        return Base64.getEncoder().encodeToString(baos.toByteArray());
    
}

实际插入的文本呈现倒置状态,无法正常阅读。


解决方法

文本倒置的核心原因是PDF页面存在旋转属性,导致默认文本坐标系与页面方向冲突。可通过以下步骤修复:

  • 获取页面旋转角度:通过PDPage.getRotation()获取页面的旋转值(常见为0、90、180、270度)
  • 适配文本矩阵:根据页面旋转角度,使用setTextMatrix调整文本的变换矩阵,让文本方向与页面一致
  • 修正偏移坐标:旋转后坐标系原点变化,需重新计算newLineAtOffset的参数值

修改后的代码示例

try (PDDocument doc = PDDocument.load(new ByteArrayInputStream(decodedBytes))) {
    PDPage firstPage = doc.getPage(0);
    int pageRotation = firstPage.getRotation();
    PDRectangle pageSize = firstPage.getMediaBox();

    try (PDPageContentStream contentStream = new PDPageContentStream(doc, firstPage, PDPageContentStream.AppendMode.APPEND, true, true)) {
        contentStream.setFont(PDType1Font.HELVETICA, 48);
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.beginText();
        
        // 根据页面旋转调整文本变换矩阵
        switch (pageRotation) {
            case 90:
                contentStream.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(90), pageSize.getWidth(), 0));
                break;
            case 180:
                contentStream.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(180), pageSize.getWidth(), pageSize.getHeight()));
                break;
            case 270:
                contentStream.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(270), 0, pageSize.getHeight()));
                break;
            default:
                // 0度无需额外调整
                break;
        }
        
        // 适配旋转后的坐标系设置偏移(示例值,可根据需求修改)
        contentStream.newLineAtOffset(300, 150);
        contentStream.showText(timestampText);
        contentStream.endText();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    doc.save(baos);
    return Base64.getEncoder().encodeToString(baos.toByteArray());
}

补充说明

  • 若页面存在非标准旋转角度,可通过Matrix类自定义旋转变换参数
  • 偏移坐标需根据旋转后的坐标系重新计算,比如90度旋转后,原x轴方向转为y轴方向,需调整偏移值适配新原点

内容的提问来源于stack exchange,提问作者Saurabh Negi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 07:47:06