我正在尝试使用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();
}
}
}
答案 0 :(得分:3)
我用我的测试数据(不幸的是你没有与你分享)重现了你的问题我得到了
修复很简单,我删除了两行
float64
现在得到
对于一般情况,您还应将裁剪框左下角的坐标添加到Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
contentStream.transform(mt);
和x_adjusted
y_adjusted
(AddImage测试方法float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX();
float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY();
)