我查了下似乎itext不支持直接添加元数据,我的方法是根据原来的PDF生成一篇同样的文件,然后删除原来的PDF,再将新生成的文件改名。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
public class PdfMetadataSetter {
public static boolean writeDocMetadata(String docName, Map Properties){
boolean isSuccess = false;
PdfReader reader=null;
PdfStamper stamp=null;
/*
* Infact i create a new file and write metadata to the file.
* after that i delete the old file and rename new file.
*/
try {
reader = new PdfReader(docName);
String newFileName=getNewFileName(docName);
stamp = new PdfStamper(reader,
new FileOutputStream(newFileName));
stamp.setMoreInfo((HashMap)Properties);
stamp.close();
File oldFile=new File(docName);
oldFile.delete();
File newFile=new File(newFileName);
newFile.renameTo(new File(docName));
} catch (Exception de) {
de.printStackTrace();
}finally{
if(reader!=null)
reader.close();
try {
if(stamp!=null)
stamp.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return isSuccess;
}
private static String getNewFileName(String fileName){
String newFileName=fileName.substring(0,(fileName.lastIndexOf(".")))+"2.pdf";
return newFileName;
}
}
觉得这么做不太好,不过暂时没有更好的方法,先将就一下。
卡牌构筑类游戏小结
17 小时前
没有评论:
发表评论