【发布时间】:2014-05-29 07:18:33
【问题描述】:
我正在尝试使用 PDF 读取字符串。这里我有一个代码在运行时给我错误..
Can not acess a closed file error in Itextsharp
我不明白为什么会出现这个错误。我的代码是在 VB 中,我是第一次使用 VB 和 Itext,所以遇到了问题。这是我的代码..
Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
Dim cb As iTextSharp.text.pdf.PdfContentByte = Nothing
Me.Cursor = Cursors.WaitCursor
If File.Exists(SourceFile) Then
Dim pReader As New PdfReader(SourceFile)
stamper = New iTextSharp.text.pdf.PdfStamper(pReader, New FileStream(DestinationFile, FileMode.Create))
PB.Value = 0 : PB.Maximum = pReader.NumberOfPages
For page As Integer = 1 To pReader.NumberOfPages
Dim strategy As myLocationTextExtractionStrategy = New myLocationTextExtractionStrategy
cb = stamper.GetUnderContent(page)
'Send some data contained in PdfContentByte, looks like the first is always cero for me and the second 100, but i'm not sure if this could change in some cases
strategy.UndercontentCharacterSpacing = cb.CharacterSpacing
strategy.UndercontentHorizontalScaling = cb.HorizontalScaling
'It's not really needed to get the text back, but we have to call this line ALWAYS,
'because it triggers the process that will get all chunks from PDF into our strategy Object
Dim currentText As String = PdfTextExtractor.GetTextFromPage(pReader, page, strategy)
我在代码的最后一行收到错误..
Dim currentText As String = PdfTextExtractor.GetTextFromPage(pReader, page, strategy)
根据评论需要的代码
Private Sub Start_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Start.Click
'Parameter1: Search Text (1 word or many)
'Parameter2: Case Sensitiveness
'Parameter3: Source file with Path
'Parameter4: Destination File with Path
PDFTextGetter("Hello", StringComparison.CurrentCultureIgnoreCase, "D:\\pdf\\18.pdf", "D:\\Bill\\Test.pdf")
End Sub
请帮助我。非常感谢!
【问题讨论】:
-
您的源文件来自哪里将是一个开始,因为提供的代码没有显示任何内容,而且您的问题的根源似乎......
-
另外你使用一个新的文件流,这是一个很好的做法,继续使用'使用'块为文件设置一个新变量,然后将它传递到你的 PdfStamper...
-
@MrCoDeXeR 我已经更新了我的帖子。请看。
-
好吧,您似乎在这里找到了代码:stackoverflow.com/questions/2550796/…,所以唯一的区别似乎是您的
extractionStrategy。虽然我不熟悉这个 API。另外,catch 看看是否有异常,或者确保策略有效。
标签: vb.net pdf itextsharp