【发布时间】: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 它也不会反转图像。
-
“反转”是指“反转颜色”吗?我以为你的意思是倒置坐标。请分享图片