如何使用iText Android在单个String中使用常规和粗体

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

我有一个由常量部分和可变部分组成的字符串。我希望变量在文本段落中使用常规字体进行格式化,而我希望常量部分为粗体。

这是我的代码:

    val boldFont = Font(Font.FontFamily.TIMES_ROMAN, 22f, Font.BOLD)
    val semiBoldFont = Font(Font.FontFamily.TIMES_ROMAN, 16f, Font.BOLD)
    val normalFont = Font(Font.FontFamily.TIMES_ROMAN, 16f, Font.NORMAL)
    val lineSeparator = LineSeparator()
    lineSeparator.lineColor = BaseColor(0, 0, 0, 68)


//      NAME OF THE STUDENT
    val paragraph = Paragraph(student?.Student_Name, boldFont)
    paragraph.alignment = Paragraph.ALIGN_CENTER

//      DOB
    val paragraphTwo = Paragraph("Date of Birth: ", semiBoldFont)
    paragraphTwo.add(Chunk(student?.Student_DOB , normalFont))
    paragraphTwo.alignment = Paragraph.ALIGN_CENTER

//      Place and Country of Birth
    val paragraphThree = Paragraph("Place and Country of Birth: ", semiBoldFont)
    paragraphThree.add(Chunk(student?.Student_City + ", " + student?.Student_Country, normalFont))
    paragraphThree.alignment = Paragraph.ALIGN_CENTER

//      Address
    val paragraphFour = Paragraph("Address: ", semiBoldFont)
    paragraphFour.add(Chunk(student?.Student_Address + ", " + student?.Student_City + ", " + student?.Student_Country, normalFont))
    paragraphFour.alignment = Paragraph.ALIGN_CENTER

//      Nationality
    val paragraphFive = Paragraph("Nationality: ", normalFont)
    paragraphFive.add(Chunk(student?.Student_Nationality_One + ", " + student?.Student_Nationality_Two, normalFont))
    paragraphFive.alignment = Paragraph.ALIGN_CENTER

try {
        document.add(paragraph)
        document.add(Chunk(lineSeparator))
        document.add(paragraphTwo)
        document.add(paragraphThree)
        document.add(paragraphFour)
        document.add(paragraphFive)

        if (educationList.size > 0) {
            document.add(Paragraph("Education", boldFont))
            document.add(Paragraph(" "))
        }

    } catch (e: DocumentException) {
        e.printStackTrace()
    }

输出:enter image description here

android kotlin itext
1个回答
1
投票

如果在Paragraph构造函数中设置字体,则稍后添加的Chunk对象使用的字体是该块的字体,该字体由未在块字体中设置的属性中的段落字体的数据补充。

字体的样式是一个位字段,不幸的是,样式字段中的这种补充是通过逐位或逐位实现的。因此,段落字体中的BOLD标志是添加到段落中的所有块的样式的or-ed!

您可以通过不在段落级别设置字体(或者至少不是具有样式位的字体)并且还将标签添加为单独的块来避免这种情况,例如,代替

// DOB
val paragraphTwo = Paragraph("Date of Birth: ", semiBoldFont)
paragraphTwo.add(Chunk(student?.Student_DOB , normalFont))
paragraphTwo.alignment = Paragraph.ALIGN_CENTER

// DOB
val paragraphTwo = Paragraph()
paragraphTwo.add(Chunk("Date of Birth: ", semiBoldFont))
paragraphTwo.add(Chunk(student?.Student_DOB , normalFont))
paragraphTwo.alignment = Paragraph.ALIGN_CENTER

或者可能

// DOB
val paragraphTwo = Paragraph("", normalFont)
paragraphTwo.add(Chunk("Date of Birth: ", semiBoldFont))
paragraphTwo.add(Chunk(student?.Student_DOB , normalFont))
paragraphTwo.alignment = Paragraph.ALIGN_CENTER

(这些选项之间的区别在于,基于段落字体信息,在段落之前添加了一些间距。)

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