Click here to Skip to main content
12,631,923 members (30,980 online)
Click here to Skip to main content
Add your own
alternative version

Stats

191.9K views
16.1K downloads
93 bookmarked
Posted

Programmatically Convert Documents to PDFs the Easy Way

, 9 Feb 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
An easy way to create PDF documents from code

Background

In my workplace, it is common for people to want documents in PDF format. The problem I was running into was that programming a PDF is no simple task. That, and I already had the documents in another format (Excel). Knowing that there were PDF print drivers, I decided to figure out how they worked. I noticed that almost all of them used Ghostscript, a program to convert PostScript to PDF format. The only problem with these print drivers was that it required user interaction. I couldn't allow this as I have to bulk print about 100 reports a month and having an end user specify where to save a file would just be too cumbersome... and I didn't like the nagging shareware graphics.

After eventually putting two and two together, I discovered that .NET could call GhostScript with the appropriate commands to generate a PDF. But my problem still lay in the fact that I didn't want to create my own printer driver. Enter virtual printers and file ports. In order for this code to work, you must create a virtual printer.

First you will want to download Ghostscript and install it.

Continue by adding a local printer and uncheck "Automatically detect and install my Plug and Play printer".

Create a new local port and enter "C:\output.ps" for the port name.

In order for GhostScript to correctly parse the PostScript, it must be set as the printer driver. You can find the printer driver for GhostScript in the GhostScript installation directory in the lib folder.

For the attached code to work, name the printer Ghostscript.

Using the Code

The attached application puts all the puzzles in place. First the application stores the current default printer. This will be used later to set the printer back.

public static string GetDefaultPrinterName(){
    PrintDocument pd = new PrintDocument();
    return pd.PrinterSettings.PrinterName;
}

Second, the Ghostscript printer that we set up earlier is set as the default so the user doesn't have to select a printer.

public static long SetDefaultPrinterName(string name){
    return SetDefaultPrinter(name);
}

Third, we call the print command on a file. The trick here for me was detecting when an Excel file was printed. I work primarily with Excel documents and needed a quick way to print out the entire workbook and not just the opened worksheet.

public static void CreatePdf(string action, string file, string directory){
    if (file.EndsWith("xls")){
        Excel.ApplicationClass excel = new Excel.ApplicationClass();
        excel.Visible = false;

        Excel.Workbook workbook = excel.Workbooks.Open(Path.Combine(directory, file),
			Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);

        workbook.PrintOut(Type.Missing, Type.Missing, 1, false, Type.Missing, 
			false, Type.Missing, Type.Missing);

        excel.Quit();
    }else{
        Process p = new Process();
                
        p.StartInfo.FileName = file;
        p.StartInfo.Verb = action;
        p.StartInfo.WorkingDirectory = directory;
        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        p.StartInfo.CreateNoWindow = true;
        Console.WriteLine("Starting process");
        p.Start();
        //p.Kill();
    }
    Console.WriteLine("Creating Pdf");
    CreatePdf(file);
}

Finally, we call the GhostScript executable, giving it the filename we want it outputted to and where to find the PostScript. In order to pass the executable a statement, we just redirect the input to a command we create and we also grab the output.

private static string CreatePdf(string fileName){
    string command = "gswin32c -q -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=\"" + 
			fileName + ".pdf\"  -fc:\\output.ps";

    Console.WriteLine(command);
    Process p = new Process();

    StreamWriter sw;
    StreamReader sr;
            
    ProcessStartInfo info = new ProcessStartInfo("cmd");
    info.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
    Console.WriteLine("Current directory: " + info.WorkingDirectory);
    info.CreateNoWindow = true;
    info.UseShellExecute = false;
            
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
            
    p.StartInfo = info;
    p.Start();
            
    sw = p.StandardInput;
    sr = p.StandardOutput;
    sw.AutoFlush = true;
            
    sw.WriteLine(command);
            
    sw.Close();
            
    string ret = sr.ReadToEnd();

    Console.WriteLine(ret);
    return ret;
}

After GhostScript runs, we just set the printer back to the previous default and the user is none the wiser.

try{
    Printers.SetDefaultPrinterName(currentPrinterName);
}catch{}

This application can be used for quick PDF creation, but mostly it is for developers looking for an example of quickly creating PDFs without the hassle of programming in the PDF SDK. When running this application, place the gswin32c executable in the same directory. For further information on optimizing PDFs and doing all sorts of other crazy things, look into the GhostScript documentation and change the parameters specified. Have fun!

Points of Interest

The neat thing about this application is that it requires no extra work for the developer to format the document into a PDF. The way the document appears on the screen in its native application is how it is printed to PDF.

Things to Remember

Make sure to set up a virtual printer. If you modify where the file port goes, make sure to update the code.

Make sure to place the gswin32c in the same directory as the executing application.

It also looks like GhostScript needs to be installed on the machine. Find the 8.54 version here.

History

  • 9th February, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jkandiko
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionGhostscript print dialog appears Pin
Member 1034393317-Oct-13 23:50
memberMember 1034393317-Oct-13 23:50 
QuestionAnyone else get Access Denied setting Port Name? Pin
RoninWarrior2-Jul-13 11:16
memberRoninWarrior2-Jul-13 11:16 
AnswerRe: Anyone else get Access Denied setting Port Name? Pin
Member 102844347-Jan-14 23:31
memberMember 102844347-Jan-14 23:31 
QuestionHelp -- Not working for me Pin
FoxTrotCharlie1-May-13 4:54
memberFoxTrotCharlie1-May-13 4:54 
AnswerRe: Help -- Not working for me Pin
jkandiko1-May-13 5:21
memberjkandiko1-May-13 5:21 
GeneralMy vote of 3 Pin
Wheman Limon14-Feb-13 7:24
memberWheman Limon14-Feb-13 7:24 
QuestionWaste of time Pin
karthikelangoram4-Jan-13 2:14
memberkarthikelangoram4-Jan-13 2:14 
GeneralMy vote of 5 Pin
chandra01shekhar8-Dec-11 21:32
memberchandra01shekhar8-Dec-11 21:32 
QuestionSpecify the PS filename in code? Pin
marc lang21-Dec-10 0:56
membermarc lang21-Dec-10 0:56 
AnswerRe: Specify the PS filename in code? Pin
jkandiko21-Dec-10 4:37
memberjkandiko21-Dec-10 4:37 
Questiongenerates Output.ps file Pin
Lekha_J27-Mar-09 10:25
memberLekha_J27-Mar-09 10:25 
GeneralXLVIEW executes but no PS File generated Pin
Member 304588412-Mar-09 14:38
memberMember 304588412-Mar-09 14:38 
GeneralRe: XLVIEW executes but no PS File generated Pin
jkandiko13-Mar-09 4:29
memberjkandiko13-Mar-09 4:29 
GeneralThanks Pin
thohoff4-Feb-09 3:36
memberthohoff4-Feb-09 3:36 
QuestionHow to pass the arguments to the console application Pin
geetha naidu9-Jul-08 19:27
membergeetha naidu9-Jul-08 19:27 
GeneralURgent: Pdf generation Pin
geetha naidu8-Jul-08 20:20
membergeetha naidu8-Jul-08 20:20 
Questionwhat kind of manufacturer and printer I must chose in step "Install Printer Software" of "Add Printer Wizad"? Pin
taihip22-Nov-07 18:16
membertaihip22-Nov-07 18:16 
AnswerRe: what kind of manufacturer and printer I must chose in step "Install Printer Software" of "Add Printer Wizad"? Pin
jkandiko27-Nov-07 4:52
memberjkandiko27-Nov-07 4:52 
QuestionRe: what kind of manufacturer and printer I must chose in step "Install Printer Software" of "Add Printer Wizad"? Pin
taihip27-Nov-07 15:24
membertaihip27-Nov-07 15:24 
AnswerRe: what kind of manufacturer and printer I must chose in step "Install Printer Software" of "Add Printer Wizad"? Pin
jkandiko28-Nov-07 4:32
memberjkandiko28-Nov-07 4:32 
GeneralRe: what kind of manufacturer and printer I must chose in step "Install Printer Software" of "Add Printer Wizad"? Pin
taihip28-Nov-07 15:27
membertaihip28-Nov-07 15:27 
Questionproblem with the executions the aplication Pin
radkeck24-Sep-07 12:35
memberradkeck24-Sep-07 12:35 
AnswerRe: problem with the executions the aplication Pin
jkandiko4-Sep-07 12:37
memberjkandiko4-Sep-07 12:37 
GeneralRe: problem with the executions the aplication Pin
radkeck24-Sep-07 12:44
memberradkeck24-Sep-07 12:44 
GeneralRe: problem with the executions the aplication Pin
radkeck24-Sep-07 12:45
memberradkeck24-Sep-07 12:45 
GeneralRe: problem with the executions the aplication Pin
jkandiko4-Sep-07 12:47
memberjkandiko4-Sep-07 12:47 
GeneralRe: problem with the executions the aplication Pin
radkeck24-Sep-07 12:55
memberradkeck24-Sep-07 12:55 
GeneralRe: problem with the executions the aplication Pin
radkeck24-Sep-07 22:11
memberradkeck24-Sep-07 22:11 
GeneralRe: problem with the executions the aplication Pin
jkandiko5-Sep-07 4:48
memberjkandiko5-Sep-07 4:48 
GeneralHi, Urgent. I want to save excel sheets as PDF Files Pin
pravin parmar1-Sep-07 8:54
memberpravin parmar1-Sep-07 8:54 
GeneralRe: Hi, Urgent. I want to save excel sheets as PDF Files Pin
jkandiko4-Sep-07 4:36
memberjkandiko4-Sep-07 4:36 
GeneralWord Document Extension Pin
skeynan24-Mar-07 8:19
memberskeynan24-Mar-07 8:19 
GeneralRe: Word Document Extension Pin
jkandiko26-Mar-07 5:30
memberjkandiko26-Mar-07 5:30 
QuestionHow can we give file to be converted Pin
akjal5-Mar-07 19:20
memberakjal5-Mar-07 19:20 
AnswerRe: How can we give file to be converted Pin
jkandiko6-Mar-07 4:37
memberjkandiko6-Mar-07 4:37 
QuestionI could don't create local port. Pin
ReneTrevi19-Feb-07 7:55
memberReneTrevi19-Feb-07 7:55 
GeneralAnother article on PDF Generation Pin
Rajaamirapu18-Feb-07 12:13
memberRajaamirapu18-Feb-07 12:13 
GeneralWorks on user's desktop but... Pin
HoyaSaxa939-Feb-07 8:54
memberHoyaSaxa939-Feb-07 8:54 
QuestionHack and slash maybe? Pin
Arch4ngel9-Feb-07 7:03
memberArch4ngel9-Feb-07 7:03 
AnswerRe: Hack and slash maybe? Pin
Ben Allfree9-Feb-07 7:20
memberBen Allfree9-Feb-07 7:20 
AnswerRe: Hack and slash maybe? Pin
Gabriel Topala9-Feb-07 7:31
memberGabriel Topala9-Feb-07 7:31 
GeneralRe: Hack and slash maybe? Pin
Purplet9-Feb-07 8:11
memberPurplet9-Feb-07 8:11 
GeneralRe: Hack and slash maybe? Pin
David C Elliott9-Feb-07 8:41
memberDavid C Elliott9-Feb-07 8:41 
GeneralRe: Hack and slash maybe? Pin
Ben Allfree9-Feb-07 9:57
memberBen Allfree9-Feb-07 9:57 
GeneralRe: Hack and slash maybe? Pin
Mike Tuersley12-Feb-07 17:42
memberMike Tuersley12-Feb-07 17:42 
GeneralRe: Hack and slash maybe? Pin
saravanackumar16-Feb-07 23:56
membersaravanackumar16-Feb-07 23:56 
AnswerRe: Hack and slash maybe? Pin
Secrets12-Feb-07 22:42
memberSecrets12-Feb-07 22:42 
GeneralRe: Hack and slash maybe? Pin
Ben Allfree13-Feb-07 8:22
memberBen Allfree13-Feb-07 8:22 
GeneralRe: Hack and slash maybe? Pin
jkandiko13-Feb-07 9:18
memberjkandiko13-Feb-07 9:18 
GeneralArticle title suggestion Pin
Ben Allfree9-Feb-07 6:52
memberBen Allfree9-Feb-07 6:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 9 Feb 2007
Article Copyright 2007 by jkandiko
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid