Generate a PDF on the server (GUIDE)

The problem.

CWP and Data API scripts cannot run Save Records as PDF directly, nor do they have access to the file system.

The solution

Use Perform Script On Server to start a new script session that runs without the limitations of CWP/Data API. After establishing context, the following steps create a PDF and then insert it into a container:

Set Variable [ $path ; Value: Get ( TemporaryPath ) & "Sample Filename.pdf" ]
Save Records as PDF [ Restore ; With dialog: Off ; "$path" ; Current Record ; Create folders: Off ]
Set Variable [ $urlpath ; "file://" & If ( Get ( SystemPlatform ) = 1 ; "/Volumes" ) & $path ]
Insert from URL [ Select ; With dialog: Off ; Target: $file ; $urlpath ; cURL options: "--FM-return-container-variable" ]
Set Field [ Table::ContainerField ; $file ]
Commit Records/Requests  [ With dialog: Off ]

Notes & gotchas

Ensure that With Dialog is Off on the Save Records as PDF script step.

Allow Printing must be enabled in the privilege set, otherwise you will get error 3.

All of the regular gotchas of PSOS apply, so you need to pass in whatever information is needed to establish the correct context. Also check your OnFirstWindowOpen script to ensure any unnecessary steps are bypassed when running on the server.

Save the PDF to the temporary folder has important benefits: 1) a new temporary folder is created for every session so there is no risk your data will be exposed to another session running at the same time, 2) the data is destroyed automatically when the session ends.

Insert File is not supported on server scripts so to get the PDF into a container, you need to use Insert From URL. Insert from URL uses a different format for the file path. The calculation in the example above should work on Mac & Windows servers. Unsure about Linux.

My preference is always to save the result of Insert from URL into a variable, since saving to a field requires that the field be on the current layout. When the result of Insert from URL is binary data, you must include the cURL option –FM-return-container-variable. You can then transfer the result to a field without having the layout dependency.

Some resources online claim that the account requires fmapp extended privilege in order to run PSOS. This may be true in version 16 or earlier, but I can confirm that this is not the case in version 17 or 18.

1 Like

Confirmed that this script works with FileMaker Server running on Ubuntu without modification. Tested using FMS 19.3.1.