如何使用iTextSharp引入新的行字符

时间:2016-09-30 12:28:16

标签: vb.net pdf itext

我已经编写了以下代码来编写PDF格式的文本,我希望在一些文本之后打破这一行。

 Dim document As Document

    document = New Document(PageSize.A4, 5.0F, 20.0F, 20.0F, 20.0F)

    Try

        Dim writer As PdfWriter
        writer = PdfWriter.GetInstance(document, New FileStream(filename, FileMode.Create))

        document.Open()

        Dim spacing As Integer

        spacing = 0

        Dim curY, lineHeight As Double

        curY = document.Top
        lineHeight = 0

        Const maxPerLine As Integer = 3


        For i As Integer = 0 To 5

            Dim table As PdfPTable
            table = New PdfPTable(4)

            table.DefaultCell.Border = Rectangle.NO_BORDER
            table.TotalWidth = 200.0F
            table.LockedWidth = True

            Dim cell As PdfPCell
            cell = New PdfPCell(New Phrase("hello \n" + i + "\n" + "wass up ?" ))
            cell.Colspan = 4
            cell.HorizontalAlignment = 0
            cell.Border = Rectangle.NO_BORDER
            cell.Padding = 30.0F
            table.AddCell(cell)

            table.WriteSelectedRows(0, -1, document.Left + spacing, curY, writer.DirectContent)

            spacing = spacing + 200

            lineHeight = Math.Max(lineHeight, table.TotalHeight)

            If 0 = (i + 1) Mod maxPerLine Then

                curY = curY - lineHeight
                spacing = 0
                lineHeight = 0

            End If

        Next

    Catch ex As Exception

    Finally

        document.Close()


    End Try

我尝试使用Paragraph,但我仍然无法将文本输入新行。

我已经阅读了他们写过的iTextSharp的文档,如果你想打破行,然后使用" \ n"但它没有用。

如何在一些文字之后打破界限?

1 个答案:

答案 0 :(得分:2)

最简单的方法是在复合模式中使用PdfPCell(您正在使用文本模式)。使用AddElement时,复合模式会起作用:

Dim cell As PdfPCell
cell = New PdfPCell()
cell.AddElement(New Paragraph("line 1"))
cell.AddElement(New Paragraph("line 2"))

请注意,在这种情况下,您无法在PdfPCell级别设置对齐方式。使用复合模式时,必须在元素级别设置对齐(在本例中为Paragraph级别)。