Friday, August 3, 2012

Print document using PDFCreator with C#.NET

Sometime it is required to Generate PDF on the fly using c#.
There are lots of Printer Drivers using which you do you task.

I was in a situation where i have to generate PDF Invoice using EXCEL VSTO. I used PDFCreator to do my job.

I will show you how to print an active Excel Sheet using PDFCreator with C#.NET

First of all Install PDFCreator When i was writing this Post it, the latest version was 1.4.3

Create a windows application and Add reference to Microsoft Excel Object and COM reference to PDFCreator

Add Assembly deceleration for PDFCreator

using PDFCreator;

//Global Deceleration
clsPDFCreator _pdfcreator = null;
string parameters = "/NoProcessingAtStartup";

On form Load Method add following Code

_pdfcreator = new clsPDFCreator();
_pdfcreator.eReady += new __clsPDFCreator_eReadyEventHandler(_pdfcreator_eReady);
_pdfcreator.eError += new __clsPDFCreator_eErrorEventHandler(_pdfcreator_eError);


void _pdfcreator_eError()
{
MessageBox.Show("Error " + _pdfcreator.cError.Description);
}

void _pdfcreator_eReady()
{
//Returns path for generated PDF File
string CreatedFile = _pdfcreator.cOutputFilename;
}

private void printSheet(Excel.Worksheet xlSheet)
{
try
{
if (!_pdfcreator.cStart(parameters, false))
MessageBox.Show("Unable to start default print \"PDFCreator\"", "Print Sheet", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
// Set parameters for saving the generating pdf automatically to a directory.
clsPDFCreatorOptions opt = _pdfcreator.cOptions;
opt.UseAutosave = 1;// Use auto save functionality.
opt.UseAutosaveDirectory = 1;// Use directory for saving the file.

opt.AutosaveDirectory = @"C:\PDFFile"; // Name of the output directory.
opt.AutosaveFormat = 0;// Format of file is to be saved. 0 if for pdf.
opt.AutosaveFilename = "Test.pdf";// Name of the output file name.

opt.Papersize = "Letter";

_pdfcreator.cOptions = opt;
_pdfcreator.cClearCache();

_pdfcreator.cDefaultPrinter = "PDFCreator";
string defaultPrinter = _pdfcreator.cDefaultPrinter;

Excel.Application app = Globals.ThisAddIn.Application;

xlSheet.PrintOutEx(Type.Missing, Type.Missing, Type.Missing, Type.Missing, "PDFCreator", Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// Wait till doc gets queued up.
while (_pdfcreator.cCountOfPrintjobs != 1) ;

// Start the printer.
_pdfcreator.cPrinterStop = false;

// Wait till all doc get converted to pdf.
while (_pdfcreator.cCountOfPrintjobs != 0) ;

// Stop the printer.
_pdfcreator.cPrinterStop = true;

}
}
catch (Exception exec)
{
MessageBox.Show(exec.Message, "Print Sheet", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
// Close the printer
_pdfcreator.cClose();
// _pdfcreator = null;
}
}

Hope this will help some one.

Thank you.