使用 VBA 和 Adobe 10 将一个 PDF 的页面替换为另一个 PDF



我正在使用VBA将PDF上的页面替换为另一个页面。我找到了这段代码,但它对我不起作用。正确保存文档时,不会交换页面。

Sub Button1_Click()
Dim AcroApp As Acrobat.CAcroApp
Dim Part1Document As Acrobat.CAcroPDDoc
Dim Part2Document As Acrobat.CAcroPDDoc
Dim numPages As Integer
Set AcroApp = CreateObject("AcroExch.App")
Set Part1Document = CreateObject("AcroExch.PDDoc")
Set Part2Document = CreateObject("AcroExch.PDDoc")
Doc1.Open ("C:tempPart1.pdf")
Doc2.Open ("C:tempPart2.pdf")
' Insert the pages of Part2 after the end of Part1
numPages = Doc1.GetNumPages()
If Doc1.InsertPages(numPages 3, Doc2,
0, Doc2.GetNumPages(), True) = False Then
MsgBox "Cannot insert pages"
End If
If Doc1.Save(PDSaveFull, "C:tempMergedFile.pdf") = False Then
MsgBox "Cannot save the modified document"
End If
Doc1.Close
Doc2.Close
AcroApp.Exit
Set AcroApp = Nothing
Set Part1Document = Nothing
Set Part2Document = Nothing
MsgBox "Done"
End Sub

请尝试下一个代码。它(现在(能够合并,插入,删除和插入页面。请玩它!对于每个选项,您必须选择适当的布尔变量。

对于boolMerge选项,它将合并两个文件,从Doc页面开始。

对于boolReplace,它将用相同数量的Doc2替换Doc1中的特定数量的页面。看起来这就是这种方法可以做的。

对于boolDelInsert,它首先删除 3 页Doc1,然后从第一页开始插入Doc2页减去 1。我没有这么大的文件,也没有(完全(测试。由于您使用了虚拟文件全名,因此我没有删除我的pdf测试文件路径...

Sub Button1_Click()
Dim AcroApp As Acrobat.CAcroApp
Dim Doc1 As Acrobat.CAcroPDDoc
Dim Doc2 As Acrobat.CAcroPDDoc
Dim numPages As Integer, boolNotSaved As Boolean
Dim boolReplace As Boolean, boolDelInsert As Boolean
Dim boolMerge As Boolean, startDel As Long, lastDel As Long 'for deletion case
boolMerge = True 'use here boolReplace, boolDelInsert 
startDel = 0: lastDel = 2 ' pdf pages are zero based
Set AcroApp = CreateObject("AcroExch.App")
Set Doc1 = CreateObject("AcroExch.PDDoc")
Set Doc2 = CreateObject("AcroExch.PDDoc")
Doc1.Open ("C:UsersFane BranestiDropboxGet Started with Dropbox - bis.pdf")
Doc2.Open ("C:UsersFane BranestiDropboxcombinate.pdf") ' Then Stop
If boolReplace Then 'it replaces starting from the first parameter (0) with all Doc2 pages
If Doc1.ReplacePages(0, Doc2, 0, Doc2.GetNumPages, 1) = False Then
MsgBox "Cannot replace pages"
Exit Sub
End If
ElseIf boolMerge Then 'it add at the end of the first file, all the content of the second
numPages = Doc1.GetNumPages()
If Doc1.InsertPages(numPages - 1, Doc2, _
0, Doc2.GetNumPages(), True) = False Then
MsgBox "Cannot merge pages"
Exit Sub
End If
ElseIf boolDelInsert Then
'delete first three pages (from 0 to 2)
If Doc1.DeletePages(startDel, lastDel) <> True Then
MsgBox "Unable to Delete"
Exit Sub
End If
'insert Doc2 pages (-1) starting from 0 (after -1):
If Doc1.InsertPages(-1, Doc2, _
0, Doc2.GetNumPages() - 1, True) = False Then
MsgBox "Cannot merge pages"
Exit Sub
End If
End If
If Doc1.Save(PDSaveFlags.PDSaveFull, "C:UsersFane BranestiDropboxProcessedFile.pdf") = False Then
MsgBox "Cannot save the modified document"
boolNotSaved = True
End If        
Doc1.Close: Doc2.Close
AcroApp.Exit
Set AcroApp = Nothing: Set Doc1 = Nothing: Set Doc2 = Nothing
If Not boolNotSaved Then MsgBox "Done"
End Sub

相关内容

最新更新