Itext PDF 对段落的处理速度很慢
Itext PDF works slowly with Paragraph
我的任务是创建一个最多包含 10000 条记录的 PDF 文件。每条记录都是 JSON 表示中的 Java 对象。 10 个对象是 ~15000 字节 (jsonString.length()
)。生成的包含 1000 条记录的文件占用大约 900 KB 的磁盘空间。然后我做:
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();
但是当我 运行 这段代码时,我正在等待 80 秒。为什么这么慢?有没有可能做得更快?
更新
当我使用只有 200 个对象的单个段落时,它的工作速度更慢:
Paragraph p = new Paragraph("{......}"); // ~300_000 bytes
document.add(p);
将 200 个对象保存为 PDF 需要 2 分钟,而不是第一种情况下将 1000 个对象保存为 1.5 分钟。
我找到了解决方案,但使用的是 OpenPdf 库。我创建了包含 10000 条记录的 pdf 文件,耗时 7 到 17 秒,pdf 大小从 4 到 32 MB,具体取决于单个记录的大小。
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 分钟)。
我的任务是创建一个最多包含 10000 条记录的 PDF 文件。每条记录都是 JSON 表示中的 Java 对象。 10 个对象是 ~15000 字节 (jsonString.length()
)。生成的包含 1000 条记录的文件占用大约 900 KB 的磁盘空间。然后我做:
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();
但是当我 运行 这段代码时,我正在等待 80 秒。为什么这么慢?有没有可能做得更快?
更新
当我使用只有 200 个对象的单个段落时,它的工作速度更慢:
Paragraph p = new Paragraph("{......}"); // ~300_000 bytes
document.add(p);
将 200 个对象保存为 PDF 需要 2 分钟,而不是第一种情况下将 1000 个对象保存为 1.5 分钟。
我找到了解决方案,但使用的是 OpenPdf 库。我创建了包含 10000 条记录的 pdf 文件,耗时 7 到 17 秒,pdf 大小从 4 到 32 MB,具体取决于单个记录的大小。
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 分钟)。