簡體   English   中英

我如何使用VBA代碼合並多個pdf文件

[英]how i can merge multi pdfs files by using VBA code

我有一個包含多個pdfs文件路徑的表...現在我需要一個VBA代碼將所有這些文件合並為一個pdf文件。 注意:-要合並的pdf文件的數量有時會有所不同。

Sub Combine_PDFs_Demo()
Dim i As Integer 'counter for records
Dim x As Integer
Dim strNPDF As String
Dim bSuccess As Boolean
Dim DB As Database
Dim RS As Recordset
Set DB = CurrentDb
Set RS = DB.OpenRecordset("SELECT[paths] from scantemp ")
strNPDF = CurrentProject.Path & "\request_pic\" & (request_no) & ".pdf"
RS.MoveLast
DB.Recordsets.Refresh
i = RS.RecordCount
RS.MoveFirst
Dim strPDFs() As String
ReDim strPDFs(0 To i)
strPDFs(0) = RS![paths]
RS.MoveNext
For i = 1 To i - 1
strPDFs(i) = RS![paths]
bSuccess = MergePDFs(strPDFs, strNPDF)
Next i
If bSuccess = False Then MsgBox "Failed to combine all PDFs", vbCritical, "Failed to Merge PDFs"
DoCmd.SetWarnings False
DoCmd.RunSQL "delete from scantemp" 'delete all paths from table scantemp after converted it to pdf
DoCmd.SetWarnings True
  RS.Close
    Set RS = Nothing`enter code here`
public Function MergePDFs(arrFiles() As String, strSaveAs As String) As Boolean
Dim objCAcroPDDocDestination As Acrobat.CAcroPDDoc
Dim objCAcroPDDocSource As Acrobat.CAcroPDDoc
Dim i As Integer
Dim iFailed As Integer

On Error GoTo NoAcrobat:
'Initialize the Acrobat objects
Set objCAcroPDDocDestination = CreateObject("AcroExch.PDDoc")
Set objCAcroPDDocSource = CreateObject("AcroExch.PDDoc")
 'Open Destination, all other documents will be added to this and saved with
'a new filename
objCAcroPDDocDestination.Open (arrFiles(LBound(arrFiles))) 'open the first file
 'Open each subsequent PDF that you want to add to the original
  'Open the source document that will be added to the destination
    For i = LBound(arrFiles) + 1 To UBound(arrFiles)
        objCAcroPDDocSource.Open (arrFiles(i))
        If objCAcroPDDocDestination.InsertPages(objCAcroPDDocDestination.GetNumPages - 1, objCAcroPDDocSource, 0, objCAcroPDDocSource.GetNumPages, 0) Then
          MergePDFs = True
        Else
          'failed to merge one of the PDFs
          iFailed = iFailed + 1
        End If
        objCAcroPDDocSource.Close
    Next i
objCAcroPDDocDestination.save 1, strSaveAs 'Save it as a new name
objCAcroPDDocDestination.Close
Set objCAcroPDDocSource = Nothing
Set objCAcroPDDocDestination = Nothing

NoAcrobat:
If iFailed <> 0 Then
    MergePDFs = False
End If
On Error GoTo 0
End Function

這使用PDF或PS文件列表來創建一個PDF。 抱歉,它在VB.net中,我真的沒有時間進行轉換。 但是,它說明了您可以嘗試的概念。 基本上,您將選項和文件名寫入文本文件,然后將該文件用作Ghostscript的參數。

    Private Shared Sub ConvertToPDF(ByVal PSPathFileList As List(Of String), _
                             ByVal PDFPathName As String, _
                             ByVal WaitForExit As Boolean, ByVal DeletePS As Boolean)

        'check that all files exist
        PSPathFileList.ForEach(AddressOf CheckFiles)

        'check old pdf file
        If IO.File.Exists(PDFPathName) Then
            Throw New ApplicationException( _
                "PDF cannot be created. File already exists: " & PDFPathName)
        End If

        'convert engine
        Dim myProcInfo As New ProcessStartInfo
        myProcInfo.FileName = DanBSolutionsLocation & "Misc\GhostScript\GSWIN32C.EXE"
        Debug.Print(myProcInfo.FileName)

        'write file names to text file as the list can be very long
        Dim tempPath As String = IO.Path.GetDirectoryName(PSPathFileList.Item(0))
        Dim fiName2 As String = tempPath & IO.Path.GetFileNameWithoutExtension(PDFPathName) & ".txt"

        Dim ft As New StreamWriter(fiName2)
        ft.WriteLine("-sDEVICE=pdfwrite -q -dSAFER -dNOPAUSE -sOUTPUTFILE=""" & PDFPathName & """ -dBATCH ")
        For i As Long = 0 To PSPathFileList.Count - 1
            ft.WriteLine(Chr(34) & PSPathFileList.Item(i) & Chr(34))
        Next
        ft.Close()

        'set args to text file
        myProcInfo.Arguments = """@" & fiName2 & """"

        'set up for output and errors
        myProcInfo.UseShellExecute = False
        myProcInfo.RedirectStandardOutput = True
        myProcInfo.RedirectStandardError = True
        Debug.Print(myProcInfo.Arguments)

        'do the conversion
        Dim myProc As Process = Process.Start(myProcInfo)

        Debug.Print(myProc.StandardOutput.ReadToEnd)
        Debug.Print(myProc.StandardError.ReadToEnd)

        If WaitForExit Then
            'wait for finish; (no more than 60 seconds)
            myProc.WaitForExit(60000)

            'delete PS
            If DeletePS Then
                PSPathFileList.ForEach(AddressOf DeleteFiles)
            End If
        End If

    End Sub

這是單個PS到PDF的VBA代碼。 因此,希望在上面的VB.net和下面的VB.net之間可以找到有用的東西。

Private Sub printToPdfDemo()

    'verify printer setup
    'be sure to install the PsPrinterInstall module
    Call PSPrinterSetup

    Dim svPsFileName As String
    Dim svPDFName As String

    'define names
    svPsFileName = "C:\Temp\Input 1.ps"
    svPDFName = "C:\Temp\Output 1.PDF"

    'save current printer
    Dim PrinterInUse As String
    PrinterInUse = Application.ActivePrinter

    'print to PS
    'If Fso.FileExists(svPsFileName) Then Call Fso.DeleteFile(svPsFileName)
    Worksheets(1).PrintOut ActivePrinter:=PSPrinterName, PrintToFile:=True, _
        PrToFileName:=svPsFileName

    'revert to saved printer name
    Application.ActivePrinter = PrinterInUse

    'convert
    Call ConvertToPDF(svPsFileName, svPDFName)
End Sub


Sub ConvertToPDF(ByVal svPsFileName As String, ByVal svPDFName As String)
    Dim fso As New FileSystemObject
    'Dim Fso: Set Fso = CreateObject("Scripting.FileSystemObject")
    Dim folGS As Folder
    Dim lcCmd As String

    'check inputs
    If svPsFileName = "" Or svPDFName = "" Then
        Call MsgBox("PS file name or PDF file name is blank in ""ConvertToPDF"" macro", vbExclamation, "Error! Missing Inputs")
        Exit Sub
    End If

    'check file
    If Not fso.FileExists(svPsFileName) Then
        Call MsgBox(svPsFileName & " file is not found", vbExclamation, "Error! Missing File")
        Exit Sub
    End If

    'check variable
    If DanBSolutionsLocation = "" Then DanBSolutionsLocation = GetDanBSolutionsLocation

    'delete old file
    If fso.FileExists(svPDFName) Then Call fso.DeleteFile(svPDFName)

    'get files
    Set folGS = fso.GetFolder(DanBSolutionsLocation & "Misc\GhostScript\") 'S:\DanB Solutions\Misc\GhostScript\GSWIN32C.EXE

    'GS command
    lcCmd = folGS.ShortPath & "\GSWIN32C.EXE " & _
    "-q -dNOPAUSE -I" & folGS.ShortPath & "\lib;./fonts " & _
    "-sFONTPATH=./fonts -sFONTMAP=" & folGS.ShortPath & "\lib\FONTMAP.GS " & _
    "-sDEVICE=pdfwrite -sOUTPUTFILE=" & """" & svPDFName & """" _
    & " -dBATCH " & """" & svPsFileName & """"

    'convert
    Debug.Print lcCmd
    Call ShellWait(lcCmd)

    'delete PS
    If fso.FileExists(svPDFName) Then fso.DeleteFile (svPsFileName)

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM