【问题标题】:Exporting PDF files in Java用 Java 导出 PDF 文件
【发布时间】:2013-05-16 13:17:39
【问题描述】:

我有一个从 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());
   }
}

谢谢

【问题讨论】:

标签: java export-to-pdf


【解决方案1】:

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

【讨论】:

  • 在商业应用中您必须使用旧的 2.1.7 版本或付费。不过2.1.7还是不错的。
【解决方案2】:

我有一个示例代码:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-30
      • 2017-11-24
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      相关资源
      最近更新 更多