猿问

为什么 Java 在转换为 PDF 的过程中会删除段落之间的空白区域?

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


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


//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();

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


慕妹3242003
浏览 179回答 1
1回答

12345678_0001

首先我怀疑您的输入真的是一个rtf文件。rtf 文件如下所示{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pardThis is some {\b bold} text.\par}(来自维基百科关于富文本格式)如果您将该文件输入到代码中,则会得到类似这大概不是你想要的。因此,让我们假设您的输入是您逐行阅读的纯文本。如何防止空行掉落请注意,从空字符串构造的字符串几乎不需要垂直空间,例如Paragraphdoc.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."));结果观察第 2 行是否被有效删除。原因是构造函数是一个方便的快捷方式,Paragraph(String string)p = new Paragraph(string);本质上等效于p = new Paragraph();if (string != null && string.length() != 0) {    p.add(new Chunk(string));}因此,对于没有将块添加到段落中,它是空的,其块不需要垂直空间。new Paragraph("")在这种情况下,您可以开始使用段落本身或周围段落的,或,但最简单的方法肯定是用包含空格的字符串替换空字符串。LeadingSpacingBeforeSpacingAfter""" "在您的情况下,可以通过更换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);}           
随时随地看视频慕课网APP

相关分类

Java
我要回答