Domanda

I have a table that gets it's data from a SQL DB. I'm trying to find the easiest way to export that table, as it is, into a PDF file. Nothing fancy, just a title and the table with it's content. I've searched around here and also checked into external packages (docmosis and such), but did not make up my mind. I am fairly new in Java and I'm looking for the easiest way to export a table to a pdf.

Trying to answer possible questions, here's how I populate the table:

try {
   result = DBConnection.getTableContent("customers", attributes, where, null, null);
   DefaultTableModel model = (DefaultTableModel) searchTable.getModel();
   model.setRowCount(0);
   for (int i = 0; i < result.size(); i++) {                        
      model.addRow(result.get(i).toArray());
   }
}

Thanks

È stato utile?

Soluzione

You can use iText PDF Api. It is pretty easy to use. You just have to download the jar, import the class and you are good to go. Check out this tutorial on how to use the classes

Altri suggerimenti

I have a sample code:

public static void createSamplePDF(String header[], String body[][]) throws Exception{
    Document documento = new Document();
    //Create new File
    File file = new File("D:/newFileName.pdf");
    file.createNewFile();
    FileOutputStream fop = new FileOutputStream(file);
    PdfWriter.getInstance(documento, fop);
    documento.open(); 
    //Fonts
    Font fontHeader = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    Font fontBody = new Font(Font.FontFamily.COURIER, 12, Font.NORMAL);
    //Table for header
    PdfPTable cabetabla = new PdfPTable(header.length);
    for (int j = 0; j < header.length; j++) {
        Phrase frase = new Phrase(header[j], fontHeader);
        PdfPCell cell = new PdfPCell(frase);
        cell.setBackgroundColor(new BaseColor(Color.lightGray.getRGB()));
        cabetabla.addCell(cell);
    }
    documento.add(cabetabla);
    //Tabla for body
    PdfPTable tabla = new PdfPTable(header.length);
    for (int i = 0; i < body.length; i++) {
        for (int j = 0; j < body[i].length; j++) {
            tabla.addCell(new Phrase(body[i][j], fontBody));
        }
    }
    documento.add(tabla);
    documento.close();
    fop.flush();
    fop.close();
}

just call:

createSamplePDF(new String[]{"col1", "col2"}, new String[][]{{"rw11", "rw12"},{"rw21", "rw22"}});

Use any java pdf generation library. Maybe an ms access database could do that for you, but JDBC doesn't provide that kind of feature, and it shouldnt.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top