我的任务是创建一个最多10000条记录的PDF文件。每条记录在JSON表示中都是一个Java对象。10个对象大约为15000字节(jsonString.length())。生成的包含1000条记录的文件在磁盘上占用大约900KB。然后我会这样做:
private static Font font = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
Paragraph p = new Paragraph();
p.add(new Paragraph("Title", font));
String jsonString = "{....}"; // 10 objects; jsonString.length()==15000
for (int i = 0; i < 100; i++) // add 1000 objects
p.add(new Paragraph(jsonString, font));
document.add(p);
document.close();但是当我运行这段代码时,我在等待80s。为什么它这么慢?有没有可能做得更快?
更新
当我使用只有200个对象的单个段落时,它的运行速度更慢:
Paragraph p = new Paragraph("{......}"); // ~300_000 bytes
document.add(p);将200个对象保存为PDF需要2分钟,而第一种情况下将1000个对象保存为PDF需要1.5分钟。
发布于 2020-08-14 15:43:59
我找到了一个解决方案,但使用的是OpenPdf库。我创建的pdf文件有10000条记录,从7秒到17秒,pdf大小从4到32MB,取决于单个记录的大小。
public static void main(String[] args) throws FileNotFoundException {
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("OpenPDF-example.pdf"));
//setting font family, color
Font font = new Font(Font.HELVETICA, 10);
doc.open();
for (int j=0; j<10000; j++) {
Paragraph para = new Paragraph("single record from 1 to 5kB", font);
doc.add(para);
}
doc.close();
writer.close();
}注意,需要按小段添加数据。当我试图在一个段落中添加所有数据时,速度非常慢(超过10分钟)。
https://stackoverflow.com/questions/63379494
复制相似问题