2013-05-21 91 views
4

我有一张从SQL DB获取数据的表。 我试图找到最简单的方式将该表导出为PDF文件。 没什么特别的,只是一个标题和它的内容表。 我在这里搜索过,也检查到外部软件包(docmosis等),但没有下定决心。 我在Java中相当新,我正在寻找将表格导出为pdf的最简单方法。用Java导出PDF文件

试图回答可能提出的问题,这里是我如何填充表:

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

感谢

+1

可能的dublicate http://stackoverflow.com/questions/735 5025/create-pdf-with-java – cb0

+0

您可以查看此链接 http://stackoverflow.com/questions/13717743/how-to-export-table-displayed-on-jsp-to-pdf-in -java-strust2/13952620?noredirect = 1#13952620 –

+0

您可以参考以下链接中的答案张贴 http://stackoverflow.com/questions/13717743/how-to-export-table-displayed- on-jsp-to-pdf-in-java-strust2/13952620?noredirect = 1#13952620 –

回答

7

您可以使用iText的PDF API。这很容易使用。你只需要下载jar,导入课程,你就可以走了。看看这个tutorial关于如何使用类

+4

在商业应用程序中,您必须使用旧的2.1.7版本或支付。 2.1.7虽然不错。 – lbalazscs

0

使用任何java pdf生成库。 也许一个ms访问数据库可以为你做,但JDBC不提供这种功能,它不应该。

5

我有一个示例代码:

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

只要致电:

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

此代码使用iText – 3d5oN