用Java导出PDF文件

use*_*013 6 java export-to-pdf

我有一个表从SQL DB获取它的数据.我正在尝试找到将该表导出为PDF文件的最简单方法.没什么好看的,只是标题和表格的内容.我在这里搜索并检查外部包(docmosis等),但没有下定决心.我是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());
   }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Ada*_*rsh 8

您可以使用iText PDF Api.它很容易使用.你只需要下载jar,导入课程就可以了.查看本教程,了解如何使用这些类

  • 在商业应用程序中,您必须使用旧的2.1.7版本或付费.2.1.7虽然相当不错. (4认同)

小智 6

我有一个示例代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

只需致电:

createSamplePDF(new String[]{"col1", "col2"}, new String[][]{{"rw11", "rw12"},{"rw21", "rw22"}});
Run Code Online (Sandbox Code Playgroud)