我使用PDFBox在Java中生成报告。我的一个要求是创建一个PDF文档,其中包含页面顶部的公司徽标。我无法找到实现这一目标的方法。我在Java类中有以下方法:
import sys,os,time,logging
RUN_RELOADER = True
logger = logging.getLogger(__name__)
whitelist = ['webapp2', 'paste', 'logging']
# this code is from autoreloader
_mtimes = {}
_win = (sys.platform == "win32")
_error_files = []
_cached_modules = set()
_cached_filenames = []
def gen_filenames(only_new=False):
global _cached_modules, _cached_filenames
module_values = set(sys.modules.values())
_cached_filenames = clean_files(_cached_filenames)
if _cached_modules == module_values:
# No changes in module list, short-circuit the function
if only_new:
return []
else:
return _cached_filenames + clean_files(_error_files)
new_modules = module_values - _cached_modules
new_filenames = clean_files(
[filename.__file__ for filename in new_modules
if hasattr(filename, '__file__')])
_cached_modules = _cached_modules.union(new_modules)
_cached_filenames += new_filenames
if only_new:
return new_filenames + clean_files(_error_files)
else:
return _cached_filenames + clean_files(_error_files)
def clean_files(filelist):
filenames = []
for filename in filelist:
if not filename:
continue
if filename.endswith(".pyc") or filename.endswith(".pyo"):
filename = filename[:-1]
if filename.endswith("$py.class"):
filename = filename[:-9] + ".py"
if os.path.exists(filename):
filenames.append(filename)
return filenames
# this code is modified from autoreloader
def check_code_changed():
global _mtimes, _win
for filename in gen_filenames():
stat = os.stat(filename)
mtime = stat.st_mtime
if _win:
mtime -= stat.st_ctime
if filename not in _mtimes:
_mtimes[filename] = mtime
continue
if mtime != _mtimes[filename]:
_mtimes = {}
try:
del _error_files[_error_files.index(filename)]
except ValueError:
pass
mname = filename.split('/')[-1].split('.')[0]
logger.info('CHANGED %s, RELOADING %s' % (filename,mname))
try:
reload(sys.modules[mname])
except:
pass
return False
def reloader_thread():
while RUN_RELOADER:
check_code_changed()
time.sleep(1)
图像当前显示在PDF的底部。我知道我需要修改的行是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();
}
}
,但我需要指定哪些坐标才能显示在页面顶部?
答案 0 :(得分:4)
通常,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个物理英寸。