PdfWriter.GetInstance() 返回一个对象,您可以查询该对象以查找当前页码,所以这是您应该知道的第一件事。如果你可以控制你的 HTML,我会注入一个标志变量,你可以稍后在 For 循环中观察它。如果找到标志变量,就做点什么,否则就照常添加内容。
只是一个快速警告,HTMLWorker 已被弃用很长时间,并且没有得到维护。所有工作都在支持 CSS 的 XmlWorker 库中完成。如果您因为许可证更改而无法使用旧版本you should probably read this,请找出有关旧许可证的神话和事实。
以下是展示标志变量的完整工作示例。在顶部,我创建了一些示例 HTML,您显然可以将其删除并替换为您的真实 HTML。然后我创建一个标准文档并像您一样遍历每个项目。在循环内部,我检查标志变量,如果找到则存储它,否则就像你做的那样添加元素。
此代码针对 iTextSharp 5.4.4。如果您使用的是旧版本的 iTextSharp,那么 Using 语句可能不起作用,只需将它们转换为 Dim 语句并删除 End Using (或升级到最新版本)。其他 cmets 见代码
''//File to write to
Dim TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
''//Create a flag value to search for. We won't write this to the PDF, it is just for searching.
Dim FlagValue = "!!UNIQUE TEXT!!"
''//Build our sample HTML. The real version of this would get the HTML from another source ideally.
Dim sampleHTML = <body/>
For I As Integer = 1 To 10
''//Just before inserting our chapter headings we insert our flag value appended with the current chapter number.
''//NOTE: This might need to be played with a little bit. I'm not sure if a new page is created by the previous entity
''// closing or the new entity starting.
sampleHTML.Add(String.Format("{0}{1}", FlagValue, I))
sampleHTML.Add(<h1><%= String.Format("Chapter {0}", I) %></h1>)
''//Add some some paragraphs
For J As Integer = 1 To 100
sampleHTML.Add(<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse ac arcu porta, tempor justo eu, tincidunt eros.
Integer lorem dolor, pretium sit amet vehicula dapibus,
faucibus a tellus.</p>)
Next
Next
''//This will be our collection of chapter numbers and the actual page numbers that they correspond to.
Dim PageNumbers As New Dictionary(Of String, Integer)
''//Standard PDF setup here, nothing special
Using fs As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using doc As New Document()
Using writer = PdfWriter.GetInstance(doc, fs)
doc.Open()
''//Parse our HTML
Dim htmlarraylistBody = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(New StringReader(sampleHTML.ToString()), Nothing)
''//Loop through each item
For Each Elem In htmlarraylistBody
''//Some HTML elements freak the system out so you should check if they are content first.
If Elem.IsContent() Then
''//If the current element is a paragraph and start with our flag value
If (TypeOf Elem Is Paragraph) AndAlso DirectCast(Elem, Paragraph).Content.StartsWith(FlagValue) Then
''//Add that to our master collection but DO NOT write it to the PDF
PageNumbers.Add(DirectCast(Elem, Paragraph).Content.Replace(FlagValue, ""), writer.PageNumber)
Else
''//Otherwise just write to the PDF normally
doc.Add(Elem)
End If
End If
Next
doc.Close()
End Using
End Using
End Using