printing pdf without spawning adobe reader? - c#

Presently I'm using the following lines of c# code to automatically print a pdf file to a mobile printer:
string defFile = (Path.Combine(System.Windows.Forms.Application.StartupPath, tkt_no + "_DEF.pdf"));
string rwPrinter = "";
if (GlobalVars.useDefaultPrinter == false)
{
foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
if (strPrinter.StartsWith("ZDesigner"))
{
rwPrinter = strPrinter;
break;
}
}
}
if (jobdo.Equals("print"))
{
Process process = new Process();
process.StartInfo.FileName = defFile;
if (rwPrinter.Length > 0)
{
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + rwPrinter + "\"";
}
else
{
process.StartInfo.Verb = "print";
}
process.Start();
process.WaitForInputIdle();
Thread.Sleep(10000);
process.Kill();
These above lines are good if the application is on a workstation desktop, but the problem I am having is when it actually prints the pdf file from a Citrix App shortcut, it spawns Adobe Reader (the default for pdf) and doesn't close when print job is done.
So my question is, is there any way to print a pdf document without opening Adobe or similar? Perhaps in the iTextSharp library which I'm using in the same application to populate fields?

Related

Show the output of Powershell script in a WPF application

I have a WPF application that executes a Powershell script and then displays a message in a textbox in the application. The Powershell script is executed like this:
string scriptPath = folderPath + "/EXECUTE.ps1";
string powershellPath = #"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
string outputLog = folderPath + "output.log";
bool is64 = IntPtr.Size == 8;
var ENV = "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* "
+ (is64 ? ",HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*" : "")
+ " | Select-Object DisplayName";
ProcessStartInfo startInstall = new ProcessStartInfo(powershellPath, ENV);
startInstall.UseShellExecute = false;
startInstall.Arguments = scriptPath;
startInstall.EnvironmentVariables.Add("RedirectStandardOutput", "true");
startInstall.EnvironmentVariables.Add("RedirectStandardError", "true");
startInstall.EnvironmentVariables.Add("UseShellExecute", "false");
startInstall.EnvironmentVariables.Add("CreateNoWindow", "true");
Process Install = Process.Start(startInstall);
Install.Close();
Console.WriteLine("Script executed successfully");
Console.WriteLine("Output available at: " + outputLog);
The last two lines in Console.WriteLine are printed out in a textbox. I was wondering, is there a way that I can show the output of the Powershell terminal window inside of this textbox named txtboxExecutionResult? I am not executing any Powershell command from my application, just starting and executing the EXECUTE.ps1 file from the application. I'd really appreciate any help to point me in some direction.
I had a similar issue once with reading output from another application and I solved it by reading the standard output of the process.
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.FileName = "example.exe";
process.StartInfo.Arguments = args;
process.Start();
output = await process.StandardOutput.ReadToEndAsync();

C# Process.Start() not starting despite file existing and setting working directory

Question update
I'm trying to use a C# script in Unity to call a python program. After following these two links:
How do I run a Python script from C#?
Process.Start() not starting the .exe file (works when run manually)
I could not get my C# script to call the python program. I know this isn't a problem with my python script because I can run the program in terminal without a problem.
public class JsonStream : MonoBehaviour
{
private string GetStream()
{
ProcessStartInfo start = new ProcessStartInfo();
//none of the paths work, the uncommented variables return true when using File.Exists
//while the commented variables return false
start.FileName = "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3";
//start.FileName = "\"/Library/Frameworks/Python.framework/Versions/3.6/bin/python3\"";
start.Arguments = Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch/stream.py";
//start.Arguments = "\"" + Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch/stream.py" + "\"";
start.WorkingDirectory = Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch";
//start.WorkingDirectory = "\"" + Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch" + "\"";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.ErrorDialog = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
return result;
}
}
}
public void DoEverythingStream()
{
UnityEngine.Debug.Log("Doing Stream");
string json_text = GetStream();
string[] games = json_text.Trim().Split('\n');
foreach (string game in games)
{
UnityEngine.Debug.Log(game);
}
}
}
Running the program raises no errors but also doesn't output anything. Does anyone have any ideas what may be wrong with my program? Thanks!
Old question, but I was struggling to figure out why C# (Unity) wasn't running my Python file even though a manual command prompt could.
By putting my python script's path in triple double quotes ("""), C# was able to run the script.
Example:
string fileName = #"""PATH\TO\YOUR\SCRIPT.PY""";
string pythonPath = #"PATH\TO\PYTHON.EXE";
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo(pythonPath, fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();

c# generate thumbnails from raw images

I have an Asp.net Web forms application,when upload raw image file with format
{ "cr2", "raw", "dng", "nef", "raf", "orf", "srf", "sr2", "arw", "k25", "kdc", "dcr","mos",
"pnx", "crw", "mrw", "pef" , "mef" , "rw2","a7","a7r"}
How can i generate thumbnails from raw image?
You can use dcraw.exe application run on your .net application.you can download it in the link.
First save raw image in local disk and use the code:
string dcrawPath = "dcraw.exe";
ProcessStartInfo startInfo = new ProcessStartInfo();
string inputImagePath= "input Raw Image Path/";
string outputImagePath = "output Raw Image Path/";
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = dcrawPath;
string commandArg1 = string.Format("\"{0}\"", outputImagePath);
string commandArg2 = string.Format("\"{0}\"", inputImagePath);
startInfo.Arguments = "-u ";
startInfo.Arguments += commandArg1;
startInfo.Arguments += " -e ";
startInfo.Arguments += commandArg2;
startInfo.Arguments += " -T";
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
string stdout = exeProcess.StandardOutput.ReadToEnd();
string stderr = exeProcess.StandardError.ReadToEnd();
Console.WriteLine("Exit code : {0}", exeProcess.ExitCode);
}
Put raw image in inputImagePath variable
You can find image in outputImagePath variable
Try GDPicture.NET component. It supports different RAW formats and easy for use, but is not free. To generate thumbnail use CreateThumbnail or CreateThumbnailHQ method of GdPictureImaging class:
using (var imaging = new GdPictureImaging())
{
int pictureId = imaging.CreateGdPictureImageFromFile(filepath);
if (pictureId == 0)
{
MessageBox.Show("Error: " + imaging.GetStat().ToString());
return;
}
int thumbnailImgId = imaging.CreateThumbnail(pictureId, 20, 20);
imaging.SaveAsPNG(thumbnailImgId, "thumbnail.png");
imaging.ReleaseGdPictureImage(thumbnailImgId);
imaging.ReleaseGdPictureImage(pictureId);
}

Output not proper when calling batch file programatically

I was trying to automate server patch installation for my product and I came to know about Wix Toolset.
I was hoping to get the JBoss Version in my installer. The command to get the same is standalone.bat --version from cmd.
So from my installer I created one CustomAction where I tried to run it and get the output.
public static string runRunnableBatch(string path){
Process exploitVersionService = new Process();
string runnableBinPath = path;
exploitVersionService.StartInfo.WorkingDirectory = path + "bin";
exploitVersionService.StartInfo.FileName = path + "bin\\standalone.bat";
exploitVersionService.StartInfo.CreateNoWindow = false;
exploitVersionService.StartInfo.Arguments = string.Format("--version");
exploitVersionService.StartInfo.UseShellExecute = false;
exploitVersionService.StartInfo.RedirectStandardOutput = true;
exploitVersionService.StartInfo.RedirectStandardInput = false;
exploitVersionService.Start();
exploitVersionService.WaitForExit();
// /*
string opt = "";
while (!exploitVersionService.StandardOutput.EndOfStream){
opt += exploitVersionService.StandardOutput.ReadLine();
}
// */
//using (StreamWriter writer = new StreamWriter("D:\\_log.txt"))
//using (StreamReader reader = exploitVersionService.StandardOutput){
// writer.AutoFlush = true;
// for (; ; ){
// string textLine = reader.ReadLine();
// if (textLine == null)
// break;
// writer.WriteLine(textLine);
// }
//}
//StreamReader exploitVersionFeed = exploitVersionService.StandardOutput;
//string output = exploitVersionFeed.ReadToEnd();
return opt;
}
When I was doing that, all I got as output was the first line of the whole output string.
I needed the whole string in my code so that from regular expression I could extract the version.
Also tried with
public static string runRunnableBatch(string path){
string executableBinPath = path + "bin";
string executableBinPath_BatchCmd = "cd " + "\"" + executableBinPath + "\"";
string outputFileName = "TempVerInfoHolder.txt";
string outputFilePath = executableBinPath+#"\TempVerInfoHolder1.txt";
string versionRetriever_BatchCmd = #"standalone.bat --version > " + "\""+outputFilePath+"\"";
string partitionName_BatchCmd = #Strings.Utils.getPartitionFromPath(path);
// Creating command sequence
SortedList<int, string> commandSequence = new SortedList<int, string>();
// ~ d:
commandSequence.Add(1, partitionName_BatchCmd);
// ~ cd %path%
commandSequence.Add(2, executableBinPath_BatchCmd);
// ~ standalone.bat --version > %filename%
commandSequence.Add(3, versionRetriever_BatchCmd);
runCommandFromSequence(commandSequence);
// Run together
return "";
}
private static void runCommandFromSequence(SortedList<int, string> commandSequence){
Process seqCmdExecHost = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = false;
seqCmdExecHost.StartInfo = psi;
seqCmdExecHost.Start();
using (StreamWriter writer = seqCmdExecHost.StandardInput) {
if (writer.BaseStream.CanWrite) {
foreach (int item in commandSequence.Keys){
MessageBox.Show(seqCmdExecHost.Id.ToString());
MessageBox.Show(commandSequence[item]);
writer.WriteLine(commandSequence[item]);
}
}
string opt = "";
while (!seqCmdExecHost.StandardOutput.EndOfStream){
opt += seqCmdExecHost.StandardOutput.ReadLine();
}
MessageBox.Show("Exited? " + seqCmdExecHost.HasExited);
MessageBox.Show("O/P? " + opt);
}
}
I have tried some other way as well. Switching the commented code of the above function was one of them.
Output getting while doing it from code level
Calling "D:\Servers\VA\XYZ\JBoss-7.1.1-Final\bin\standalone.conf.bat
Output while running the same command manually from cmd
Calling D:\Servers\VA\XYZ\JBoss-7.1.1-Final\bin\standalone.conf.bat
======================================================================
JBoss Bootstrap Environment
JBOSS_HOME: D:\Servers\VA\XYZ\JBoss-7.1.1-Final
JAVA: C:\Program Files\Java\jdk1.7.0_67\bin\java
JAVA_OPTS
======================================================================
Listening for transport dt_socket at address: 8787
19:08:08,333 INFO [org.jboss.modules] JBoss Modules version 1.1.1.GA
JBoss AS 7.1.1.Final "Brontes"
Press any key to continue . . .
My observation is, the stream is getting closed once the nested standalone.conf.bat is getting called from standalone.bat.
If any workaround available to get the full output in string/buffer/stream, would be appreciated.
Thanks
What you could do is call the Command line Application instead of calling the batch file
exploitVersionService.StartInfo.WorkingDirectory = path + "bin";
exploitVersionService.StartInfo.FileName = "cmd.exe";
exploitVersionService.StartInfo.CreateNoWindow = false;
exploitVersionService.StartInfo.Arguments = string.Format(" /c \"{0}\" --version",path + "bin\\standalone.bat");
I found one work around to do achieve this.
I created the batch file programmatically and ran it with cmd.
public static void createBatchToGetVersion(string path)
{
CustomLogger.getInstance().debug("Started creating batch file");
BatchOps.executableBinPath = path + "bin";
CustomLogger.getInstance().debug("Ëxecutable bin path: " + BatchOps.executableBinPath);
BatchOps.tempBatchFileName = "JBossVerCmd.bat";
BatchOps.holderFileName = #"JBossVerHolder.txt";
BatchOps.absoluteHolderPath = Strings.Utils.normalize(executableBinPath) + holderFileName;
CustomLogger.getInstance().debug("Normalized absoluteHolderPath: " + BatchOps.absoluteHolderPath);
CustomLogger.getInstance().debug("Checking if JBOSS_HOME entered by user actuallty points to JBOSS");
if (!File.Exists(Strings.Utils.normalize(executableBinPath) + "standalone.bat"))
{
CustomLogger.getInstance().error("standalone.bat not found. JBOSS_HOME Dir is not correctly entered");
throw new CustomExceptions.DirectoryNotAcceptableException("Bad directory is assigned to JBOSS_HOME or JBOSS_HOME structure corrupted");
}
/*
* Batch file formation.
* Contains:
* Start file
* D:
* cd D:\Fusion Server\jboss 7.1.1\bin
* #echo | call standalone.bat --version > sample.txt
* #echo Done
* End file
* #echo is required here because it exits the cmd when completed whithout having the user pressing any key
*/
string changePartition_cmd = Strings.Utils.getPartitionFromPath(path);
string changeDirectory_cmd = #"cd " + BatchOps.executableBinPath;
string getVersion_cmd = #"#echo | call standalone.bat --version > " + holderFileName;
string exitCmd = #"#echo Done";
CustomLogger.getInstance().debug("Command to be written on batch file");
CustomLogger.getInstance().debug("\r\n" + changePartition_cmd + "\r\n" + changeDirectory_cmd + "\r\n" + getVersion_cmd + "\r\n" + exitCmd);
SortedList<int, string> commandSequence = new SortedList<int, string>();
CustomLogger.getInstance().debug("Initializing command sequence.");
commandSequence.Add(1, changePartition_cmd);
commandSequence.Add(2, changeDirectory_cmd);
commandSequence.Add(3, getVersion_cmd);
commandSequence.Add(4, exitCmd);
// Will create one if file never existed and open one delete the content and set the pointer to the begnning
// if already existed
StreamWriter batchFileWriter = null;
try
{
CustomLogger.getInstance().debug("Establishing stream to and from temp batch file");
batchFileWriter = new StreamWriter(tempBatchFileName);
CustomLogger.getInstance().debug("Command sequence ready to be written on temp batch file.");
Perform.writeToStreamFromSequence(batchFileWriter, commandSequence);
CustomLogger.getInstance().debug("Command sequence successfully written");
}
catch (IOException ex)
{
CustomLogger.getInstance().error("Error while writing command sequence.\n" + ex.ToString());
// throw exception to CustomAction
throw new IOException("Error while writing commandSequence");
}
finally
{
// Not required. Stream already closed in writeToStreamFromSequence
}
}
public static void runTempBatchFile()
{
Process seqCmdExecHost = new Process();
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", #"/c " + BatchOps.tempBatchFileName);
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
seqCmdExecHost.StartInfo = procStartInfo;
seqCmdExecHost.Start();
seqCmdExecHost.WaitForExit();
seqCmdExecHost.Close();
}
I found the moment i was doing
procStartInfo.UseShellExecute=true;
procStartInfo.RedirectStandardOutput=true
It was giving the first line of output. Dont know why?. If anyone has any idea about it please explain.
Thanks

html or pdf printing on server side c#

I know its a known topic in many forums and blogs. I read many articles. And many of them are quiet informative. But for me it seems like it demands new approach to achieve this task.
Am looking for a solution to print a html on server side. But after working with many options i realised that we
cant give printer name or
its printing html raw content like a txt file
Later came to know about ghostscript (https://stackoverflow.com/a/2600189/1238159) can be used to print a PDF on server side silently.
Also tried with crystal report (but how to pass HTML content to it dynamically eventhough it wont support many tags), itextsharp, ssrs, pdfsharp etc etc but none of them were supporting many of the HTMl tags & W3C standards. So i ended at one point to generate PDF. Only wkhtmltopdf is perfect for converting html to pdf. it supports every html tag unlike anyother as of my experience. but printing PDf is the question for me from many years.
But now am facing a problem even with GhostScript (am using ver 9.05). With localhost i can use it perfectly. i can print on server side to what ever printer name coming from UI silently. but with the IP address or machine name its not working. i even implemented Impersonation. Even though the process gets hanged while calling GhostScript.
Now what i want to get clear is
Is it possible to print a html or pdf (actual content) on server side?
Any open source tools are there to achieve this
printer name I would like to pass dynamically
Any clue or workaround might help many hours of people around the globe. :)
Many thanks in advance.
Regards,
Pavan N
After using the suggestion by Lau. am able to do it in command prompt (means cmd.exe runs under my account). but my application will run under network service.
Now am getting a problem just a kind of this ACCESS Denied
Yeah. Finally i was able to start the process. and am able to see my gswin32c.exe process under task manager with my domain credentials. code is as follows:
public bool PrintVSPDF(string ghostScriptPath, int numberOfCopies, string printerName, string pdfFileName)
{
Logger.AddToLog("printerName", printerName);
string impersonationUsername = "";
string impersonationDomain = "";
string impersonationPWD = "";
if (ConfigurationManager.AppSettings["UName"] != null)
{
impersonationUsername = Encryption.Decrypt(ConfigurationManager.AppSettings["UName"].ToString(), Encryption.DEFAULT_KEY, Encryption.DEFAULT_SEED);
impersonationDomain = impersonationUsername.Split('\\').Count() > 1 ? impersonationUsername.Split('\\')[0] : "";
impersonationUsername = impersonationUsername.Split('\\').Count() > 1 ? impersonationUsername.Split('\\')[1] : impersonationUsername.Split('\\')[0];
}
if (ConfigurationManager.AppSettings["PD"] != null)
{
impersonationPWD = Encryption.Decrypt(ConfigurationManager.AppSettings["PD"].ToString(), Encryption.DEFAULT_KEY, Encryption.DEFAULT_SEED);
}
using (Impersonation imp = new Impersonation(impersonationUsername, impersonationDomain, impersonationPWD))
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = "-dPrinted -dNoCancel -dNOPAUSE -dBATCH -dNumCopies=" + Convert.ToString(numberOfCopies) + " -sDEVICE=mswinpr2 -sOutputFile=%printer%\"" + printerName + "\" \"" + pdfFileName + "\" ";
startInfo.FileName = ghostScriptPath;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
//startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UserName = impersonationUsername;
startInfo.Domain = impersonationDomain;
SecureString ss = new SecureString();
for (int i = 0; i < impersonationPWD.Length; i++)
{
ss.AppendChar(impersonationPWD[i]);
}
startInfo.Password = ss;
Process process = null;
try
{
process = Process.Start(startInfo);
//Logger.AddToLog("Error VS", process.StandardError.ReadToEnd());
//Logger.AddToLog("Output VS", process.StandardOutput.ReadToEnd());
//Logger.AddToLog(process.StartInfo.Arguments.ToString(), "VS Print Arguments");
//Console.WriteLine(process.StandardError.ReadToEnd() + process.StandardOutput.ReadToEnd());
//Logger.AddToLog(process.StartInfo.FileName.ToString(), "VS Print file name");
process.WaitForExit(30000);
if (process.HasExited == false)
process.Kill();
int exitcode = process.ExitCode;
process.Close();
return exitcode == 0;
}
catch (Exception ex)
{
Logger.AddToLog(ex);
return false;
}
}
}
But the process is working perfectly in localhost:5030 ie., while running from my visual studio. but with IP address or machine name. it just hangs and throws this error
Same thing is happening for adobe reader, foxit, etc etc.
( Process must exit before requested information can be determined. : at System.Diagnostics.Process.EnsureState(State state)
at System.Diagnostics.Process.get_ExitCode() )
I have been working on a project that is doing just this. It has been a very frustrating experience. The most reliable method I have found is to export my reports to PDF and then use Foxit Reader (NOT Adobe Reader due to security problems) via Diagnostics.Process to print the document.
The printer name can be supplied to the Foxit Reader command line args.
The environment I am working with is ASP.net 3.5 on IIS 7 on Windows Server 2008 R2 x64.
I am also using Sql Server Reporting Services.
Maybe this code will help you out:
public FileContentResult GetPOReport(DataTable reportData, int poNumber, string copies, out string fileName, out string downloadPath)
{
fileName = "PO_" + poNumber.ToString().Trim() + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".pdf";
downloadPath = "/Generated/" + fileName;
var outputFiles = new Dictionary<string, string>
{
{"", Server.MapPath("~" + downloadPath)}
};
if (!string.IsNullOrWhiteSpace(copies))
{
var copyList = copies.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var temp in copyList)
outputFiles.Add(temp, Server.MapPath("~" + "/Generated/" + temp.Trim() + ".pdf"));
}
FileContentResult returnFile = null;
foreach (var outputFile in outputFiles)
{
var file = WriteReportToDisk(reportData, outputFile.Value, outputFile.Key);
if (file == null)
continue;
if (string.IsNullOrWhiteSpace(outputFile.Key))
returnFile = file;
else
PrintReport(outputFile.Value);
}
return returnFile;
}
public void PrintReport(string filePath)
{
try
{
if (!ConfigurationManager.AppSettings.AllKeys.Contains("AdobeReaderPath") ||
!ConfigurationManager.AppSettings.AllKeys.Contains("AdobePrintParameters") ||
!ConfigurationManager.AppSettings.AllKeys.Contains("PrinterName"))
return;
var adobeReaderPath = ConfigurationManager.AppSettings["AdobeReaderPath"].Trim();
var adobePrintParameters = ConfigurationManager.AppSettings["AdobePrintParameters"].Trim();
var printerName = ConfigurationManager.AppSettings["PrinterName"].Trim();
var printProcessDomain = ConfigurationManager.AppSettings["PrintProcessDomain"].Trim();
var printProcessUserName = ConfigurationManager.AppSettings["PrintProcessUserName"].Trim();
var printProcessPassword = ConfigurationManager.AppSettings["PrintProcessPassword"].Trim();
var userPrinter = Entities.UserPrinters.FirstOrDefault(p => p.UserName == User.Identity.Name);
if (userPrinter != null)
printerName = userPrinter.PrinterName.Trim();
using (var process = new Process
{
StartInfo =
new ProcessStartInfo(
adobeReaderPath,
string.Format(adobePrintParameters, filePath, printerName)
)
})
{
if (!string.IsNullOrWhiteSpace(printProcessUserName))
{
if (!string.IsNullOrWhiteSpace(printProcessDomain))
process.StartInfo.Domain = printProcessDomain;
process.StartInfo.UserName = printProcessUserName;
var securePassword = new SecureString();
foreach (var passwordCharacter in printProcessPassword)
securePassword.AppendChar(passwordCharacter);
process.StartInfo.Password = securePassword;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.LoadUserProfile = true;
}
process.Start();
process.WaitForExit(30000);
}
}
catch (Exception exception)
{
EventLog.WriteEntry("PO Suggestion Viewer", string.Format("PO Suggestion Viewer Error:\n{0}", exception.Message));
throw;
}
}
public FileContentResult WriteReportToDisk(DataTable reportData, string filePath, string copy)
{
var webReport = new WebReport()
{
ExportFileName = "PO Report",
ReportPath = Server.MapPath("~/Reports/PurchaseOrderReport.rdlc")
};
if (!string.IsNullOrWhiteSpace(copy))
webReport.ReportParameters.Add(new ReportParameter("Copy", copy));
if ((User != null) && (User.Identity != null) && (User.Identity.Name != null))
webReport.ReportParameters.Add(new ReportParameter("User", User.Identity.Name));
webReport.ReportDataSources.Add(new ReportDataSource("ReportData", reportData));
var report = webReport.GetReport();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.{1}", webReport.ExportFileName, webReport.FileNameExtension));
Response.ContentType = "application/pdf";
var file = File(report, webReport.MimeType, "POReport");
System.IO.File.WriteAllBytes(filePath, file.FileContents);
return file;
}
My web.config contains:
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="AdobeReaderPath" value="C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Re-ader.exe" />
<add key="AdobePrintParameters" value="-t "{0}" "{1}"" />
<add key="PrinterName" value="HP_Office" />
<add key="PrintProcessDomain" value="DOMAIN_NAME" />
<add key="PrintProcessUserName" value="DOMAIN_USER" />
<add key="PrintProcessPassword" value="DOMAIN_PASSWORD" />
</appSettings>
sorry for the late posting. i taught i already answered this Q.
I found a work around to convert html to pdf.
am using WKHTMLTOPDF API to convert the html to pdf. and it looks awesome compared to many commercial products out there. am able to get coloured/greyscale, margins, indexing. and many more.
here is the link i followed
http://code.google.com/p/wkhtmltopdf/
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + #"\bin\wkhtmltopdf.exe";
pdfFile = localReportPath + "\\Reports\\Savedfiles\\" + filename + ".pdf";
//Ref: http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html
startInfo.Arguments = " --minimum-font-size 16 --margin-left 10mm --margin-right 10mm --zoom 3 " + htmlFile + " " + pdfFile;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process p = Process.Start(startInfo);
p.WaitForExit();
p.Dispose();
p.Close();
and the same i sent for ghostscript to get an beautiful TIFF file for faxing. performance is good with huge data also.
Regards,
Pavan N

Categories

Resources