【问题标题】:Draw image at mid position using pdfbox Java使用pdfbox Java在中间位置绘制图像
【发布时间】:2018-04-21 17:50:37
【问题描述】:

我正在尝试使用 pdfbox 将图像添加到 pdf 的中心。下面是我的代码,但我无法在 pdf 中获得正确的图像位置。我按照以下链接In PDFBox, how to change the origin (0,0) point of a PDRectangle object? 获得了正确的位置,但静止图像偏离了中点位置?

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

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.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;

public class imageAppend {
     public static void main (String[] args){

            File file = new File("...pdf file location");
            PDDocument doc = null;
            try 
            {
                doc = PDDocument.load(file);
                PDImageXObject pdImage = PDImageXObject.createFromFile("image file location", doc);

                PDPage page = doc.getPage(0);
                PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);

               float x_pos = page.getCropBox().getWidth();
               float y_pos = page.getCropBox().getHeight();

                float x_adjusted = ( x_pos - w ) / 2;
                float y_adjusted = ( y_pos - h ) / 2;

                Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
            contentStream.transform(mt);
            contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);

                doc.save("new pdf file location");
                doc.close();

            } catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
}

【问题讨论】:

  • 乍一看,图像的左下角居中。
  • 嗨@mkl 我能够在正确的位置绘制图像,但是图像是倒置的。不知道怎么改?
  • 好吧,您的矩阵参数以1f, 0f, 0f, -1f 开头。 -1 表示在 y 坐标方向上的镜像。
  • 即使我做 1f 它也不会反转图像。
  • “反转”是指“反转颜色”吗?我以为你的意思是倒置坐标。请分享图片

标签: java pdfbox


【解决方案1】:

我用我的测试数据重现了你的问题(不幸的是你没有分享你的)我得到了

修复很简单,我删除了这两行

Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
contentStream.transform(mt);

现在得到

对于一般情况,您还应该将裁剪框左下角的坐标添加到您的x_adjustedy_adjusted

float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX();
float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY();

(AddImage测试方法testImageAppendNoMirror)

【讨论】:

    猜你喜欢
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多