首页 > 解决方案 > 我正在使用此代码创建 PDF,在我的计算机上运行良好,但在其他计算机上存在兼容性问题。你以前遇到过这个吗?

问题描述

    Sub CreatePWPDF(DefName, PassPhrase)
'Purpose: Sub to create and password protect PDF copy of the raw workbook
'Function: Utilizes the PDFCreator reference library to create and password protect pdf copies of the raw workbook
'Inputs:
'(1) DefName - The name of the file without the file type extension
'(2) The passphrase to encrypt the PDF
'Notes:
'(1) Requires the PDFCreator reference library enabled to work
'(2) Does not work with PDFCreator version 2.0 or greater since it does not appear to have the PDFCreator reference library

Dim pdfobj As PDFCreator.clsPDFCreator
Dim FPath$, KillFile As String

FPath = ActiveWorkbook.Path & Application.PathSeparator 'Defines the file path. Ensures that the PDF is saved in the same place as the raw workbook
KillFile = FPath & DefName & ".pdf"


Set pdfobj = New PDFCreator.clsPDFCreator 'Define PDF Object variable

With pdfobj

    If .cStart("/NoProcessingAtStartup") = False Then 'Check to see if PDFCreator is already running.
        MsgBox "Can't initialize PDFCreator. If PDF Creator is already running, close PDFCreator and try again.", vbCritical + _
                vbOKOnly, "Critical Error with PDFCreator"
        Exit Sub 'If PDFCreator is already running then exit sub. This is necessary in order to prevent errors from occuring.
    End If

    .cOption("UseAutosave") = 1 'Allows for automatic saving into a directory
    .cOption("UseAutosaveDirectory") = 1
    .cOption("AutosaveDirectory") = FPath 'Define file path
    .cOption("AutosaveFilename") = DefName 'Define file name
    .cOption("AutosaveFormat") = 0    ' Set format to PDF
    .cOption("PDFUseSecurity") = 1 'Enable password protection
    .cOption("PDFOwnerPass") = 1 'Enable editing password
    .cOption("PDFOwnerPasswordString") = PassPhrase 'Set editing password
    .cOption("PDFDisallowCopy") = 0 'Allow copying of contents in PDF
    .cOption("PDFDisallowModifyContents") = 1 'Do not allow modification to PDF
    .cOption("PDFDisallowPrinting") = 0 'Allow pdf to be printed
    .cOption("PDFHighEncryption") = 1 'Enable strong encryption
    .cClearCache 'Clear cache for print job
End With

If Dir(KillFile) <> "" Then 'Deletes existing PDF file with the same name
    SetAttr KillFile, vbNormal
    Kill KillFile
End If

ActiveWorkbook.PrintOut copies:=1, ActivePrinter:="PDFCreator" 'Print entire workbook to PDF

Do Until pdfobj.cCountOfPrintjobs = 1 'Wait until the entire workbook is printed to PDF
    DoEvents 'Wait
Loop

pdfobj.cPrinterStop = False 'Do not stop printer

Do 'Ensure that the file is created before closing PDFCreator
    DoEvents 'Wait
Loop Until Dir(FPath & DefName & ".pdf") = DefName & ".pdf"

pdfobj.cClose 'Ensures that PDFCreator closes
Set pdfobj = Nothing

End Sub

标签: vba

解决方案


推荐阅读