我正在一个应用程序中生成一些 PDF,并且我正在使用 itext-pdf 库进行一些 POC。
我在寻找正确的行间距时遇到一些问题。我手动生成了一个我想要实现的示例,它应该如下所示:
但是我得到的最接近的是这样的:
生成第二个的代码是这样的:
@Test
void testDocumentWithCustomFont() throws FileNotFoundException {
inDocument(CUSTOM_FONT_DESTINATION, document -> {
try {
FontProgram fontProgram = FontProgramFactory.createFont(CUSTOM_FONT);
PdfFont customFont = PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H,
PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
Text title = new Text("THIS IS A TITLE").setFont(customFont);
title.setFontSize(18);
document.add(new Paragraph(title).setTextAlignment(TextAlignment.CENTER).setMarginBottom(12));
Text chordLine = new Text("THIS IS A RED LINE").setFont(customFont);
chordLine.setFontSize(12);
chordLine.setFontColor(ColorConstants.RED);
document.add(new Paragraph(chordLine).setMarginBottom(0));
Text lyricLine = new Text("THIS IS A BLACK LINE THAT SHOULD BE NEAR TO THE RED").setFont(customFont);
lyricLine.setFontSize(12);
document.add(new Paragraph(lyricLine));
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
});
}
private void inDocument(String destination, Consumer<Document> documentConsumer) throws FileNotFoundException {
try (Document document = new Document(new PdfDocument(new PdfWriter(destination)))){
documentConsumer.accept(document);
}
}
我应该如何更改代码才能达到预期的结果?预先感谢您的评论
您可以在两个段落上使用 setMultipliedLeading 来减少段落之间的间距。这是以下代码的结果:
Text title = new Text("THIS IS A TITLE");
title.setFontSize(18);
document.add(new Paragraph(title).setTextAlignment(TextAlignment.CENTER).setMarginBottom(12));
Text chordLine = new Text("THIS IS A RED LINE");
chordLine.setFontSize(12);
chordLine.setFontColor(ColorConstants.RED);
document.add(new Paragraph(chordLine).setMarginBottom(0).setMultipliedLeading(0.7f));
Text lyricLine = new Text("THIS IS A BLACK LINE THAT SHOULD BE NEAR TO THE RED");
lyricLine.setFontSize(12);
document.add(new Paragraph(lyricLine).setMultipliedLeading(0.7f));