为什么 Java 在转换为 PDF 期间删除段落之间的空白 space?

Why does Java delete the blank space between paragraphs during conversion to PDF?

为什么 Java 删除段落之间的空格?我正在使用 iText5 将 .rtf 文件转换为 PDF。该文件包含报告,每个报告都在其自己的页面上。转换后,段落之间的空格被删除,使分页与转换前不一样。

我尝试使用矩形设置页面大小,但由于报表的行数不同,一些报表仍与其他报表共享同一页面。

//Set PDF layout
//Rectangle rectangle = new Rectangle (0, 0, 1350, 16615);
Document document = new Document(PageSize.A4.rotate());
document.setMargins(13, 0, 10, 10);           
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();

br = new BufferedReader(new FileReader(TEXT));

String line;
Paragraph p;       
//PDF font configuration
Font normal = new Font(FontFamily.COURIER, 5);
Font bold = new Font(FontFamily.COURIER, 5, Font.BOLD);

//add page to PDF       
boolean title = true;
    while ((line = br.readLine()) != null) {               
    p = new Paragraph(line, title ? bold : normal);
        document.add(p);
     }           
        document.close();

我不希望程序删除段落之间的空格。

首发

我怀疑您输入的是否真的是 rtf 文件。一个 rtf 文件看起来像这样

{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard
This is some {\b bold} text.\par
}

(来自Wikipedia about Rich Text Format

如果将该文件输入到代码中,您会得到类似

的内容

这可能不是您想要的。

所以让我们假设您的输入是您逐行阅读的纯文本。

如何防止空行丢失

请注意,从空字符串构造的 Paragraph 实际上不需要垂直 space,例如

doc.add(new Paragraph("1 Between this line and line 3 there is an empty paragraph."));
doc.add(new Paragraph(""));
doc.add(new Paragraph("3 This is line 3."));
doc.add(new Paragraph("4 Between this line and line 6 there is a paragraph with only a space."));
doc.add(new Paragraph(" "));
doc.add(new Paragraph("6 This is line 6."));

(EmptyParagraphs 测试 testEmptyParagraphsForFazriBadri)

结果

观察到第 2 行有效地被删除了。

原因是 Paragraph(String string) 构造函数是一个方便的快捷方式,

p = new Paragraph(string);

本质上等同于

p = new Paragraph();
if (string != null && string.length() != 0) {
    p.add(new Chunk(string));
}

因此,对于new Paragraph(""),段落中没有添加块,它是空的,其块不需要垂直space。

在这种情况下,您可以开始使用段落本身或周围段落的 LeadingSpacingBeforeSpacingAfter,但最简单的方法肯定是用包含 space " ".

的字符串替换空字符串 ""

在你的情况下,可以通过替换

来完成
while ((line = br.readLine()) != null) {               
    p = new Paragraph(line, title ? bold : normal);
    document.add(p);
}           

来自

while ((line = br.readLine()) != null) {               
    p = new Paragraph(line.length() == 0 ? " " : line, title ? bold : normal);
    document.add(p);
}