Java 如何使用ApachePDFBox将图像移动到PDF页面顶部?
我正在使用Java生成报告。我的要求之一是创建一个PDF文档,在页面顶部包含公司徽标。我无法找到实现这一目标的方法 我在Java类中有以下方法:Java 如何使用ApachePDFBox将图像移动到PDF页面顶部?,java,pdfbox,Java,Pdfbox,我正在使用Java生成报告。我的要求之一是创建一个PDF文档,在页面顶部包含公司徽标。我无法找到实现这一目标的方法 我在Java类中有以下方法: public void createPdf() { PDDocument document = null; PDPage page = null; ServletContext servletContext = (ServletContext) FacesContext
public void createPdf() {
PDDocument document = null;
PDPage page = null;
ServletContext servletContext = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
try {
File f = new File("Afiliado_2.pdf");
if (f.exists() && !f.isDirectory()) {
document = PDDocument.load(new File("Afiliado_2.pdf"));
page = document.getPage(0);
} else {
document = new PDDocument();
page = new PDPage();
document.addPage(page);
}
PDImageXObject pdImage = PDImageXObject.createFromFile(
servletContext.getRealPath("/resources/images/logo.jpg"),
document);
PDPageContentStream contentStream = new PDPageContentStream(
document, page, AppendMode.APPEND, true);
contentStream.drawImage(pdImage, 0, 0);
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Afiliado_2.pdf");
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
该图像当前显示在PDF的底部。我知道我需要修改的行是
contentStream.drawImage(pdImage,0,0)
但是我需要指定什么坐标才能显示在页面顶部?通常PDF页面的坐标系从左下角开始。所以
contentStream.drawImage(pdImage, 0, 0);
此时您正在绘制图像。您可以使用
page.getMediaBox();
并用它来定位你的形象,例如
PDRectangle mediaBox = page.getMediaBox();
// draw with the starting point 1 inch to the left
// and 2 inch from the top of the page
contentStream.drawImage(pdImage, 72, mediaBox.getHeight() - 2 * 72);
PDF文件通常指定72点到1物理英寸。可能与此有关。AppendMode.APPEND是Maruans答案的补充-对于现有文件,使用带有第5个参数(resetContext)的PDPageContentStream构造函数可能更安全。为什么要使用72?这是PDF的标准单位。72点等于1英寸。很抱歉,我认为这是理所当然的。您可能应该使用裁剪框而不是媒体框。@Erick Maruan在他的回答中使用了
page.getMediaBox()
。只需使用page.getCropBox()
即可。并且仅当您在PDFBOx2.0.x上时才使用这些方法;如果您仍然使用PDFBox 1.8.x,则应使用page.findMediaBox()
或page.findCropBox()
。您好,我们如何使用相同的代码contentStream.drawImage(pdImage,72,mediaBox.getHeight()-2*72);对于像素,如果我的x和y是像素单位?