Securing PDF with PDFlib PSP (Pretty Safe PDF)
;------------------------------------------------------------------------------------------------------------------------------------------
; PDFLib.PSP.COM  v1.01  20030115.20030117                                                                                (c)20030115 Detlev Dalitz
;------------------------------------------------------------------------------------------------------------------------------------------
; WinBatch wrapper resp. demo code for the COM object "PDFlib - PSP (Pretty Safe PDF) Version 1.0.1"
;------------------------------------------------------------------------------------------------------------------------------------------
;   PDFlib and the PDFlib logo are registered trademarks of PDFlib GmbH.
;
;   PDFlib GmbH
;   Tal 40, 80331 München, Germany
;   http://www.pdflib.com
;   phone +49 • 89 • 29 16 46 87
;   fax +49 • 89 • 29 16 46 86
;
;   If you have questions check the PDFlib mailing list and archive at http:/groups.yahoo.com/group/pdflib
;
;   Licensing contact: sales@pdflib.com
;   Customer support: support@pdflib.com (please include your license number)
;   (c)PDFlib GmbH München, Germany; http://www.pdflib.com
;------------------------------------------------------------------------------------------------------------------------------------------
;!! In order to use the following WinBatch code, you have to agree with the licensing rules of "PDFlib GmbH"
;!! and download the file "PSP-1.0.1.msi.zip" from their website "http://www.pdflib.com".
;------------------------------------------------------------------------------------------------------------------------------------------
;   This WinBatch implementation is based on PDFlib PSP Version 1.0.1 and manual from October 22, 2002.
;------------------------------------------------------------------------------------------------------------------------------------------
;   From the PSP manual:
;   Applying the PSP License Key
;   All versions of the PSP command-line tool and programming library can be used as fully
;   functional evaluation versions regardless of whether or not you obtained a commercial license.
;   However, unlicensed versions will only allow the use of passwords which we consider not secure enough
;   for professional applications (see Section 1.2, »Strength of PDF Encryption« for more details):
;   passwords with 5 characters or less can be applied with the free evaluation version of PSP.
;   However, even if you use only short passwords, unlicensed versions of PSP must not be used for production purposes,
;   but only for evaluating the product’s features and performance.
;   Using PSP for production purposes or applying passwords with more than 5 characters requires a valid PDFlib PSP license key.
;------------------------------------------------------------------------------------------------------------------------------------------
;   Windows users can enter the license key when they install PSP using the supplied installer.
;   This is the recommended method on Windows.
;   If you do not have write access to the registry or cannot use the installer refer to the following method:
;   Apply the license key manually each runtime by writing it directly into the script (or read it from an inifile):
;   oPSP.set_parameter ("license", "...your license key...")
;------------------------------------------------------------------------------------------------------------------------------------------
;   Perhaps after this Demo you will like PSP so much for your PDF files, so rent a license from "PDFlib GmbH".
;   ... and now ... Happy WinBatching and private PDF Securing for free!
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
;
;   Q: What can you do with "PDFlib - PSP (Pretty Safe PDF)"?
;   A: PSP does Securing of PDF Documents.
;
;   PSP applies or removes Acrobat standard security features to PDF files.
;   PSP can apply user and master passwords, and set access permissions to prevent
;   printing the document with Acrobat, extracting text, modifying the document, etc.
;   PSP uses 40-bit or 128-bit encryption keys.
;   128-bit keys have been introduced in Acrobat 5, and are also known as "secure" keys.
;
;   With PDFlib PSP you can do the following:
;      - Encrypt a PDF document with a user or master password (or both).
;      - Remove PDF encryption if you know the document’s master password.
;      - Add or remove permission settings (e.g., printing or text extraction not allowed)
;        if you know the document’s master password.
;      - Query information about the security status (encrypted with user or master password),
;        encryption scheme (Acrobat standard security, WebBuy, etc.), permission settings,
;        and document info fields.
;      - Combine PSP with our PDFlib 4 product for generating encrypted PDF documents dynamically.
;
;
;   Q: Is PSP a command-line tool or a PSP library?
;   A: PSP is available both as a programming library (component) for various development languages,
;   and as a command-line tool for batch operations.
;   Both offer the same security features, but are suitable for different deployment tasks.
;
;   Note: The PSP command-line tool can be used as fully functional evaluation version regardless
;   of whether or not you obtained a commercial license. However, unlicensed versions will only
;   allow the use of passwords which we consider not secure enough for professional applications
;   (see Manual, Section 1.2, "Strength of PDF Encryption" for more details):
;   Passwords with 5 characters or less can be applied with the free evaluation version of PSP.
;   However, even if you use only short passwords, unlicensed versions of PSP must not be used
;   for production purposes, but only for evaluating the product’s features and performance.
;   Using PSP for production purposes or applying passwords with more than 5 characters
;   requires a valid PDFlib PSP license key.
;
;
;   Q: Is it possible to set Passwords with PSP into PDF files?
;   A: Yes. It is strongly recommended to have a closer look into the developer's "PSP-manual.pdf"!
;
;
;   Q: Is it possible to set Permissions with PSP into PDF files, e.g. forbid printing?
;   A: Yes. It is strongly recommended to have a closer look into the developer's "PSP-manual.pdf"!
;------------------------------------------------------------------------------------------------------------------------------------------



;##########################################################################################################################################
;------------------------------------------------------------------------------------------------------------------------------------------
; Constant
;   iPSPError = -2147220992 ; 0x80040200
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; iResult = oPSP.open_file (sPassword, sFilename)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Open a PDF document (which may be protected) from file.
;
;   sPassword  ... The user or master password for the document.
;                  If the document is unprotected, or if it is encrypted
;                  but only the document’s encryption status will be queried,
;                  an empty password may be supplied.
;                  If the document is encrypted and info entries will be queried,
;                  the user password must be supplied.
;                  Otherwise the document’s master password is required.
;   sFilename  ... The full path name of the PDF file to be opened.
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; iResult = oPSP.get_buffer (hMemBuffer)  ; /* HRESULT get_buffer([out, retval] VARIANT* pVar) */
;------------------------------------------------------------------------------------------------------------------------------------------
;   Fetch full or partial buffer contents of the output document from memory.
;
;   hMemBuffer     Handle to the memory buffer.
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; iResult = oPSP.open_mem (sPassword, hMemBuffer)  ; /* HRESULT open_mem([in] BSTR password, [in] VARIANT* data) */
;------------------------------------------------------------------------------------------------------------------------------------------
;   Open a PDF document (which may be protected) from memory via a read function.
;
;   sPassword  ... The user or master password for the document.
;                  If the document is unprotected, or if it is encrypted
;                  but only the document’s encryption status will be queried,
;                  an empty password may be supplied.
;                  If the document is encrypted and info entries will be queried,
;                  the user password must be supplied.
;                  Otherwise the document’s master password is required.
;
;   hMemBuffer     The memory-based method is faster, but requires more memory.
;                  It is recommended for dynamic PDF generation and encryption in Web application
;                  unless you deal with very large documents.
;                  Instead of generating a PDF file on disk with PDFlib 4, use in-core PDF generation
;                  (by supplying an empty file name to PDF_open_file()), fetch the contents of the buffer
;                  containing the generated PDF data using PDF_get_buffer(), and pass this buffer
;                  to PSP using PSP_open_mem( ). Note that it is not possible to fetch the PDFlib 4 buffer
;                  contents in multiple portions since the full document must be supplied to PSP in a single
;                  buffer. Therefore you must call the PDF_get_buffer() method between PDF_close()
;                  and PDF_delete().
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; iResult = oPSP.create_file (sPasswordMaster, sPasswordUser, sAccess, iEncryptAlgorithm, iEncryptKeyLength, sFilename)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Create a PDF output document (which may be protected) on disk file.
;
;   sPasswordMaster  ....... The master password for the document. If this is an empty string no master password will be applied.
;   sPasswordUser    ....... The user password for the document. If this is an empty string no user password will be applied.
;   sAccess          ....... A string with the access permissions for the output document.
;                            It contains any number of the noprint, nomodify, nocopy, noannots, noforms, noaccessible, and nohiresprint
;                            keywords, separated from each other by a colon character ’:’.
;   iEncryptAlgorithm  ..... A number which identifies the algorithm used for PDF encryption:
;                            0  ... means no encryption.
;                                   This can only be used if no user and master password and no access restrictions have been specified.
;                            1  ... is the standard algorithm used in PDF 1.1 - 1.3 (up to Acrobat 4), and can be used with 40-bit keys.
;                                   The PDF version of the input document will be preserved.
;                            2  ... is the standard algorithm used in PDF 1.4 (Acrobat 5), and can be used with 128-bit keys.
;                                   The PDF version of the output document will be pushed to PDF 1.4 if necessary.
;   iEncryptKeyLength  ..... The length of the encryption key in bits.
;                            The standard key length in Acrobat 4 is 40 bits. Standard: 40-bit RC4 (Acrobat 3.x, 4.x)
;                            In Acrobat 5 it is 128 bits.
;                            Algorithm 0 (no encryption) requires a key length of 0 bits.
;   sFilename  ............. The name of the generated output file, which should be different from the input file name
;                            supplied to PSP_open_file(). If this is an empty string the output will be generated in memory,
;                            and can later be fetched with PSP_get_buffer().
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; oPSP.close ()
;------------------------------------------------------------------------------------------------------------------------------------------
;   Close the input and output documents.
;------------------------------------------------------------------------------------------------------------------------------------------
;##########################################################################################################################################



;##########################################################################################################################################
;------------------------------------------------------------------------------------------------------------------------------------------
; iResult = oPSP.get_value (sKey)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Get some parameter with numerical type.
;
;   iResult is 0.0 --> @FALSE
;   iResult is 1.0 --> @TRUE
;   See Table "Keys for oPSP.get_value (sKey)".
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; oPSP.set_value (sKey, iValue)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Set some parameter with numerical type.
;
;   Currently no keys are defined for this function.
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; iResult = oPSP.get_parameter (sKey)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Get some parameter with string type.
;
;   Returns the string value of the parameter sKey.
;   See Table "Keys for oPSP.get_parameter (sKey)".
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; oPSP.set_parameter (sKey, sString)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Set some parameter with string type.
;
;   sKey  ...... The name of the parameter to be retrieved.
;   sString  ... The value of the parameter to be set.
;                See Table "Keys for oPSP.set_parameter (sKey, sString)".
;------------------------------------------------------------------------------------------------------------------------------------------
;##########################################################################################################################################



;##########################################################################################################################################
; Tables
;------------------------------------------------------------------------------------------------------------------------------------------
; Keys for oPSP.get_value (sKey)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Name  .................. Remarks
;
;   major  ................. The major revision number of the library.
;   minor  ................. The minor revision  number of the library.
;   revision  .............. The revision number of the library.
;
;   has/Info  .............. Returns 1 if the document contains an info dictionary.
;   has/Info/xxx  .......... Returns 1 if the document contains the info dictionary entry xxx.
;
;   has/Encrypt  ........... Returns 1 if the document has any encryption, and 0 otherwise.
;   has/Encrypt/Filter ..... Returns 1 if the document has an encryption filter (equivalent to has/Encrypt)
;   /Encrypt/Length  ....... Returns the length of encryption key in bits.
;
;   /Encrypt/P  ............ The raw permission bit flag in the PDF file
;                           (unlikely to be useful since permission settings can be queried directly).
;
;   /Encrypt/algorithm  .... Returns the encryption algorithm used in the document:
;                            -1 ... Non-standard encryption filter,
;                                   or an encryption algorithm which is not implemented in PSP.
;                            0 .... No encryption
;                            1 .... 40-bit encryption as used in Acrobat 2-4
;                            2 .... 128-bit encryption as used in Acrobat 5
;
;   /Encrypt/user   ........ Returns 1 if the document requires a user password for opening, and 0 otherwise.
;
;   /Encrypt/nomodify etc.   Returns 1 if the respective access protection is set, and 0 otherwise.
;
;   pdfversion  ............ Returns the PDF version number of the input document,
;                            multiplied by ten (i.e. PDF 1.4 will be returned as 14).
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; Keys for oPSP.get_parameter (sKey)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Name  .................. Always available?  ................... Remarks
;
;   /Info/xxx  ............. no  .................................. arbitrary document info entries
;
;   /Encrypt/Filter  ....... only if the document is encrypted  ... The encryption algorithm used in the document,
;                            (check "has/Encrypt" to test this)     e.g. Standard (this is the default algorithm in Acrobat,
;                                                                   and the one used by PSP), FileOpen, WebBuy
;
;   version  ............... yes  ................................. Return the full library version string in the format
;                                                                   "major.minor.revision", possibly suffixed with
;                                                                   additional qualifiers such as "beta", "rc" etc..
;------------------------------------------------------------------------------------------------------------------------------------------
; Example
;   oPSP.get_parameter ("/Info/Producer")  --> "Acrobat Distiller 5.0.5 \(Windows\)"
;
; Other keywords:
;   /Producer (Acrobat Distiller 5.0.5 \(Windows\))
;   /Author (PDFlib GmbH)
;   /Subject (PDFlib Pretty Safe PDF \(PSP\): PDF security toolkit)
;   /ModDate (D:20021022111112Z00'00')
;   /CreationDate (D:20021022110629Z00'00')
;   /Title (PDFlib Pretty Safe PDF \(PSP\) Manual)
;   /Creator (FrameMaker 6.0)
;------------------------------------------------------------------------------------------------------------------------------------------



;------------------------------------------------------------------------------------------------------------------------------------------
; Keys for oPSP.set_parameter (sKey, sString)
;------------------------------------------------------------------------------------------------------------------------------------------
;   Name  .................. Remarks
;
;   license  ............... The PSP license key as a string
;
;   flush  ................. Set PSP’s flushing strategy to none, content, or heavy.
;                            The flushing strategy, which is only effective for in-memory generation,
;                            affects the amount of data returned by PSP_get_buffer() (C language implementation only).
;                            The default is none.
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; Access restriction keywords
;------------------------------------------------------------------------------------------------------------------------------------------
;   Keyword Long / Short .... Explanation
;
;   noprint      / nopr  .... Acrobat will prevent printing the file.
;   nomodify     / nomo  .... Acrobat will prevent users from adding form fields or making any other changes.
;   nocopy       / noco  .... Acrobat will prevent copying and extracting text or graphics, and will disable accessibility
;   noannots     / noan  .... Acrobat will prevent adding or changing comments or form fields.
;   noforms      / nofo  .... Acrobat will prevent form field filling, even if noannots has not been specified (requires Acrobat 5).
;                             Setting this  restriction implies noannots automatically.
;   noaccessib1e / noac  .... Acrobat will prevent extracting text or graphics for accessibility purposes (e.g. a screenreader)
;   noassemble   / noas  .... Acrobat will prevent inserting, deleting, or rotating pages and creating bookmarks and
;                             thumbnails, even if nomodify has not been specified.
;                             Setting this restriction implies nomodify automatically.
;   nohiresprint / nohi ..... Acrobat will prevent high-resolution printing (requires Acrobat 5).
;                             If noprint has not been specified, printing is restricted to the "print as image" feature,
;                             which prints a low-resolution rendition of the page.
;
;                             Example: sPermissions = "noprint:nocopy:noannots"
;------------------------------------------------------------------------------------------------------------------------------------------


;------------------------------------------------------------------------------------------------------------------------------------------
; Required passwords for various operations on encrypted documents
;------------------------------------------------------------------------------------------------------------------------------------------
; If you know the ...
;
;   master password            Yes        Yes        No         No
;
;   user password              Yes        No         Yes        No
;
;------------------------------------------------------------------------------------------------------------------------------------------
; You can perform ...
;
;   query encryption status    Yes        Yes        Yes        Yes
;
;   query document info        Yes        Yes        Yes        Only if no user password is set
;
;   change user password,      Yes        Yes        No         No
;   master password,
;   or permissions
;------------------------------------------------------------------------------------------------------------------------------------------
;##########################################################################################################################################



;##########################################################################################################################################
; OLE Object Interface   PSPlib_com.dll
;------------------------------------------------------------------------------------------------------------------------------------------
;   [
;     odl,
;     uuid(ECD2531D-7848-43A8-B266-4ED090C0013C),
;     helpstring("IPSP Interface"),
;     dual,
;     nonextensible,
;     oleautomation
;   ]
;   interface IPSP : IDispatch {
;       [id(0x60020000), helpstring("Open a PDF document (which may be protected) from file.")]
;       HRESULT open_file(
;                       [in] BSTR password,
;                       [in] BSTR filename,
;                       [out, retval] int* piRetVal);
;       [id(0x60020001), helpstring("Open a PDF document (which may be protected) from memory via a read function.")]
;       HRESULT open_mem(
;                       [in] BSTR password,
;                       [in] VARIANT* data);
;       [id(0x60020002), helpstring("Close the input and output documents.")]
;       HRESULT close();
;       [id(0x60020003), helpstring("Create a PDF output document (which may be protected) in memory or on disk file.")]
;       HRESULT create_file(
;                       [in] BSTR master,
;                       [in] BSTR user,
;                       [in] BSTR access,
;                       [in] int algorithm,
;                       [in] int keylen,
;                       [in] BSTR filename,
;                       [out, retval] int* piRetVal);
;       [id(0x60020004), helpstring("Fetch full or partial buffer contents of the output document from memory.")]
;       HRESULT get_buffer([out, retval] VARIANT* pVar);
;       [id(0x60020005), helpstring("Get some parameter with numerical type.")]
;       HRESULT get_value(
;                       [in] BSTR key,
;                       [out, retval] double* pfRetVal);
;       [id(0x60020006), helpstring("Set some parameter with numerical type.")]
;       HRESULT set_value(
;                       [in] BSTR key,
;                       [in] double value);
;       [id(0x60020007), helpstring(" Get some parameter with string type.")]
;       HRESULT get_parameter(
;                       [in] BSTR key,
;                       [out, retval] BSTR* pbstrRetVal);
;       [id(0x60020008), helpstring("Set some parameter with string type.")]
;       HRESULT set_parameter(
;                       [in] BSTR key,
;                       [in] BSTR value);
;   };
;------------------------------------------------------------------------------------------------------------------------------------------
;##########################################################################################################################################



;##########################################################################################################################################
;------------------------------------------------------------------------------------------------------------------------------------------
; PSP command-line options   PSP.EXE
;------------------------------------------------------------------------------------------------------------------------------------------
;   Long Option            Short Option   Parameters           Function
;
;   -access                -a             [<permissions>...]   set output access permissions
;                                                              (see Table for a list of permission strings)
;                                                              default: no restrictions.
;                                                              An empty or missing string can be used to reset the permissions.
;   -help (or no option)   -?                                  display help with a summary of available options
;   -infile                -i             <filename>...        process input file(s).
;                                                              Important: the encryption or decryption process for all files
;                                                              in a block starts when this option is encountered.
;                                                              Therefore all relevant options must have been set before the -infile option.
;   -keylength             -k             40 | 128             set output encryption key length to 40 or 128 bits; default: 128.
;   -logfile               -l             <filename> [1-2]     set log file name and verbosity; default verbosity level is 2
;                                                              (see -verbose option below)
;   -master                -m             [<password>]         set output master password; missing string means no password
;   -outfile               -o             <filename>           set output file name (input and output file name must be different,
;                                                              use -replace if you want to overwrite the input file)
;   -password              -p             <password>           set input user or master password; use empty string to reset password
;   -replace               -r                                  set replace mode (allow input document to be replaced by output document)
;   -showinfo              -s                                  display input file encryption status (no further action)
;   -targetdir             -t             <dirname>            set output directory name; the directory must already exist.
;   -user                  -u             [<password>]         set output user password; missing string means no password
;   -verbose               -v             0-2                  verbosity level (default is 1):
;                                                              0 no output at all (using -logfile is heavily recommended)
;                                                              1 emit only errors
;                                                              2 emit errors and file names
;------------------------------------------------------------------------------------------------------------------------------------------
;##########################################################################################################################################




; --- test ---

sMsgTitle = "Demo  PDFlib PSP (Pretty Safe PDF)"

;------------------------------------------------------------------------------------------------------------------------------------------
; Example 1
; Encrypt a single file with user password "psp" and master password "PSP", and 128-bit key.
;------------------------------------------------------------------------------------------------------------------------------------------

; We use the OLE automation object.
oPSP = ObjectOpen("PSPlib_com.PSP")

; Open unprotected input file without any password.
sFilenameIn = "D:\Programme\PDFlib\PSP-1.0.1\examples\data\PSP-datasheet.pdf"
sPasswordIn = ""

iResult = oPSP.open_file(sPasswordIn,sFilenameIn)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open input PDF file:",@LF,sFilenameIn))
   Goto CANCEL
EndIf

; Create the output file with master and user passwords and permissions.
sPasswordMaster   = "PSP"
sPasswordUser     = "psp"
sPermissions      = "noprint:nocopy:noannots:nomodify" ; PDF 1.4
iEncryptAlgorithm = 1
iEncryptKeyLength = 40 ; Standard 40-bit RC4 (Acrobat 3.x, 4.x)
sFilenameOut      = "D:\TEMP\PSP-datasheet-encrypted.pdf"

iResult = oPSP.create_file(sPasswordMaster,sPasswordUser,sPermissions,iEncryptAlgorithm,iEncryptKeyLength,sFilenameOut)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open output PDF file:",@LF,sFilenameOut))
   Goto CANCEL
EndIf

; Close input and output files.
oPSP.Close
ObjectClose(oPSP)
Drop(oPSP)

; Take a look into the PDF documents.
Run(sFilenameIn,"")
TimeDelay(10)
Run(sFilenameOut,"")
;------------------------------------------------------------------------------------------------------------------------------------------



Pause("Demo PSP","Press OK for the next example.")



;------------------------------------------------------------------------------------------------------------------------------------------
; Example 2
; Decrypt the encrypted file from example 1 with the master password "PSP".
; All access restrictions which may have been applied to the input document will be removed (since the output is unencrypted).
;------------------------------------------------------------------------------------------------------------------------------------------

; We use the OLE automation object.
oPSP = ObjectOpen("PSPlib_com.PSP")

; Open protected input file with master password.
sFilenameIn     = "D:\TEMP\PSP-datasheet-encrypted.pdf"
sPasswordMaster = "PSP"

iResult = oPSP.open_file(sPasswordMaster,sFilenameIn)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open input PDF file:",@LF,sFilenameIn))
   Goto CANCEL
EndIf

; Create the output file with no encryption.
sPasswordMaster   = ""
sPasswordUser     = ""
sPermissions      = ""
iEncryptAlgorithm = 0
iEncryptKeyLength = 0
sFilenameOut      = "D:\TEMP\PSP-datasheet-decrypted.pdf"

iResult = oPSP.create_file(sPasswordMaster,sPasswordUser,sPermissions,iEncryptAlgorithm,iEncryptKeyLength,sFilenameOut)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open output PDF file:",@LF,sFilenameOut))
   Goto CANCEL
EndIf

; Close input and output files.
oPSP.Close
ObjectClose(oPSP)

; Take a look into the PDF documents.
Run(sFilenameIn,"")
TimeDelay(10)
Run(sFilenameOut,"")
;------------------------------------------------------------------------------------------------------------------------------------------



Pause("Demo PSP","Press OK for the next example.")



;------------------------------------------------------------------------------------------------------------------------------------------
; Example 3
; Demontrates how to use PSP.get_buffer() and PSP.open_mem().
;------------------------------------------------------------------------------------------------------------------------------------------
; Phase A
; Open PSP component.
; Open unprotected single file.
; Create virtual output file.
; Fill PSP memory buffer with current file content.
; Close PSP component.
;
; At this point we have a handle to a WinBatch Binary Buffer filled with PDF data.
; Do some other stuff here ...
;
; Phase B
; Open PSP component.
; Open PSP memory buffer.
; Create real output file with password and access control.
; Close PSP component.
;------------------------------------------------------------------------------------------------------------------------------------------

; Open an instance of the component.
oPSP = ObjectOpen("PSPlib_com.PSP")

; Open unprotected input file without any password.
sFilenameIn = "D:\Programme\PDFlib\PSP-1.0.1\examples\data\PSP-datasheet.pdf"
sPasswordIn = ""

iResult = oPSP.open_file(sPasswordIn,sFilenameIn)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open input PDF file:",@LF,sFilenameIn))
   Goto CANCEL
EndIf

; Create the output file for memory buffer mode.
; You are able to use password and access control protection.
; Here we use nothing at all.
sPasswordMaster   = ""
sPasswordUser     = ""
sPermissions      = ""
iEncryptAlgorithm = 0
iEncryptKeyLength = 0
sFilenameOut      = ""

iResult = oPSP.create_file(sPasswordMaster,sPasswordUser,sPermissions,iEncryptAlgorithm,iEncryptKeyLength,sFilenameOut)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open output PDF file:",@LF,sFilenameOut))
   Goto CANCEL
EndIf

; Specify how OLE byte arrays will be handled.
; Store in binary buffer
IntControl(83,1,0,0,0)
hBB = oPSP.get_buffer

; Close input and output files.
oPSP.Close

; Close object.
ObjectClose(oPSP)


;---------------------------------------------------------------------------------
; At this point we have a handle to a WinBatch Binary Buffer filled with PDF data.
; Do some other stuff here ...

; We take a look into the buffer with the WinBatch browser.exe utility.
sFileTemp = FileCreateTemp("")
BinaryWrite(hBB,sFileTemp)
Run(StrCat(DirHome(),"browser.exe"),sFileTemp)
sBrowser = WinGetactive()
TimeDelay(2)
SendKeysTo(sBrowser,"^t")
WinWaitClose(sBrowser)
FileDelete(sFileTemp)
;---------------------------------------------------------------------------------


; Specify how a binary buffer will be used by OLE functions.
; 3 = byte array (VT_UI1 | VT_ARRAY); direction 100 = input parameter
iResult = BinaryOleType(hBB,3+100,0,0,0)

; Open an instance of the component.
oPSP = ObjectOpen("PSPlib_com.PSP")

; Open PSP memory buffer for reading PDF data from WinBatch Binary Buffer.
iResult = oPSP.open_mem(sPasswordIn,hBB)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open input PDF file:",@LF,sFilenameIn))
   Goto CANCEL
EndIf

; Create the output file with master and user passwords and with permissions.
sPasswordMaster   = "PSP"
sPasswordUser     = "psp"
sPermissions      = "noprint:nocopy:noannots:noforms:nomodify:nohiresprint:noassemble:noaccessible"
iEncryptAlgorithm = 2
iEncryptKeyLength = 128
sFilenameOut      = "D:\TEMP\PSP-datasheet-encrypted.pdf"

iResult = oPSP.create_file(sPasswordMaster,sPasswordUser,sPermissions,iEncryptAlgorithm,iEncryptKeyLength,sFilenameOut)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open output PDF file:",@LF,sFilenameOut))
   Goto CANCEL
EndIf

; Free the WinBatch Binary Buffer.
iResult = BinaryFree(hBB)

; Close input and output files.
oPSP.Close

; Close object.
ObjectClose(oPSP)

; Take a look into the PDF document.
Run(sFilenameIn,"")
;------------------------------------------------------------------------------------------------------------------------------------------



Pause("Demo PSP","Press OK for the next example.")



;------------------------------------------------------------------------------------------------------------------------------------------
; Example 4
; PDFlib PSP (Pretty Safe PDF) showinfo example.
;------------------------------------------------------------------------------------------------------------------------------------------

;------------------------------------------------------------------------------------------------------------------------------------------
#DefineFunction udfSayNoYes (bool) ; returns string "No" or "Yes"
Return (ItemExtract(1+!!bool,"No,Yes",","))
#EndFunction
;------------------------------------------------------------------------------------------------------------------------------------------

; We use the OLE automation object.
oPSP = ObjectOpen("PSPlib_com.PSP")

; Open protected input file with master password (from example 1).
sFilenameIn     = "D:\TEMP\PSP-datasheet-encrypted.pdf"
sPasswordMaster = "PSP"

iResult = oPSP.open_file(sPasswordMaster,sFilenameIn)
If (iResult == -1)
   Message(sMsgTitle,StrCat("Cannot open input PDF file:",@LF,sFilenameIn))
   Goto ErrExit
EndIf


sOutput = ""

If !!oPSP.get_value("pdfversion")
   sPDFVersion = oPSP.get_value("pdfversion") ; Returned number is integer, multiplied by ten.
   sPDFVersion = sPDFVersion / 10.0 ; Force it to float with fractional part of the version number.
   sOutput = StrCat(sOutput,"PDF Version: ",sPDFVersion,@LF) ;
EndIf


iIsPDFEncrypted = !!oPSP.get_value("has/Encrypt")

If iIsPDFEncrypted
   iIsPDFEncryptedUser = !!oPSP.get_value("/Encrypt/user")

   iPDFEncryptAlgorithm = Int(oPSP.get_value("/Encrypt/algorithm"))
   Select iPDFEncryptAlgorithm
   Case -1
      sPDFEncryptAlgorithm = "No standard encryption filter, or unknown to PSP."
      Break
   Case 0
      sPDFEncryptAlgorithm = "No encryption."
      Break
   Case 1
      sPDFEncryptAlgorithm = "40 bit encryption Acrobat 2-4."
      Break
   Case 2
      sPDFEncryptAlgorithm = "128 bit encryption Acrobat 5."
      Break
   EndSelect

   iPDFEncryptKeyLength = oPSP.get_value("/Encrypt/Length") ; Returns a nice float number -->128.0
   iPDFEncryptKeyLength = Int(iPDFEncryptKeyLength) ; Discard the fractional part of the number.

   iIsPDFAccessible = !oPSP.get_value("/Encrypt/noaccessible")
   iIsPDFAnnots     = !oPSP.get_value("/Encrypt/noannots")
   iIsPDFAssemble   = !oPSP.get_value("/Encrypt/noassemble")
   iIsPDFCopy       = !oPSP.get_value("/Encrypt/nocopy")
   iIsPDFForms      = !oPSP.get_value("/Encrypt/noforms")
   iIsPDFHiResPrint = !oPSP.get_value("/Encrypt/nohiresprint")
   iIsPDFModify     = !oPSP.get_value("/Encrypt/nomodify")
   iIsPDFPrint      = !oPSP.get_value("/Encrypt/noprint")

   sOutput = StrCat(sOutput,"File is encrypted.",@LF)
   sOutput = StrCat(sOutput,"Encryption Key Algorithm: ",sPDFEncryptAlgorithm,@LF)
   sOutput = StrCat(sOutput,"Encryption Key Length: ",iPDFEncryptKeyLength," bit",@LF)
   sOutput = StrCat(sOutput,"user password: ",udfSayNoYes(iIsPDFEncryptedUser),@LF)
   sOutput = StrCat(sOutput,"print: "        ,udfSayNoYes(iIsPDFPrint      ),@LF)
   sOutput = StrCat(sOutput,"hiresprint: "   ,udfSayNoYes(iIsPDFHiResPrint ),@LF)
   sOutput = StrCat(sOutput,"modify: "       ,udfSayNoYes(iIsPDFModify     ),@LF)
   sOutput = StrCat(sOutput,"copy: "         ,udfSayNoYes(iIsPDFCopy       ),@LF)
   sOutput = StrCat(sOutput,"annots: "       ,udfSayNoYes(iIsPDFAnnots     ),@LF)
   sOutput = StrCat(sOutput,"forms: "        ,udfSayNoYes(iIsPDFForms      ),@LF)
   sOutput = StrCat(sOutput,"accessible: "   ,udfSayNoYes(iIsPDFAccessible ),@LF)
   sOutput = StrCat(sOutput,"assemble: "     ,udfSayNoYes(iIsPDFAssemble   ),@LF)
Else
   ssOutput = StrCat("File is not encrypted.",@LF)
EndIf


If !!oPSP.get_value("has/Info/Title")
   sPDFInfoTitle = oPSP.get_parameter("/Info/Title")
   sOutput = StrCat(sOutput,'Document info field "Title":',@LF,'"',sPDFInfoTitle,'"',@LF)
EndIf

If !!oPSP.get_value("has/Info/Producer")
   sPDFInfoProducer = oPSP.get_parameter("/Info/Producer")
   sOutput = StrCat(sOutput,'Document info field "Producer":',@LF,'"',sPDFInfoProducer,'"',@LF)
EndIf

If !!oPSP.get_value("has/Info/Author")
   sPDFInfoAuthor = oPSP.get_parameter("/Info/Author")
   sOutput = StrCat(sOutput,'Document info field "Author":',@LF,'"',sPDFInfoAuthor,'"',@LF)
EndIf

If !!oPSP.get_value("has/Info/Subject")
   sPDFInfoSubject = oPSP.get_parameter("/Info/Subject")
   sOutput = StrCat(sOutput,'Document info field "Subject":',@LF,'"',sPDFInfoSubject,'"',@LF)
EndIf

If !!oPSP.get_value("has/Info/Creator")
   sPDFInfoCreator = oPSP.get_parameter("/Info/Creator")
   sOutput = StrCat(sOutput,'Document info field "Creator":',@LF,'"',sPDFInfoCreator,'"',@LF)
EndIf

If !!oPSP.get_value("has/Info/CreationDate")
   sPDFInfoCreationDate = oPSP.get_parameter("/Info/CreationDate")
   sOutput = StrCat(sOutput,'Document info field "CreationDate":',@LF,'"',sPDFInfoCreationDate,'"',@LF)
EndIf

If !!oPSP.get_value("has/Info/ModDate")
   sPDFInfoModDate = oPSP.get_parameter("/Info/ModDate")
   sOutput = StrCat(sOutput,'Document info field "ModDate":',@LF,'"',sPDFInfoModDate,'"',@LF)
EndIf

; Note:
; iResultFalse = oPSP.get_value("has/Info/Autho")  ; Returned number is float number -->0.0 -->@FALSE.
; iResultTrue  = oPSP.get_value("has/Info/Author") ; Returned number is float number -->1.0 -->@TRUE.

Message(sMsgTitle,sOutput)

; Close input and output files.
oPSP.Close

; Close object.
ObjectClose(oPSP)
;------------------------------------------------------------------------------------------------------------------------------------------
Exit
:CANCEL
oPSP.Close
ObjectClose(oPSP)
Exit
;------------------------------------------------------------------------------------------------------------------------------------------
;*EOF*