[英]Exporting PDF files in Java
我有一個表從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());
}
}
謝謝
您可以使用iText PDF Api。 它很容易使用。 你只需要下載jar,導入課程就可以了。 查看本教程 ,了解如何使用這些類
我有一個示例代碼:
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"}});
使用任何java pdf生成庫。 也許ms訪問數據庫可以為您做到這一點,但JDBC不提供這種功能,它不應該。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.