繁体   English   中英

为什么我不能用 itext 生成 pdf 文件

[英]Why i cannot generate pdf file with itext

所以我试图从我的 [database] 表中获取数据,然后从中生成一个 PDF 。 首先,我尝试 select 使用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"));

它有效。 但我希望路径是动态的而不是硬编码的。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM