【问题标题】:Why i cannot generate pdf file with itext为什么我不能用 itext 生成 pdf 文件
【发布时间】: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 中。仍在弄清楚为什么没有生成。

标签: java swing itext


【解决方案1】:

所以从你上次编辑你的问题我会建议尝试

PdfWriter.getInstance(doc, new FileOutputStream(path + "\\abcd123.pdf"));

您也可以尝试打印路径以查看它的价值。

顺便说一句,您应该使用适用于 Windows 和 Unix(Linux) 的文件分隔符:

String fileSeparator = FileSystems.getDefault().getSeparator();

【讨论】:

  • 哦,是的,我忘了在路径上加上反斜杠
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
相关资源
最近更新 更多