我正在使用itext 7 pdf从jdbc查询生成pdf.它可以处理4000条记录,但一旦我们在表中插入17000条记录,我就开始让Java内存不足.我一次获取所有数据,如下所示,如何修改它以使用分页查询,并将所有分页结果缝合到一个PDF中.
这是我的驱动程序代码,它输入表名和HttpServlet,并将其传递给实现ResultsTextRactor的类.
public void generatePDF(String tableName, HttpServletResponse response, String[] filter) throws DataAccessException, IOException {
//Table validation logic
String sql = "select * from table";
mainJdbcTemplate.query(sql, paramMap,
new StreamingPDFResultSetExtractor(response.getOutputStream(), tableName));
}
实现结果集提取器的自定义类.我输入所有结果集数据,并使用itext生成PDF.
public class StreamingPDFResultSetExtractor implements ResultSetExtractor<Void> {
private final OutputStream os;
private String tableName;
/**
* @param os the OutputStream to stream the PDF to
*/
public StreamingPDFResultSetExtractor(final OutputStream os, final String tableName) {
this.os = os;
this.tableName = tableName;
}
@Override
public Void extractData(final ResultSet rs) throws SQLException {
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(os));
// Creating a Document and setting page size
Document document = new Document(pdfDoc, new PageSize(2384, 3370));
// Adding a new page
pdfDoc.addNewPage();
final var rsmd = rs.getMetaData();
final var columnCount = rsmd.getColumnCount();
try {
log.info("Generating PDF");
Paragraph tablename = new Paragraph(tableName);
tablename.setFontSize(20);
// Add table
Table table = new Table(columnCount);
// Set width of table
table.setWidth(UnitValue.createPercentValue(100)).setFixedLayout();
table.setHorizontalAlignment(HorizontalAlignment.CENTER);
table.setTextAlignment(TextAlignment.CENTER);
// Header Font and color
DeviceRgb hColor = new DeviceRgb(3, 148, 252);
for (var i = 1; i <= columnCount; i++) {
Cell hcell = new Cell();
hcell.add(new Paragraph(rsmd.getColumnName(i)));
hcell.setFontSize(14);
hcell.setBackgroundColor(hColor);
table.addHeaderCell(hcell);
}
while (rs.next()) {
for (var i = 1; i <= columnCount; i++) {
final var value = rs.getObject(i);
String v = value == null ? "" : value.toString();
Cell cell = new Cell();
cell.add(new Paragraph(v));
table.addCell(cell);
}
}
}
document.add(tablename);
document.add(table);
document.close();
log.info("PDF generation complete");
} catch (Exception ex) {
log.error("Error occurred: {0}", ex);
}
return null;
}
}