我正在尝试将openpdf用于动态字段。
maven:
<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>1.3.8</version>
</dependency>查找字段:(动态查找字段名)
Type type = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) type;
Class<V> entity = (Class<V>) pt.getActualTypeArguments()[0];
// create Header
List<String> columnNames = new ArrayList<>();
Field[] superFields = entity.getSuperclass().getDeclaredFields();
for (Field field : superFields) {
if ( ! field.getName().equals("serialVersionUID"))
columnNames.add( field.getName() );
}
Field[] fields = entity.getDeclaredFields();
for (Field field : fields) {
if ( ! field.getName().equals("serialVersionUID"))
columnNames.add( field.getName() );
}
for (String columnName : columnNames) {
cell.setPhrase( new Phrase(columnName));
table.addCell(cell);
}
document.add(table);
document.close();如何改变动态这一点?(我只对User对象使用此代码)
List<User> users = repository.findAll();
for (User user : Users) {
cell.setPhrase( new Phrase( user.getId() ));
cell.setPhrase( new Phrase( user.getFirstName() ));
cell.setPhrase( new Phrase( user.getLastName() ));
}PDF出口有更好的自由吗?
谢谢
发布于 2022-05-09 05:47:17
我为这个问题编写了一些代码:
首先,我可以获得名称方法的列表:
private final MethodCache cache = new MethodCache();
public List<Object> toArray(Object source, String[] nameMapping) throws Exception {
extractBeanValues(source, nameMapping);
return beanValues;
}
private final MethodCache cache = new MethodCache();
private final List<Object> beanValues = new ArrayList<>();
private void extractBeanValues(Object source, String[] nameMapping) throws Exception {
if (source == null)
throw new NullPointerException("the bean to write should not be null");
if (nameMapping == null) {
throw new NullPointerException(
"the nameMapping array can't be null as it's used to map from fields to columns");
}
this.beanValues.clear();
for (int i = 0; i < nameMapping.length; i++) {
String fieldName = nameMapping[i];
if (fieldName == null) {
this.beanValues.add(null);
} else {
Method getMethod = this.cache.getGetMethod(source, fieldName);
try {
this.beanValues.add(getMethod.invoke(source, new Object[0]));
} catch (Exception e) {
throw new Exception(
String.format("error extracting bean value for field %s", new Object[] { fieldName }), e);
}
}
}
}第二次转换为List<Object>:
private final List<Object> beanValues = new ArrayList<>();
public List<Object> toArray(Object source, String[] nameMapping) throws Exception {
extractBeanValues(source, nameMapping);
return beanValues;
}和end :
List<V> list = repository.findAll();
for (V v: list ) {
toArray(v, names);
for (Object obj: this.beanValues) {
cell.setPhrase( new Phrase( obj.toString() ) );
table.addCell(cell);
}
}现在我可以用动态对象和字段调用该方法了。
https://stackoverflow.com/questions/72158531
复制相似问题