CS-Script

The CS-Script action allows you to implement a custom script in C# to process the print job. You have the possibility to work with the entire print job data (you are accessing the actual job object) right before and immediately after the conversion. All with the full functionality available in C#.

The used technology is CS-Script. A CLR (Common Language Runtime) based scripting system which uses ECMA-compliant C# as a programming language. By this we provide an interface with pre- and postconversion functions for your own implementation.

For more info on CS-Script please see the official CS-Script documentation.

PDFCreator Server uses CodeDOM hosting. Please be aware of the CodeDOM compatibility when reading the documentation. In general, you can use .net 4.5 with C#5.

Attention

You should only use the CS-Script feature with scripts from trustworthy sources!
The feature addresses experienced programmers, you should not use it in a productive environment if you’re new to programming or C#.
Please understand that the PDFCreator support team is not able to assist you with programming custom scripts!

Settings

You can enable the cs-script action in the advanced section of the queue settings. The setting will always enable pre- and the postconversion functions. If you wish to disable one of the functions, simply implement an empty function with a successful ScriptResult (see PDFCreatorScript Interface below).

The script file must be a .cs or .csx file and must be located in the CS-Scripts Folder in the PDFCreator Server program directory. All the available script files are listed in the dropdown. If the file is not not listed please click on Reload Script List. With Open CS-Scripts Folder you can check the script file location in the windows explorer.

If a script is selected it will be automatically checked and compiled. Potential errors are listed beneath the dropdown. Click on Check Script to repeat the check.

Note

PDFCreator will cache your compiled script while the PDFCreator Server Service is running. You will not lose performace caused by compiling.

Sample Script

PDFCreator is delivered with a sample script file named SetFilenameInPreConversionCreateBackUpInPostConversionScript.cs. It can be found in the CS-Scripts folder in the PDFCreator Server program directory.

The script sets a new output file template before the conversion and creates a backup file afterwards. The backup folder gets created in the target folder and is named after the filename with an appended “_backup”. The script will succeed if the backup is created and will abort if it fails or the backup file already exists.

PDFCreatorScript Interface

The custom script needs to provide a class that implements the PDFCreatorScript interface.

public interface IPDFCreatorScript
{
        ScriptResult PreConversion(Job job, Logger logger);
        ScriptResult PostConversion(Job job, Logger logger);
}

The PreConversion function is called immediately before the conversion of a document, PostConversion directly afterwards.

References

Ensure the following using directives in your script:

using NLog;
using pdfforge.CustomScriptAction;
using pdfforge.PDFCreator.Conversion.Jobs.Jobs;
using pdfforge.PDFCreator.Conversion.Settings;
using pdfforge.PDFCreator.Utilities.Tokens;

You can use the NLogg.dll, CustomScriptAction.dll, PDFCreator.Jobs.dll, PDFCreator.Settings.dll and the PDFCreator.Utilities.dll files from the PDFCreator Server program directory to embed them in your IDE. The script compiler will automatically consider all the DLLs in the PDFCreator Server program directory and the CS-Scripts folder.

Note

If you are referencing external libraries the required DLL files must be located in the CS-Scripts folder in the PDFCreator Server program directory.

ScriptResult

The return value can be either ScriptResult.Success for an successful execution (or at least to continue the current job) or ScriptResult.Abort to cancel the current job.

Logger

The given logger is the current logger from the PDFCreator, so the logs entries from the custom script are included in the general PDFCreator log according to the current log level (see Debug).

The logger is a NLog.Logger. The common functions to log on a certain log level are:

logger.Debug(messagestring)
logger.Warn(messagestring)
logger.Warn(exception, messagestring)
logger.Error(messagestring)
logger.Error(exception, messagestring)

Job Class

The job class contains all the data of the current job including the current profile (see below).

Note

The job class works with a copy of the current profile and all the job data is monetary. Changed data (including passwords) will be not be saved and will be discarded when the job is finished.

At execution time of the script some data from the profile is already processed. All the listed properties will be used instead the related data in the profile:

OutputFileTemplate

This is the template to the full path of the future output file. Used tokens are already replaced. If applicable, the output filename will be extended automatically by a page number (for multi file formats) or a counter to ensure an unique filename.

OutputFiles

List of output files generated during conversion

Passwords

The JobPasswords class contains properties for passwords of each action.

For example:

job.Passwords.PdfUserPassword = "1234";
job.Passwords.PdfOwnerPassword = "Swordfish";

Note

For missing passwords the profile check will fail. Please disable the concerned action in the settings and enable it in the PreConversion function of the script.

Accounts

The Accounts class contains for functions to access the accounts for each action - pass the current profile to get the current account.

For example:

job.Accounts.GetFtpAccount(job.Profile);

Note

For incomplete accounts the profile check will fail. Please disable the concerned action in the settings and enable it in the PreConversion function of the script.

The required password must be set in the job.Passwords property

If you want to create a new Account, you have to give it an AccountId, add the new account to job.Accounts and set the AccountId in the profile.

JobInfo

Contains the Metadata from the print job, the time of printing (PrintDateTime) and a function to determine the total number of pages: job.JobInfo.CalculateTotalPages()

TokenReplacer

Use the TokenReplacer to extract the values from your UserTokens.

var userTokenValue = job.TokenReplacer.GetToken("User").GetValueWithFormat("YourUserTokenKey");
                                               //GetToken is always called with "User"
                                                                                                                      //Just change your requested UserToken key

Profile Class

The job class contains the profile with the following settings:

Setting Type Description
AuthorTemplate String Template for the Author field. This may contain tokens.
FileNameTemplate String Template of which the filename will be created. This may contain Tokens.
Guid String GUID of the profile
KeywordTemplate String Template for the Keyword field. This may contain tokens.
Name String Name of the profile
OpenViewer Bool Open the default viewer after converting the document
OpenWithPdfArchitect Bool If the output is a PDF, use PDF Architect instead of the default PDF viewer
OutputFormat Enum Default format for this print job. Valid values: Pdf, PdfA1B, PdfA2B, PdfX, Jpeg, Png, Tif, Txt
ShowAllNotifications Bool Show a notification after converting the document
ShowOnlyErrorNotifications Bool Only show notification for error
ShowProgress Bool If true, a progress window will be shown during conversion
ShowQuickActions Bool Show quick actions page after converting the document
SkipPrintDialog Bool Allows to skip the print dialog (where metadata are set) and directly proceed to the save dialog
SubjectTemplate String Template for the Subject field. This may contain tokens.
TargetDirectory String Directory in which the files will be saved (in interactive mode, this is the default location that is presented to the user)
TitleTemplate String Template for the Title field. This may contain tokens.
AttachmentPage
Appends one or more pages at the end of the converted document
AttachmentPage.Enabled Bool Enables the AttachmentPage action
AttachmentPage.File String Filename of the PDF that will be appended
BackgroundPage
Adds a page background to the resulting document
BackgroundPage.Enabled Bool Enables the BackgroundPage action
BackgroundPage.File String Filename of the PDF that will be used as background
BackgroundPage.OnAttachment Bool If true, the background will be placed on the attachment as well
BackgroundPage.OnCover Bool If true, the background will be placed on the cover as well
BackgroundPage.Repetition Enum Defines the way the background document is repeated. Valid values: NoRepetition, RepeatAllPages, RepeatLastPage
CoverPage
Inserts one or more pages at the beginning of the converted document
CoverPage.Enabled Bool Enables the CoverPage action
CoverPage.File String Filename of the PDF that will be inserted
CustomScript
Pre- and postconversion actions calling functions from a custom script
CustomScript.Enabled Bool Enables the custom script pre- and postconversion action
CustomScript.ScriptFilename String Filename of the custom script in application directory ‘Cs-Scripts’ folder
DropboxSettings
Dropbox settings for currently logged user
DropboxSettings.AccountId String ID of the linked account
DropboxSettings.CreateShareLink Bool  
DropboxSettings.Enabled Bool  
DropboxSettings.EnsureUniqueFilenames Bool If true, files with the same name will not be overwritten on the server. A counter will be appended instead (i.e. document_2.pdf)
DropboxSettings.SharedFolder String  
EmailClientSettings
Opens the default e-mail client with the converted document as attachment
EmailClientSettings.AddSignature Bool Add the PDFCreator signature to the mail
EmailClientSettings.Content String Body text of the e-mail
EmailClientSettings.Enabled Bool Enables the EmailClient action
EmailClientSettings.Html Bool Use html for e-mail body
EmailClientSettings.Recipients String The list of receipients of the e-mail, i.e. info@someone.com; me@mywebsite.org
EmailClientSettings.RecipientsBcc String The list of receipients of the e-mail in the ‘BCC’ field, i.e. info@someone.com; me@mywebsite.org
EmailClientSettings.RecipientsCc String The list of receipients of the e-mail in the ‘CC’ field, i.e. info@someone.com; me@mywebsite.org
EmailClientSettings.Subject String Subject line of the e-mail
EmailSmtpSettings
Sends a mail without user interaction through SMTP
EmailSmtpSettings.AccountId String ID of linked account
EmailSmtpSettings.AddSignature Bool Add the PDFCreator signature to the mail
EmailSmtpSettings.Content String Body text of the mail
EmailSmtpSettings.Enabled Bool If true, this action will be executed
EmailSmtpSettings.Html Bool Use html for e-mail body
EmailSmtpSettings.Recipients String The list of receipients of the e-mail, i.e. info@someone.com; me@mywebsite.org
EmailSmtpSettings.RecipientsBcc String The list of receipients of the e-mail in the ‘BCC’ field, i.e. info@someone.com; me@mywebsite.org
EmailSmtpSettings.RecipientsCc String The list of receipients of the e-mail in the ‘CC’ field, i.e. info@someone.com; me@mywebsite.org
EmailSmtpSettings.Subject String Subject line of the e-mail
Ftp
Upload the converted documents with FTP
Ftp.AccountId String ID of the linked account
Ftp.Directory String Target directory on the server
Ftp.Enabled Bool If true, this action will be executed
Ftp.EnsureUniqueFilenames Bool If true, files with the same name will not be overwritten on the server. A counter will be appended instead (i.e. document_2.pdf)
Ghostscript
Ghostscript settings
Ghostscript.AdditionalGsParameters String These parameters will be provided to Ghostscript in addition to the PDFCreator parameters
HttpSettings
Action to upload files to a HTTP server
HttpSettings.AccountId String  
HttpSettings.Enabled Bool If true, this action will be executed
JpegSettings
Settings for the JPEG output format
JpegSettings.Color Enum Number of colors. Valid values: Color24Bit, Gray8Bit
JpegSettings.Dpi Int Resolution of the JPEG files
JpegSettings.Quality Int Quality factor of the resulting JPEG (100 is best, 0 is worst)
PdfSettings
Settings for the PDF output format
PdfSettings.ColorModel Enum Color model of the PDF (does not apply to images). Valid values: Rgb, Cmyk, Gray
PdfSettings.DocumentView Enum Defines which controls will be opened in the reader. Valid values: NoOutLineNoThumbnailImages, Outline, ThumbnailImages, FullScreen, ContentGroupPanel, AttachmentsPanel
PdfSettings.EnablePdfAValidation Bool Enable PdfAValidation
PdfSettings.PageOrientation Enum Define how pages are automatically rotated. Valid values: Automatic, Portrait, Landscape
PdfSettings.PageView Enum Defines how the document will be opened in the reader. Valid values: OnePage, OneColumn, TwoColumnsOddLeft, TwoColumnsOddRight, TwoPagesOddLeft, TwoPagesOddRight
PdfSettings.ViewerStartsOnPage Int Defines the page number the viewer will start on when opening the document
CompressColorAndGray
Compression settings for color and greyscale images
PdfSettings.CompressColorAndGray.Compression Enum Settings for the compression method. Valid values: Automatic, JpegMaximum, JpegHigh, JpegMedium, JpegLow, JpegMinimum, JpegManual, Zip
PdfSettings.CompressColorAndGray.Dpi Int Images will be resampled to this maximum resolution of the images, if resampling is enabled
PdfSettings.CompressColorAndGray.Enabled Bool If true, color and grayscale images will be processed according to the algorithm. If false, they will remain uncompressed
PdfSettings.CompressColorAndGray.JpegCompressionFactor Double Define a custom compression factor (requires JpegManual as method)
PdfSettings.CompressColorAndGray.Resampling Bool If true, the images will be resampled to a maximum resolution
CompressMonochrome
Compression settings for monochrome images
PdfSettings.CompressMonochrome.Compression Enum Settings for the compression method. Valid values: CcittFaxEncoding, Zip, RunLengthEncoding
PdfSettings.CompressMonochrome.Dpi Int Images will be resampled to this maximum resolution of the images, if resampling is enabled
PdfSettings.CompressMonochrome.Enabled Bool If true, monochrome images will be processed according to the algorithm. If false, they will remain uncompressed
PdfSettings.CompressMonochrome.Resampling Bool If true, the images will be resampled to a maximum resolution
Security
PDF Security options
PdfSettings.Security.AllowPrinting Bool Allow to user to print the document
PdfSettings.Security.AllowScreenReader Bool Allow to user to use a screen reader
PdfSettings.Security.AllowToCopyContent Bool Allow to user to copy content from the PDF
PdfSettings.Security.AllowToEditAssembly Bool Allow to user to make changes to the assembly
PdfSettings.Security.AllowToEditComments Bool Allow to user to edit comments
PdfSettings.Security.AllowToEditTheDocument Bool Allow to user to edit the document
PdfSettings.Security.AllowToFillForms Bool Allow to user to fill in forms
PdfSettings.Security.Enabled Bool If true, the PDF file will be password protected
PdfSettings.Security.EncryptionLevel Enum Defines the encryption level. Valid values: Rc40Bit, Rc128Bit, Aes128Bit, Aes256Bit
PdfSettings.Security.OwnerPassword String Password that can be used to modify the document
PdfSettings.Security.RequireUserPassword Bool If true, a password is required to open the document.
PdfSettings.Security.RestrictPrintingToLowQuality Bool If true, only printing in low resolution will be supported
PdfSettings.Security.UserPassword String Password that must be used to open the document (if set)
Signature
Digitally sign the PDF document
PdfSettings.Signature.AllowMultiSigning Bool If true, the PDF file may be signed by additional persons
PdfSettings.Signature.CertificateFile String Path to the certificate
PdfSettings.Signature.DisplaySignatureInDocument Bool If true, the signature will be displayed in the PDF file
PdfSettings.Signature.Enabled Bool If true, the signature will be displayed in the PDF document
PdfSettings.Signature.LeftX Int Signature location: Top left corner (X part)
PdfSettings.Signature.LeftY Int Signature location: Top left corner (Y part)
PdfSettings.Signature.RightX Int Signature location: Bottom right corner (X part)
PdfSettings.Signature.RightY Int Signature location: Bottom right corner (Y part)
PdfSettings.Signature.SignContact String Contact name of the signature
PdfSettings.Signature.SignLocation String Signature location
PdfSettings.Signature.SignReason String Reason for the signature
PdfSettings.Signature.SignatureCustomPage Int If the signature page is set to custom, this property defines the page where the signature will be displayed
PdfSettings.Signature.SignaturePage Enum Defines the page on which the signature will be displayed. Valid values: FirstPage, LastPage, CustomPage
PdfSettings.Signature.SignaturePassword String Password for the certificate file
PdfSettings.Signature.TimeServerAccountId String ID of the linked account for the timeserver
PngSettings
Settings for the PNG output format
PngSettings.Color Enum Number of colors. Valid values: Color32BitTransp, Color24Bit, Color8Bit, Color4Bit, Gray8Bit, BlackWhite
PngSettings.Dpi Int Resolution of the PNG files
Printing
Print the document to a physical printer
Printing.Duplex Enum Defines the duplex printing mode. Valid values: Disable, LongEdge, ShortEdge
Printing.Enabled Bool If enabled, the document will be printed to a physical printer
Printing.PrinterName String Name of the printer that will be used, if SelectedPrinter is set.
Printing.SelectPrinter Enum Method to select the printer. Valid values: DefaultPrinter, ShowDialog, SelectedPrinter
Scripting
The scripting action allows to run a script after the conversion
Scripting.Enabled Bool If true, the given script or application will be executed
Scripting.ParameterString String Parameters that will be passed to the script in addition to the output files
Scripting.ScriptFile String Path to the script or application
Scripting.WaitForScript Bool Wait until the script excution has ended
Stamping
Place a stamp text on all pages of the document
Stamping.Color Color Color of the text
Stamping.Enabled Bool If true, the document all pages will be stamped with a text
Stamping.FontAsOutline Bool If true, the text will be rendered as outline. If false, it will be filled.
Stamping.FontName String Name of the font. (this is only used as a hint, the PostScriptFontName contains the real name)
Stamping.FontOutlineWidth Int Width of the outline
Stamping.FontSize Float Size of the font
Stamping.PostScriptFontName String PostScript name of the stamp font.
Stamping.StampText String Text that will be stamped
TextSettings
TextSettings.Format Int Text Format (0 outputs XML-escaped Unicode along with information regarding the format of the text | 1 same XML output format, but attempts similar processing to MuPDF, and will output blocks of text | 2 outputs Unicode (UCS2) text (with a Byte Order Mark) which approximates the original text layout | 3 same as 2 encoded in UTF-8)
TiffSettings
Settings for the TIFF output format
TiffSettings.Color Enum Number of colors. Valid values: Color24Bit, Color12Bit, Gray8Bit, BlackWhiteG3Fax, BlackWhiteG4Fax, BlackWhiteLzw
TiffSettings.Dpi Int Resolution of the TIFF files
UserTokens
Parse ps files for user definied tokens
UserTokens.Enabled Bool Activate parsing ps files for user tokens (Only available in PDFCreator Business)
UserTokens.Seperator Enum UserToken seperator in the document Valid values: SquareBrackets, AngleBrackets, CurlyBrackets, RoundBrackets