首页 > 解决方案 > 使用 iText 如何更改新行之间的距离?

问题描述

我在搞乱itext,我正在更改字体大小,结果我的pdf中出现了一些奇怪的间隔文本:

在此处输入图像描述

我想变成这样的东西:(请原谅糟糕的图像编辑)

在此处输入图像描述

这是我用来输入文本的代码:

private fun setBaseInfo(info: ArrayList<String>): PdfPCell
{
    val cell = PdfPCell()

    val glue = Chunk(VerticalPositionMark())
    val p = Paragraph()
    p.font.size = 8.0f

    for (str in info)
    {
        p.add(glue)
        p.add(str)
        p.add("\n")
    }

    cell.border = Rectangle.NO_BORDER
    cell.addElement(p)

    return cell
}

这是我提供的信息:

private fun foo(): ArrayList<String>
{
    val array = ArrayList<String>()
    array.add("Hi")
    array.add("StackOverflow")
    array.add("I'd Like")
    array.add("This")
    array.add("text")
    array.add("to be closer")
    array.add("together!")
    return array
} 

删除时p.add("\n")这是输出: 在此处输入图像描述

标签: javakotlinitext

解决方案


全面披露:这里的前 iText 员工

我会这样做:

public static void main(String[] args) throws IOException {

    // create a temp file to hold the output
    File outputFile = File.createTempFile("stackoverflow",".pdf");

    PdfDocument pdfDocument =  new PdfDocument(new PdfWriter(outputFile));
    Document layoutDocument = new Document(pdfDocument);

    String[] lines = {"Hi","StackOverflow","I'd like","this","text","to","be","closer","together!"};
    for(String line : lines){
        layoutDocument.add(new Paragraph(line)
                .setMultipliedLeading(0.5f));   // this is where the magic happens
    }

    layoutDocument.close();
    pdfDocument.close();

    // display the temp file with the default PDF viewer
    Desktop.getDesktop().open(outputFile);
}

我改变了几件事:

  • 尽可能使用最新版本的 iText。您想从几年的错误修复和更新的架构中受益。
  • 不要使用表格来解决布局问题。
  • 在段落对象上使用前导(MultipliedLeading 或 FixedLeading)来解决您的问题。

推荐阅读