我想在用户单击按钮时将JTable内的数据提取到pdf文件中。
下面是我的代码:
public void actionPerformed(ActionEvent e) {
try {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("table.pdf"));
doc.open();
PdfPTable pdfTable = new PdfPTable(table.getColumnCount());
//adding table headers
for (int i = 0; i < table.getColumnCount(); i++) {
pdfTable.addCell(table.getColumnName(i));
}
//extracting data from the JTable and inserting it to PdfPTable
for (int rows = 0; rows < table.getRowCount() - 1; rows++) {
for (int cols = 0; cols < table.getColumnCount(); cols++) {
pdfTable.addCell(table.getModel().getValueAt(rows, cols).toString());
}
}
doc.add(pdfTable);
doc.close();
System.out.println("done");
} catch (DocumentException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:0)
您的PDF生成代码看起来不错,假设您已经在磁盘上生成了文件。您可以使用下面的文件下载
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class ExportJtable extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/pdf");
PrintWriter out = response.getWriter();
String filename = "table.pdf";
String filepath = "/user/home";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream = new FileInputStream(filepath + filename);
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
}