【发布时间】:2018-05-16 20:12:37
【问题描述】:
我正在尝试获取 PDF 文档中的页数。我的一些 PDF 是在 Word 中创建的(另存为 PDF),其中一些是复印到目录中的(不确定这是否重要)。
经过数小时的研究,我发现这说起来容易做起来难。 页数很少返回给我正确的页数,尽管事实上大多数 PDF 的二进制代码中确实有 /Count。
例如,我使用了以下代码;它应该以二进制模式打开文档,查找 /Count 或 /N 并获取它旁边的数字,这应该给我页数。
Public Sub pagecount(sfilename As String)
On Error GoTo a
Dim nFileNum As Integer
Dim s As String
Dim c As Integer
Dim pos, pos1 As Integer
pos = 0
pos1 = 0
c = 0
' Get an available file number from the system
nFileNum = FreeFile
'OPEN the PDF file in Binary mode
Open sfilename For Binary Lock Read Write As #nFileNum
' Get the data from the file
Do Until EOF(nFileNum)
Input #1, s
c = c + 1
If c <= 10 Then
pos = InStr(s, "/N")
End If
pos1 = InStr(s, "/count")
If pos > 0 Or pos1 > 0 Then
Close #nFileNum
s = Trim(Mid(s, pos, 10))
s = Replace(s, "/N", "")
s = Replace(s, "/count", "")
s = Replace(s, " ", "")
s = Replace(s, "/", "")
For i = 65 To 125
s = Replace(s, Chr(i), "")
Next
pages = Val(Trim(s))
If pages < 0 Then
pages = 1
End If
Close #nFileNum
Exit Sub
End If
'imp only 1000 lines searches
If c >= 1000 Then
GoTo a
End If
Loop
Close #nFileNum
Exit Sub
a:
Close #nFileNum
pages = 1
Exit Sub
End Sub
但是,大多数情况下,它默认为 pages = 1(在 a: 下)。
我也将它更新为 10000 以确保它到达 /Count 行,但它仍然没有给我正确的计数。
If c >= 10000 Then
GoTo a
End If
我也遇到过这个reddit
还有其他方法可以做到这一点,我可以在我的应用程序中使用吗?
非常感谢任何帮助。
背景:
这适用于我试图让用户操作 PDF 文件的旧版 vb6 应用程序。我添加了一个 ListBox,用于显示特定目录中的所有 PDF 文档。当用户双击任何一个文件时,我会将其显示在我的应用程序内的 WebBrowser 组件中。
编辑:包含 3 个不同文档的 BinaryMode 行计数的图像:
我仔细检查了页数,/Count 显示了三个文档中每一个的正确页数。
【问题讨论】:
-
除非您的 PDF 是由同一个生成器创建的,否则您无法在不遵守 pdf 结构的情况下确定正确的页码,即从文件背面解析文件,定位 Pages 通过文件尾部和交叉引用创建树,并分析该根对象。