我对 itext 库有一个问题,可以描述如下:
我想通过在第二段上使用 spacingBefore 属性在两个段落之间放置一个垂直间距。
问题是,从一定的空间单位值(默认点单位),itext 导致第二段显示在新页面上,即使显然有足够的空间将 2 段放在同一页上。
这段代码说明了这种情况:
public static void main(String[] args) throws Exception {
Document document = new Document();
OutputStream result = new FileOutputStream("output.pdf");
PdfWriter.getInstance(document, result);
document.open();
Paragraph paragraph1 = new Paragraph("First paragraph");
Paragraph paragraph2 = new Paragraph("Second paragraph");
//380 causes the new page...
paragraph2.setSpacingBefore(380f);
//...whereas 370 does not
// paragraph2.setSpacingBefore(370f);
document.add(paragraph1);
document.add(paragraph2);
document.close();
}
有人对这种奇怪的行为有解释吗?
提前致谢
最佳答案
我已将您的代码复制到一个独立示例中。您可以在此处找到此示例:ParagraphSpacingBefore
public void createPdf(String filename) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
Paragraph paragraph1 = new Paragraph("First paragraph");
Paragraph paragraph2 = new Paragraph("Second paragraph");
paragraph2.setSpacingBefore(380f);
document.add(paragraph1);
document.add(paragraph2);
document.close();
}
我不认为这与您正在做的有什么不同,但就我而言,这两段都在一个页面上。请查看paragraph_spacebefore.pdf自己找出答案。
也许您还在 paragraph1
之前应用了间距,或者您使用的是旧版本的 iText(例如 2.1.7,一个过时的版本,不应再使用)或者也许您正在使用 iText 的非官方版本(例如 iText 4,一个由第三方创建的版本,没有人知道它是否合法使用)。
简而言之:问题无法解释,因为问题无法重现。
关于java - 应用于 Paragraph 的 itext spacingBefore 属性导致新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945733/