识别文本是否包装在段落/单元格中



我有一个完全对正的文本Chunk(不同长度的字符串),后面跟着一个包含DottedLineSeparator对象的Chunk。我需要知道的是,不同长度的字符串是否缠绕到第二行(理论上它可以缠绕到第三行,但这不太可能)。

我熟悉在Chunk对象上使用GetWidthPoint()方法(我读过这个问题),这就是我正在使用的;但我相信,由于文本的充分理由,它不能100%准确地工作。。。这意味着空间的实际宽度可能不同。

我希望有一些方法可以确定包含这两个块的Paragraph的高度,或者我正在使用.AddElement()添加Paragraph对象的PdfPCell对象,或者甚至是我添加PdfPCel对象的PdfPTable对象。我知道在将PdfPTable对象写入文档(使用.TotalHeight)后,我可以获得表的高度。这很令人困惑,因为我可以调用cell。GetMaxHeight(),但它总是返回8.75……无论文本是否足够长以换行!

不幸的是,我需要知道第一个单元格的高度是多少,然后才能为其余单元格生成内容——这就是难题。

有什么想法/建议/指导吗?

这里有一些代码可以说明:

Dim c As PdfPCell
Dim t As PdfPTable
Dim p As Paragraph
Dim textWrapsAround As Boolean = False
Dim amendedTextWrapsAround As Boolean = False
t = New PdfPTable(3)
t.SetWidths({40, 12, 12})
t.WidthPercentage = 95.0F
t.HorizontalAlignment = Element.ALIGN_CENTER
p = New Paragraph("", DEFAULTFONT)
p.SetLeading(0.5F, 1.0F)
c = New PdfPCell() With {.Border = 0}
c.MinimumHeight = PdfDocument.LineHeightPts
p.Add(New Chunk(name.Trim(), DEFAULTFONT)) 
p.Add(New Chunk(leaderLine))
p.Alignment = Element.ALIGN_JUSTIFIED

If p.Chunks(0).GetWidthPoint >= 216 Then textWrapsAround = True

c.AddElement(p)
c.HorizontalAlignment = Element.ALIGN_JUSTIFIED
c.PaddingTop = 0
t.SetExtendLastRow(True, False)
t.AddCell(c)
c = emitPdfColumnCell(col1, lFormat, textWrapsAround)
c.MinimumHeight = PdfDocument.LineHeightPts
c.HorizontalAlignment = Element.ALIGN_RIGHT
c.PaddingTop = If(textWrapsAround AndAlso col2.Contains(vbCrLf), top_padding, 0)
t.SetExtendLastRow(True, False)
t.AddCell(c)
c = emitPdfColumnCell(col2, lFormat, textWrapsAround)
c.MinimumHeight = PdfDocument.LineHeightPts
c.HorizontalAlignment = Element.ALIGN_RIGHT
c.PaddingTop = If(textWrapsAround AndAlso col2.Contains(vbCrLf), top_padding, 0)
t.SetExtendLastRow(True, False)
t.AddCell(c)
t.KeepTogether = True
pdf_doc.Add(t)

我终于找到了一种方法。。。这是100%的破解,我可能应该从使用Table切换到ColumnText,因为这就是我确定有多少行的方式。。。这是解决方案:

'returns # of lines 
Private Function CheckParagraphTextWrap(ByVal p As Paragraph) As Integer
    Dim ct As New ColumnText(Me.pdf_writer.DirectContent)
    ct.SetIndent(2.0F, True)
    ct.RightIndent = 1.5F
    Dim show As Boolean = False
    Dim x1, x2, y1, y2 As Double
    Dim phrase As New Phrase()
    phrase.AddAll(p.Chunks)
    'hard-coded to match the EXACT width of the cell... this is essential and
    x1 = 104.25 : y1 = 580 : x2 = 320.72 : y2 = 620
    ct.SetSimpleColumn(phrase, x1, y1, x2, y2, 1.0F, Element.ALIGN_JUSTIFIED)
    ct.SetLeading(0.5F, 1.0F) 'also has to match what was being done for the cell
    ct.Go(Not show) 'simulate mode
    Return ct.LinesWritten
End Function

我为添加到表中单元格的每个段落调用此函数;这是需要的,因为我必须在这之后为桌子上的其他单元格做调整。虽然笨拙,但它100%都有效(至少到目前为止)。我以前的方法只在95%的时间内有效:)

最新更新