如何正确配置使用text-pdf 8生成的PDF的行间距

问题描述 投票:0回答:1

我正在一个应用程序中生成一些 PDF,并且我正在使用 itext-pdf 库进行一些 POC。

我在寻找正确的行间距时遇到一些问题。我手动生成了一个我想要实现的示例,它应该如下所示:

PDF generated manually

但是我得到的最接近的是这样的:

PDF generated programmatically

生成第二个的代码是这样的:

@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);
    }
}

我应该如何更改代码才能达到预期的结果?预先感谢您的评论

pdf itext pdf-generation
1个回答
0
投票

您可以在两个段落上使用 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));

Result

© www.soinside.com 2019 - 2024. All rights reserved.