【发布时间】:2022-07-29 13:31:41
【问题描述】:
所以我尝试从我的 [database] 表中获取数据,然后从中生成 PDF。首先,我尝试使用JFileChooser 选择要保存文件的目录。然后,我尝试在所选目录中创建 PDF。最后,我尝试从我的数据库中获取所有数据并将其插入到我的 PDF 中。
问题是没有生成 PDF 文件并且没有显示错误消息。
String path = \"\";
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int x = j.showSaveDialog(this);
if(x == JFileChooser.APPROVE_OPTION){
path = j.getSelectedFile().getPath();
}
try{
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream(path + \"abcd123.pdf\"));
doc.open();
PdfPTable tbl = new PdfPTable(2);
tbl.addCell(\"Class ID\");
tbl.addCell(\"Class Name\");
try{
String query = \"SELECT * FROM kelas\";
PreparedStatement st = (PreparedStatement)conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()) {
tbl.addCell(rs.getString(\"id\"));
tbl.addCell(rs.getString(\"nama\"));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
doc.add(tbl);
doc.close();
} catch (Exception e) {
System.err.println(e);
}
所以我试图改变路径
PdfWriter.getInstance(doc, new FileOutputStream(path + \"abcd123.pdf\"))
至
PdfWriter.getInstance(doc, new FileOutputStream(\"C:\\\\Users\\\\Daniel\\\\Desktop\\\\tes.pdf\"));
它有效。但我希望路径是动态的而不是硬编码的。
-
您为 PDF 使用的库是什么?在许多库中,您有 doc.save() (或类似方法)来保存更改。
-
@Level_Up 我使用了 itext 库。我改变了问题。因为,我刚刚尝试在 pdf 中生成一个段落的第一个问题已经在工作。在这个更新的问题中。我试图从我的数据库中获取数据并将其插入到 pdf 中。仍在弄清楚为什么没有生成。