This tutorial shows how to create and set up a LEADTOOLS Virtual Printer so users can print to it and save it as a PDF file.
Overview | |
---|---|
Summary | This tutorial covers how to install a printer and catch print jobs in a C# Console application. |
Completion Time | 30 minutes |
Visual Studio Project | Download tutorial project (3 KB) |
Platform | Windows C# Console Application |
IDE | Visual Studio 2017, 2019 |
Development License | Download LEADTOOLS |
Before working on the Print to File Using the Virtual Printer Driver - Console C# tutorial, get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial.
This tutorial also requires the Leadtools.Printer.dll, which is only installed in the SDK by request during installation. Be sure to request both the Win32 and x64 DLL architecture versions (if both are needed) during installation, when prompted.
Creating a new LEADTOOLS Printer Driver and adding it to the machine requires that Visual Studio be run under elevated administrator permissions.
In Visual Studio, create a new C# Windows Console project, and add the below necessary LEADTOOLS references.
The references needed depend upon the purpose of the project. For this project, add the below DLLs located at <INSTALL_DIR>\LEADTOOLS21\Bin\Dotnet4\x64
:
Leadtools.Printer.dll
Leadtools.Codecs.dll
Leadtools.dll
Leadtools.Pdf.dll
Leadtools.Document.Writer.dll
The System.Drawing assembly from .NET is also needed. To add it, right-click on the References in the Solution Explorer, and then Add reference. Under Assemblies, find and select System.Drawing
.
For a complete list of which Codec DLLs are required for specific formats, refer to File Format Support.
The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.
There are two types of runtime licenses:
Note
Adding LEADTOOLS NuGet and local references and setting a license are covered in more detail in the Add References and Set a License tutorial.
Now that the LEADTOOLS references have been added to the project, coding can begin.
Start by adding the relevant code to create the Printer driver.
At the top of the Program.cs
place the following LEADTOOLS using statements
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using Leadtools;
using Leadtools.Document.Writer;
using Leadtools.Printer;
Instantiate the following global variables inside of the Program
Class:
static Printer LeadPrinter;
static DocumentWriter DocumentWriter;
static PrinterInfo PrinterInfo;
static string OutputFile;
Add the SetLicense()
code from the Add References and Set a License tutorial in the Main(string[] args)
method.
Next, add the SetupPrinter()
method to initialize and install the virtual printer:
static void Main(string[] args)
{
SetLicense();
SetupPrinter();
Console.WriteLine("Printer set up and ready to receive jobs. Print to the LEADTOOLS Printer to see it working. Press enter to exit.");
Console.ReadLine();
Printer.UnInstall(PrinterInfo);
}
static void SetLicense()
{
string license = @"C:\LEADTOOLS21\Support\Common\License\LEADTOOLS.LIC";
string key = File.ReadAllText(@"C:\LEADTOOLS21\Support\Common\License\LEADTOOLS.LIC.KEY");
RasterSupport.SetLicense(license, key);
if (RasterSupport.KernelExpired)
Console.WriteLine("License file invalid or expired.");
else
Console.WriteLine("License file set successfully");
}
static void SetupPrinter()
{
List<string> installedPrinters = new List<string>();
foreach (string printer in PrinterSettings.InstalledPrinters)
installedPrinters.Add(printer);
string printerName = "LEADTOOLS Printer";
string printerPassword = "";
string documentPrinterRegPath = @"SOFTWARE\LEAD Technologies, Inc.\21\Printer\";
PrinterInfo = new PrinterInfo
{
MonitorName = printerName,
PortName = printerName,
ProductName = printerName,
PrinterName = printerName,
Password = printerPassword,
RegistryKey = documentPrinterRegPath + printerName,
RootDir = @"C:\LEADTOOLS21\Bin\Common\PrinterDriver\",
Url = "https://www.leadtools.com",
PrinterExe = AppDomain.CurrentDomain.BaseDirectory
};
if (!installedPrinters.Contains(printerName))
Printer.Install(PrinterInfo);
LeadPrinter = new Printer(printerName);
LeadPrinter.EmfEvent += new EventHandler<EmfEventArgs>(LeadPrinter_EmfEvent);
LeadPrinter.JobEvent += new EventHandler<JobEventArgs>(LeadPrinter_JobEvent);
DocumentWriter = new DocumentWriter();
}
In the previous step, some EventHandler
lines of code were added onto the LeadPrinter
object. Now it is time to add the EmfEvent and JobEvent to the project.
The Emf Event will fire for each page of a print job.
The Job Event will fire twice: the first time when the job begins, and a second time when the job ends.
static void LeadPrinter_EmfEvent(object sender, EmfEventArgs e)
{
Metafile metaFile = new Metafile(e.Stream);
DocumentWriterEmfPage documentPage = new DocumentWriterEmfPage
{
EmfHandle = metaFile.GetHenhmetafile()
};
DocumentWriter.AddPage(documentPage);
}
static void LeadPrinter_JobEvent(object sender, JobEventArgs e)
{
string printerName = e.PrinterName;
int jobID = e.JobID;
if (e.JobEventState == EventState.JobStart)
{
string tempDir = @"C:\Temp";
if (!Directory.Exists(tempDir))
Directory.CreateDirectory(tempDir);
OutputFile = Path.Combine(@"C:\Temp", Path.ChangeExtension(Path.GetRandomFileName(), "pdf"));
DocumentWriter.BeginDocument(OutputFile, DocumentFormat.Pdf);
Console.WriteLine($"Job {jobID} for {printerName} was started");
}
else if (e.JobEventState == EventState.JobEnd)
{
DocumentWriter.EndDocument();
Console.WriteLine($"Job {jobID} for {printerName} was ended. PDF saved to {OutputFile}");
}
}
Installing a new Virtual Printer requires Administrator Access. In order to check for access prior to running, add an app.manifest
file to the project by right-clicking on the csproj
, clicking Add > New Item > Application Manifest File (Windows Only) then clicking Add.
The app.manifest
should look like this
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.Print_to_File_Using_the_Virtual_Printer_Driver"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
Note
Create the directory
C:\Temp
in order to use it as a temporary folder. Otherwise, usePath.GetTempPath
to use the %TEMP% folder.
Run the project by pressing F5, or by selecting Debug -> Start Debugging.
Note
At this point, if Visual Studio 2019 is not running with an Administrator's permissions, stop the project and set it to run as an Administrator. Administrator's permissions are necessary so the program can connect to the machine's files to see which Printers are currently installed.
After the program is running, open any program that allows printing. For example, open Notepad and write a short message. Then print to the LEADTOOLS Printer
that has just been installed. After printing to it, a message displays in the console that shows the path to the PDF file that was just printed.
This tutorial showed how to create and install a LEADTOOLS Virtual Printer to print documents as PDF files.