pdfServMachine by Broadgun Software

Readme

 

Overview

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.

 

Prerequisites

• pdfMachine 10.2 or latter must be installed. The latest version is available at http://pdfmachine.de
• Internet Explorer 6
 

 

Installation - Out of Process COM Server

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.

 

Installation - Service

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

   

Un-Installation

From the command line, run:

pdfServMachine.exe /UnregServer

 

 

Examples

The JavaScript examples can be be saved to a file with a ".js" extension and executed with either wscript.exe or cscript.exe.  
 

Convert  to PDF example

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");

Convert  to PDF example - calling app does print

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");

Append PDF example

// 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");


Add signature example

//
// 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());
}

Create Self Signed Certificate Example

//
// 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());
}

Export key, then Sign Example

//
// 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());
}

C++ Example

// 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();
}






 

COM API for "pdfServMachine.converter"

 

convert

Converts a document or web page to a PDF file.

BOOL convert(	BSTR inFileName, 
		BSTR outFileName, 
		BOOL postProcess )

Parameters

BSTR inFileName

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. 

BSTR outFileName

The resulting PDF filename.

BOOL postProcess

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.
 

Returns

TRUE if success, otherwise FALSE.

 

printJobStart

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)

Parameters

BSTR outFileName

The resulting PDF filename.

BOOL setDefPrinter

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.

Returns

TRUE if success, otherwise FALSE.

 

printJobEnd

Ends a print job previously opened with printJobStart().   This call blocks until the print spooler has finished printing. 

BOOL printJobEnd(BOOL restoreDefPrinter, BOOL postProcess)

Parameters

BOOL restoreDefPrinter

If TRUE, the default windows printer is restored to what it was previously, otherwise it is left alone.

BOOL postProcess

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.
 

Returns

TRUE if success, otherwise FALSE.

 

COM API for "pdfServMachine.Pdf"

 

open

Opens a PDF file ready for manipulation. 

BOOL open(BSTR fileName)

Parameters

BSTR fileName

The full path of the PDF file to be opened.

Returns

TRUE if success, otherwise FALSE.

 

saveAs

Creates a PDF file containing the result of the PDF manipulation. 

BOOL saveAs(BSTR fileName)

Parameters

BSTR fileName

The full path of the PDF file to be written to.

Returns

TRUE if success, otherwise FALSE.

 

append

Opens the PDF file 'fileName' and appends the contents to our internal representation.

BOOL append(BSTR fileName)

Parameters

BSTR fileName

The full path of the PDF file that will be read in.

Returns

TRUE if success, otherwise FALSE.

 

deletePage

Deletes a page.

BOOL deletePage(int pageNum)

Parameters

int pageNum

The number of the page to be deleted.

Returns

TRUE if success, otherwise FALSE.

 

getNumPages

Deletes a page.

int getNumPages()

Returns

The number of pages.

 

setStationery

Applies stationery.  The first page of the 'stationeryFile' is drawn on each page specified.

BOOL setStationery(BSTR stationeryFile, 
	int startPage, int endPage, BOOL ontop)

Parameters

BSTR stationeryFile

The path of the file to be read in and used as stationery.

int startPage

The first page to have stationery applied.

int endPage

The last page to have stationery applied is endPage -1. If endPage is -1, then all pages will have stationery applied.

BOOL ontop

If TRUE, the stationery is drawn after the existing page has been drawn, otherwise it is drawn first.

Returns

TRUE if success, otherwise FALSE.

 

applyNup

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)

Parameters

BSTR pageSize

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.
 

int numPagesOnEachPage

Either 1, 2, 4 or 8.

int margin

The size of the margin between pages, measured in points.

int borderThickness

The size of the border drawn around each page measured in points. -1 means no border, 0 means as thin as possible.

Returns

TRUE if success, otherwise FALSE.

 

getErrorMessage

Applies N-Up processing, where 2, 4 or 8 pages are shrunk and drawn on the one page.

BSTR getErrorMessage()

Returns

A description of what went wrong. This is set if any of the functions return FALSE.

 

 

saveWithSecurity

Saves a PDF file with PDF standard security and encryption.

BOOL saveWithSecurity(BSTR fileName, BSTR userPass, BSTR ownerPass, 
	int flags, int keysizeInBits)


Parameters

BSTR fileName

The full path of the PDF file to be written to.

BSTR userPass

The password for opening the PDF file.  May be empty.
 

BSTR ownerPass

The password for changing permissions in the PDF file. .
 

int flags

Flags as returned by makeEncryptFlags128() or makeEncryptFlags40().

int keysizeInBits

The key size. The values of 40 or 128 are allowed.

Returns

TRUE if success, otherwise FALSE.

 

makeEncryptFlags40

Creates 40 bit encryption flags for use by saveWithSecurity().

int makeEncryptFlags40(BOOL print, BOOL change, 
	BOOL copy, BOOL addnotes)

Parameters

BOOL print

If true, printing will be allowed.

BOOL change

If true, changing of the document will be allowed.

BOOL copy

If true, copying will be allowed.

BOOL addnotes

If true, annotations will be allowed.

Returns

The flags to be passed to saveWithSecurity().

 

makeEncryptFlags128

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)

Parameters

BOOL print

If true, printing will be allowed.

BOOL change

If true, changing of the document will be allowed.

BOOL copyAndExtract

If true, copying and extraction will be allowed.

BOOL addnotes

If true, annotations will be allowed.

BOOL formFillOrSign

If true, filling our of forms and document signing will be allowed.

BOOL extractAccessibility

If true, extraction for accessibility purposes is allowed.

BOOL assemble

If true, document assembly is allowed.

BOOL hiResPrint

If true, hi-res printing is allowed.

Returns

The flags to be passed to saveWithSecurity().

 

 

 

setDocInfo

Sets document information properties.

BOOL setDocInfo(BSTR name, BSTR value)

Parameters

BSTR name

The name of the value to be set.  Allowed values are: Author, Title, Subject, Keywords.

BSTR value

If corresponding value.

Returns

TRUE  if success.

 

 

addPage

Adds a blank new page to the current PDF document.

BOOL addPage(long width, long height)

Parameters

long width

The width of the page in points.

long height

The height of the page in points.

Returns

TRUE  if success.

 

 

addSignature

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) 

Parameters
 

bool isVisible

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.

BSTR storeName

Optional. The name of the Windows certificate store.  Defaults to "My".

BSTR certName

The common name of the certificate.  If the certificate is issued to a person, it is usually the persons name.

BSTR issuerName

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.

BSTR serialNum

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.

BSTR keyBlob

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.

BSTR location

Optional.  The location string in the signature.  e.g. "City of Melbourne".

BSTR reason

Optional.   The reason string in the signature.  e.g. "I agree".

BSTR imageFile

Optional.  The full path of an image file that will appear in the signature.  JPEG, BMP and GIF files can be used.

long  textDisplayFlags

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

long  pageNum

The page to place the signature on.  1 is the first page, -1 means the last page.

BSTR  anchorPosition

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.
 

long  X

Used to combination with "anchorPosition" to set the X coordinate.  Units are in points.

long  Y

Used to combination with "anchorPosition" to set the Y coordinate. Units are in points.

long  width

The signature width. Units are in points.

long  height

The signature height. Units are in points.

 

Returns

TRUE  if success.

 

 

exportKeysByCertificateName

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)

Parameters

BSTR certName

The certificate name.

Returns

Unencrypted hexencoded key string to be used in the "keyBlob" parameter of addSignature.

 

createSelfSignedCertificate

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)

Parameters

BSTR certName

The certificate name.

BSTR orgUnit

Optional. The organizational unit.

BSTR orgName

Optional. The organizational name.

BSTR email

Optional. The email address.

BSTR localeName

Optional. The locale.

BSTR stateName

Optional. The state.

BSTR countryCode

Optional. The 2 char country code.

Returns

TRUE if success.

 

Release History

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.

pdfservmachine