Home > Net >  Why i cannot generate pdf file with itext
Why i cannot generate pdf file with itext

Time:07-29

So I tried to get data from my [database] table then generate a PDF from it. First, I tried to select the directory where I want to save the file with JFileChooser. Then, I tried to create the PDF inside the selected directories. Last, I tried to get all the data from my DB and insert it to my PDF.

The problem is that the PDF file is not generated and there is no error message showing.

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);
}

So I tried to change the path from

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

to

PdfWriter.getInstance(doc, new FileOutputStream("C:\\Users\\Daniel\\Desktop\\tes.pdf"));

And it works. But I want the path to be dynamic and not hard coded.

CodePudding user response:

So from your last edit of your question I will suggest to try

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

Also you can try to print the path to see what is the value of it.

By the way you should use file separator that works on Windows and Unix(Linux):

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