pdfServMachine is a Software Development Kit (SDK) for PDF conversion and manipulation.
• Easily convert your HTML, text and Microsoft Office files to PDF.
• Integrate PDF generation into virtually any application that can print.
• Manipulate existing PDF documents.
• pdfServMachine runs on Windows NT/2000/XP/2003 and exposes a COM API.
• pdfMachine 10.2 or latter must be installed. The latest version is available
at
http://pdfmachine.de
• Internet Explorer 6
1. Download
Down and unzip the SDK to a suitable directory.
e.g. c:\pdfServMachine
2. Register the COM server
From the command line, run:
pdfServMachine /RegServer
Depending upon the your security settings, you may be able to now use
pdfServMachine or you may need use dcomcnfg.exe to add your users to the access
list. See the section on
dcomcnfg.exe in the service installation instructions if required.
Before installing the service, think very hard as to whether this is the way to go for you, as it adds a lot of extra configuration steps. In most cases it is unnecessary to install pdfServMachine as a service.
click here for details on service installation
From the command line, run:
pdfServMachine.exe /UnregServer
The JavaScript examples can be be saved to a file with a ".js" extension and
executed with either wscript.exe or cscript.exe.
Look at the following sample javascript to see how easy it is to use pdfServMachine:
// Example javascript script to convert the
// www.google.com web page to a PDF file
var conv = new ActiveXObject("pdfServMachine.converter");
conv.convert("http://www.google.com", "c:\\google.pdf");
WScript.Echo("finished conversion");
This time around the calling application starts the windows print job. The file c:\x.txt is converted to the PDF file c:\x.pdf, but Notepad.exe does the printing.
var conv = new ActiveXObject("pdfServMachine.converter");
var shell = new ActiveXObject("WScript.Shell");
conv.printJobStart("c:\\x.pdf", true);
shell.Run("notepad.exe /p c:\\x.txt");
conv.printJobEnd(true, false);
WScript.Echo("finished conversion");
// Example javascript script to that merges
// several PDF's into one big PDF.
var pdf = new ActiveXObject("pdfServMachine.Pdf");
pdf.append("c:\\afile.pdf");
pdf.append("c:\\bfile.pdf");
pdf.append("c:\\cfile.pdf");
pdf.saveAs("c:\\mergedFile.pdf");
//
// Example javascript that signs the document c:\x.pdf and saves
// it as c:\withSig.pdf
//
var pdf = new ActiveXObject("pdfServMachine.Pdf")
try
{
var certName = "self signer test cert"
if (!pdf.open("c:/x.pdf"))
throw "open failed";
if (!pdf.addSignature(
true, // is signature visible
"My", // store
certName, // cert name
"", // Issuer name (optional)
"", // Serial number (optional)
"", // key blob (optional)
"", // location (optional)
"I agree", // reason
"", // image file (optional)
1, // Display flags - show reason text
1, // page num
"bottomleft", // position relative to
0, 0, 100, 100)) // xoffset, yoffset, width, height
throw "addSignature failed";
if (!pdf.saveAs("c:/withSig.pdf"))
throw "saveAs failed";
WScript.Echo("The file c:/withSig.pdf has been signed");
}
catch(e)
{
WScript.Echo("Exception " + e + "\nError: "+pdf.getErrorMessage());
}
//
// Example javascript that creates a self signed certificate in
// the default cert store.
//
var pdf = new ActiveXObject("pdfServMachine.Pdf")
try
{
var certName = "self signer test cert"
if (!pdf.createSelfSignedCertificate(
certName,
"Development", // org unit
"Broadgun", // org name
"test@blah.com", // email
"Melbourne", // locale
"Victoria", // state
"AU")) // 2 char country code
throw "createSelfSignedCertificate failed";
WScript.Echo("The certificate has been created. Cert name: "
+certName);
}
catch(e)
{
WScript.Echo("Exception " + e + "\nError: "+
pdf.getErrorMessage());
}
//
// Example javascript that signs the document c:\x.pdf and saves
// it as c:\withSig.pdf
// First exports key to a string.
//
var pdf = new ActiveXObject("pdfServMachine.Pdf")
try
{
var certName = "self signer test cert"
var keyString = ""
keyString = pdf.exportKeysByCertificateName(certName)
if (keyString.length == 0)
throw "explortKeysByCertificateName failed";
if (!pdf.open("c:/x.pdf"))
throw "open failed";
if (!pdf.addSignature(
true, // is signature visible
"My", // store
certName, // cert name
"", // Issuer name (optional)
"", // Serial number (optional)
keyString, // key blob (optional)
"", // location (optional)
"I agree", // reason
"", // image file (optional)
1, // Display flags - show reason text
1, // page num
"bottomleft", // position relative to
0, 0, 100, 100)) // xoffset, yoffset, width, height
throw "addSignature failed";
if (!pdf.saveAs("c:/withSig.pdf"))
throw "saveAs failed";
WScript.Echo("The file c:/withSig.pdf has been signed");
}
catch(e)
{
WScript.Echo("Exception " + e + "\nError: "+pdf.getErrorMessage());
}
// Example that generates a PDF file by explicitly
// printing to the pdfMachine printer.
// Compiled with msvc ++ 2003
// Compiler command line used: cl /EHsc print2pdf.cpp
#include <stdio.h>
#include <tchar.h>
#include <time.h>
// generates all the code for the smart pointers
#import "c:/dev/pdfservmachine/release/pdfservmachine.exe"
const TCHAR *errMsg = 0;
// initializes a devmode for printing
void initDevmode(DEVMODE *dm)
{
memset(dm, 0, sizeof(DEVMODE));
dm->dmSize = sizeof(DEVMODE);
dm->dmOrientation = DMORIENT_PORTRAIT ;
_tcscpy((TCHAR*)dm->dmFormName, TEXT("A4"));
dm->dmFields = DM_ORIENTATION | DM_FORMNAME;
}
// Prints "numPages" of boring text to the printer "printerName".
bool doPrint(const TCHAR *printerName, int numPages)
{
if (printerName == 0 || _tcslen(printerName) == 0 )
printerName = _T("Broadgun pdfMachine");
DEVMODE dm;
initDevmode(&dm);
HDC dc = CreateDC(0, printerName, 0,&dm);
if (!dc)
{
errMsg = "CreateDC failed";
return false;
}
DOCINFO di = {0};
di.cbSize = sizeof(di);
di.lpszDocName = "doc name";
int rc = StartDoc(dc, &di);
if (rc == SP_ERROR)
{
errMsg = "StartDoc failed";
return false;
}
char str[100];
sprintf(str, "On Page %d", 0);
SIZE sz;
GetTextExtentPoint32(dc, str, (int)strlen(str), &sz);
for (int i = 0; i < numPages; i++)
{
rc = StartPage(dc);
if (rc <= 0)
{
errMsg = "StartPage failed";
return false;
}
SetMapMode(dc, MM_TEXT);
LOGFONT lf = {0};
lf.lfHeight = 50;
strcpy(lf.lfFaceName, "Arial");
HFONT font = CreateFontIndirect(&lf);
HFONT oldFont = (HFONT)SelectObject(dc, font);
sprintf(str, "On Page %d", i);
for (int j = 0; j < 2; j++)
{
TextOut(dc, 0, sz.cy*j, str, (int)strlen(str));
}
rc = EndPage(dc);
if (rc <= 0)
{
errMsg = "EndPage failed";
return false;
}
SelectObject(dc, oldFont);
DeleteObject(font);
}
rc = EndDoc(dc);
if (rc <= 0)
{
errMsg = "EndDoc failed";
return false;
}
DeleteDC(dc);
return true;
}
// Generates a PDF files.
// The number of files generated is controlled by the "numFiles".
void doTest(int numFiles)
{
TCHAR filename[MAX_PATH];
pdfServMachineLib::IconverterPtr conv;
conv.CreateInstance(L"pdfServMachine.converter");
if (conv == 0)
{
_tprintf(_T("Error: could not create pdfServMachine.converter\n"));
return;
}
srand(time(0));
int randNum = rand();
for (int i = 0; i < numFiles; i++)
{
_stprintf(filename, _T("C:/tmp/Ptest_%d_%d.pdf"), randNum, i);
if (!conv->printJobStart(_bstr_t(filename), false))
goto fail;
if (!doPrint(_T("Broadgun pdfMachine"), 10))
{
_tprintf(_T("print doc failed: %s\n"), errMsg);
break;
}
if (!conv->printJobEnd(false, false))
goto fail;
}
_tprintf(_T("Created %d files. Last file [%s].\n"), i, filename);
return;
fail:
{
_bstr_t err = conv->getErrorMessage();
_tprintf(_T("Error: %s\n"), (const TCHAR *)err);
_tprintf(_T("Created %d files. Last file [%s].\n"), i, filename);
}
}
void _tmain(int argc, TCHAR *argv[])
{
// read in command line parameter for number of files to generate
int numFiles = 1;
if (argc > 1)
numFiles = _ttoi(argv[1]);
CoInitialize(0);
try
{
doTest(numFiles);
}
catch (_com_error &e)
{
_tprintf(_T("COM Error: %d. %s\n"), e.Error(),
(const TCHAR*)e.ErrorMessage());
}
CoUninitialize();
}
Converts a document or web page to a PDF file.
BOOL convert( BSTR inFileName, BSTR outFileName, BOOL postProcess )
The full path of the document to be converted to PDF. This can be a document that can be printed with the Shellexec api, such as a MS Word file or a text file or it can be the url of a web page.
The resulting PDF filename.
If TRUE, normal pdfMachine processing of the PDF file occurs
applying features such as encryption, N-Up, stationery and doc. info.
- if
they are enabled. These features can be enabled within the pdfMachine
options dialog, or by directly setting registry entries. If you wish
to directly set a registry entry, please read
http://www.broadgun.de/pdfmachine/developer.htm for details.
TRUE if success, otherwise FALSE.
Used when the calling application is starting the Windows print job. Must be followed by a printJobEnd() after the print job has been started.
BOOL printJobStart(BSTR outFileName, BOOL setDefPrinter)
The resulting PDF filename.
If TRUE, the Windows default printer is set to the current pdfMachine printer, usually "Broadgun pdfMachine". The default printer prior to this call can be restored by setting the "restoreDefPrinter" flag in the corresonding printJobEnd call.
TRUE if success, otherwise FALSE.
Ends a print job previously opened with printJobStart(). This call blocks until the print spooler has finished printing.
BOOL printJobEnd(BOOL restoreDefPrinter, BOOL postProcess)
If TRUE, the default windows printer is restored to what it was previously, otherwise it is left alone.
If TRUE, normal pdfMachine processing of the PDF file occurs
applying features such as encryption, N-Up, stationery and doc. info.
- if
they are enabled. These features can be enabled within the pdfMachine
options dialog, or by directly setting registry entries. If you wish
to directly set a registry entry, please read
http://www.broadgun.de/pdfmachine/developer.htm for details.
TRUE if success, otherwise FALSE.
Opens a PDF file ready for manipulation.
BOOL open(BSTR fileName)
The full path of the PDF file to be opened.
TRUE if success, otherwise FALSE.
Creates a PDF file containing the result of the PDF manipulation.
BOOL saveAs(BSTR fileName)
The full path of the PDF file to be written to.
TRUE if success, otherwise FALSE.
Opens the PDF file 'fileName' and appends the contents to our internal representation.
BOOL append(BSTR fileName)
The full path of the PDF file that will be read in.
TRUE if success, otherwise FALSE.
Deletes a page.
BOOL deletePage(int pageNum)
The number of the page to be deleted.
TRUE if success, otherwise FALSE.
Deletes a page.
int getNumPages()
The number of pages.
Applies stationery. The first page of the 'stationeryFile' is drawn on each page specified.
BOOL setStationery(BSTR stationeryFile, int startPage, int endPage, BOOL ontop)
The path of the file to be read in and used as stationery.
The first page to have stationery applied.
The last page to have stationery applied is endPage -1. If endPage is -1, then all pages will have stationery applied.
If TRUE, the stationery is drawn after the existing page has been drawn, otherwise it is drawn first.
TRUE if success, otherwise FALSE.
Applies N-Up processing, where 2, 4 or 8 pages are shrunk and drawn on the one page.
BOOL applyNup(BSTR pageSize, int numPagesOnEachPage,
int margin, int borderThickness)
A common page name, such as "A4" or "Letter". Valid values are:
4A, 2A, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, 4B, 2B, B0, B1,
B2, B3, B4, B5, B6, B7, B8, B9, B10, SRA0, SRA1, SRA2, SRA3, SRA4,
RA0, RA1, RA2, C0, C1, C2, C3, C4, C5, C6, C7/6, C7, DL, A3, extra,
A4, extra, Letter, Legal, Executive, Ledger, Tabloid.
Either 1, 2, 4 or 8.
The size of the margin between pages, measured in points.
The size of the border drawn around each page measured in points. -1 means no border, 0 means as thin as possible.
TRUE if success, otherwise FALSE.
Applies N-Up processing, where 2, 4 or 8 pages are shrunk and drawn on the one page.
BSTR getErrorMessage()
A description of what went wrong. This is set if any of the functions return FALSE.
Saves a PDF file with PDF standard security and encryption.
BOOL saveWithSecurity(BSTR fileName, BSTR userPass, BSTR ownerPass,
int flags, int keysizeInBits)
The full path of the PDF file to be written to.
The password for opening the PDF file. May be empty.
The password for changing permissions in the PDF file. .
Flags as returned by makeEncryptFlags128() or makeEncryptFlags40().
The key size. The values of 40 or 128 are allowed.
TRUE if success, otherwise FALSE.
Creates 40 bit encryption flags for use by saveWithSecurity().
int makeEncryptFlags40(BOOL print, BOOL change,
BOOL copy, BOOL addnotes)
If true, printing will be allowed.
If true, changing of the document will be allowed.
If true, copying will be allowed.
If true, annotations will be allowed.
The flags to be passed to saveWithSecurity().
Creates 128 bit encryption flags for use by saveWithSecurity().
int makeEncryptFlags128(BOOL print, BOOL change,
BOOL copyAndExtract, BOOL addnotes,
BOOL formFillOrSign, BOOL extractAccessibility,
BOOL assemble, BOOL hiResPrint)
If true, printing will be allowed.
If true, changing of the document will be allowed.
If true, copying and extraction will be allowed.
If true, annotations will be allowed.
If true, filling our of forms and document signing will be allowed.
If true, extraction for accessibility purposes is allowed.
If true, document assembly is allowed.
If true, hi-res printing is allowed.
The flags to be passed to saveWithSecurity().
Sets document information properties.
BOOL setDocInfo(BSTR name, BSTR value)
The name of the value to be set. Allowed values are: Author, Title, Subject, Keywords.
If corresponding value.
TRUE if success.
Adds a blank new page to the current PDF document.
BOOL addPage(long width, long height)
The width of the page in points.
The height of the page in points.
TRUE if success.
Adds a digital signature to the PDF. Uses Windows certificate management. To see what certificates are installed, open up Control Panel, select "Internet Options", then "Content", then "Certificates".
BOOL addSignature( BOOL isVisibile, BSTR storeName, BSTR certName, BSTR issuerName, BSTR serialNum, BSTR keyBlob, BSTR location, BSTR reason, BSTR imageFile, LONG textDisplayFlags, LONG pageNum, BSTR anchorPosition, LONG x, LONG y, LONG width, LONG height)
If true the signature will be visible on the page, otherwise there will be no appearance, but the signature will be present in the signature tab of acrobat reader.
Optional. The name of the Windows certificate store. Defaults to "My".
The common name of the certificate. If the certificate is issued to a person, it is usually the persons name.
Optional. The name of the issuer. Used when there are multiple certificates with the same common name. The combination of issuerName and serialNum is unique.
Optional. A hex encoded string that is the serial number of the certificate to use. Used when there are multiple certificates with the same common name. The combination of issuerName and serialNum is unique.
Optional. A hex encoded key used for signing. This is returned from exportKeysByCertificateName. It is used to avoid Windows showing the "accessing a private key" dialog box, which would be problematic for unattended applications/services.
Optional. The location string in the signature. e.g. "City of Melbourne".
Optional. The reason string in the signature. e.g. "I agree".
Optional. The full path of an image file that will appear in the signature. JPEG, BMP and GIF files can be used.
A bitmask that controls what text appears on the signature
appearance.
The following hex values may be OR'ed together.
0x01 - Certificate Name
0x02 - Location
0x04 - Reason
0x08 - Time/Date
0x20 - Big certificate Name
The page to place the signature on. 1 is the first page, -1 means the last page.
Effects the position of the signature by controlling what the X
and Y values are anchored to. Can be either: topleft, topright,
bottomleft, bottomright, center, centerleft, centerright, centertop,
centerbottom.
Used to combination with "anchorPosition" to set the X coordinate. Units are in points.
Used to combination with "anchorPosition" to set the Y coordinate. Units are in points.
The signature width. Units are in points.
The signature height. Units are in points.
TRUE if success.
Exports the keys associated with a certificate as a hex string.
The value returned can be used in the
addSignature method. The returned keys are not
encrypted.
This method will cause Windows to display the "accessing a
private key" dialog box, however when the result is passed to
addSignature, no dialog will be
shown.
BSTR exportKeysByCertificateName(BSTR certName)
The certificate name.
Unencrypted hexencoded key string to be used in the "keyBlob" parameter of addSignature.
Creates a self signed certificate. The certificate is created in the Windows Certificate "My" store.
BOOL createSelfSignedCertificate(BSTR certName,
BSTR orgUnit, BSTR orgName,
BSTR email, BSTR localeName,
BSTR stateName, BSTR countryCode)
The certificate name.
Optional. The organizational unit.
Optional. The organizational name.
Optional. The email address.
Optional. The locale.
Optional. The state.
Optional. The 2 char country code.
TRUE if success.
14 Oct 2004 - 1.4
Fixed problem where createSelfSignedCertificate was failing on NT and W2K.
Added more examples to readme file.
Sep 2004 - 1.3
Fixed bug that displayed signature appearance in wrong spot. Also added new
parameter "storeName" to addSignature method.
3 Sep 2004 - 1.2
Added support for digital signatures.
5 Aug 2004 - 1.1
First commercial release.
Added saveWithSecurity, setDocInfo, makeEncryptFlags40, makeEncryptFlags128.
26 Feb 2004 - beta5
Added printJobStart() printJobEnd() methods to the Converter object.
20 Feb 2004 - beta4
Improved notes on installation in this file. No changes to the program.
18 Feb 2004 - beta3
Added new COM class, Pdf, for PDF manipulation.
10 Jan 2004 - beta2
First public beta.
![]()