0
我使用iTextSharp打印GridView,但在嘗試確定列的合適寬度時遇到問題。在我的gridview中,我沒有設置它,而是讓ASP.NET引擎調整寬度(它根據文本的樣式動態地調整寬度)。iTextSharp打印GridView - 輸出頁眉寬度
默認情況下,所有列的大小相同,在大多數情況下都是不好的。
如何配置標題的PdfPCell對象的寬度適合其中的文本?
我使用iTextSharp打印GridView,但在嘗試確定列的合適寬度時遇到問題。在我的gridview中,我沒有設置它,而是讓ASP.NET引擎調整寬度(它根據文本的樣式動態地調整寬度)。iTextSharp打印GridView - 輸出頁眉寬度
默認情況下,所有列的大小相同,在大多數情況下都是不好的。
如何配置標題的PdfPCell對象的寬度適合其中的文本?
列寬度計算在PdfPTable
級別,因此您需要在此處解決。根據您使用的解析器的不同,有幾種方法可以啓動,但最終結果是您需要將HTML解析爲iTextSharp對象,然後在將它們提交給PDF之前手動應用自己的邏輯。下面的代碼是基於使用(首選)XMLWorker和iTextSharp的5.4.0,以及下面的示例HTML:
<html>
<head>
<title>This is a test</title>
</head>
<body>
<table>
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>Dole</td>
</tr>
</tbody>
</table>
</body>
</html>
首先,你需要實現自己的IElementHandler
類。這將允許您在將它們寫入PDF之前捕獲元素。
Public Class CustomElementHandler
Implements IElementHandler
''//List of all elements
Public elements As New List(Of IElement)
''//Will get called for each top-level elements
Public Sub Add(w As IWritable) Implements IElementHandler.Add
''//Sanity check
If (TypeOf w Is WritableElement) Then
''//Add the element (which might have sub-elements)
elements.AddRange(DirectCast(w, WritableElement).Elements)
End If
End Sub
End Class
然後你只需要使用您的處理程序,而不是上面直接寫入到文件:
''//TODO: Populate this with your HTML
Dim Html = ""
''//Where we're write our PDF to
Dim File1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "File1.pdf")
''//Create our PDF, nothing special here
Using FS As New FileStream(File1, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document()
Using writer = PdfWriter.GetInstance(Doc, FS)
Doc.Open()
''//Create an instance of our handler
Dim Handler As New CustomElementHandler()
''//Bind a StringReader to our text
Using SR As New StringReader(Html)
''//Have the XMLWorker read our HTML and push it to our handler
XMLWorkerHelper.GetInstance().ParseXHtml(Handler, SR)
End Using
''//Loop through each element that the parser found
For Each El In Handler.elements
''//If the element is a table
If TypeOf El Is PdfPTable Then
''//Below is just for illustration, change as needed
''//Set the absolute width of the table
DirectCast(El, PdfPTable).TotalWidth = 500
''//Set the first column to be 25% and the second column to be 75%
DirectCast(El, PdfPTable).SetWidths({0.25, 0.75})
''//Also, just for illustration, turn borders on for each cell so that we can see the actual widths
For Each R In DirectCast(El, PdfPTable).Rows
For Each C In R.GetCells()
C.BorderWidthLeft = 1
C.BorderWidthRight = 1
C.BorderWidthBottom = 1
C.BorderWidthTop = 1
Next
Next
End If
''//Add the element to the document
Doc.Add(El)
Next
Doc.Close()
End Using
End Using
End Using