Printing PDF using ReportViewer from C# windows - c#

Here is my creating PDF code, which will open the PDF document .
public void createPDF(string Reportpath, ReportViewer RV)
{
Warning[] warnings;
string[] streamids;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
byte[] bytes = RV.LocalReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamids, out warnings);
try
{
FileStream fs = new FileStream(Reportpath, FileMode.Create);
Thread.Sleep(1000);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
Thread.Sleep(1000);
System.Diagnostics.Process.Start(Reportpath);
}
catch (Exception ex)
{
MessageBox.Show("Report could not be created...\n" + ex.Message);
}
}
instead of opening i need to print the pdf directly using reportviewer or any other way to print that pdf document??.

I think this MSDN article gives a good solution to your problem

got some idea from the following link
http://www.codeproject.com/Tips/598424/How-to-Silently-Print-PDFs-using-Adobe-Reader-and
send the pdf to adobe reader to print....
public static Boolean PrintPDFs(string pdfFileName)
{
try
{
Process proc = new Process();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.Verb = "print";
//Define location of adobe reader/command line
//switches to launch adobe in "print" mode
proc.StartInfo.FileName =
#"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe";
proc.StartInfo.Arguments = String.Format(#"/p /h {0}", pdfFileName);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (proc.HasExited == false)
{
proc.WaitForExit(10000);
}
proc.EnableRaisingEvents = true;
proc.Close();
KillAdobe("AcroRd32");
return true;
}
catch
{
return false;
}
}

Related

C# PSExec to execute multiple path from StreamReader parsing

I'm trying to learn how C# could read and parsing multiple line from text file using streamReader and afterward process each of line with PSExec
Inside cocomand.txt have multiple line example
c:/command1.cmd
c:/command2.bat
c:/command3.cmd
private static void calleachline()
{
string pathx = #"c:\cocomand.txt";
using (StreamReader reader = new StreamReader(new FileStream(pathx, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.ASCII))
{
while ((!reader.EndOfStream))
{
System.Diagnostics.Process cmd = new System.Diagnostics.Process();
cmd.StartInfo.FileName = #"psexec.exe";
cmd.StartInfo.Arguments = #"\\localhost";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
if (!cmd.WaitForExit(cmd2))
{
ExecutePSKill(cmd);
}
else
{
//
}
}
}
Trying to understand from few thread but with my lack knowledge seems this still doesn't work

whats the right c# input stream for cmd.exe encoding

I am starting a cmd.exe from my c# application and redirect its inputstream.This works fine for normal chars like "abc" But when i try to redirect chars like "äöüßáàâ" in the consolewindow appears "õ÷³óô".
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/K";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.WorkingDirectory = #"c:\";
myProcess.Start();
StreamWriter myStreamWriter = myProcess.StandardInput;
myStreamWriter.WriteLine("äöüßáàâ");
myStreamWriter.Encoding says its encoding is codepage 1252 i tryed to convert my string into it but it didnt change the result.
How to convert my string that it is shown correct?
I took the code and ran the same.. When I didnt redirect the output, I saw the same as the OP. However
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/K";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
//myProcess.StartInfo.StandardOutputEncoding = Encoding.UTF32;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.WorkingDirectory = #"c:\";
myProcess.Start();
StreamWriter myStreamWriter = myProcess.StandardInput;
StreamReader myStreamReader = myProcess.StandardOutput;
myStreamWriter.WriteLine("äöüßáàâ");
richTextBox1.Text = myStreamReader.ReadToEnd();
This produced c:\>äöüßáàâ as expected in the text box.. even though it didnt seem to show it as right in the console window that showed.

Downloading FileStream object doesn't open Download Dialog Box

Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
I had other issues with authentication, and the workaround included the using of the FileStream class on my website.
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Is there an way where user can choose where it wants to save the .pdf file?
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.
You might want to combine the two try-catch blocks:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
/*
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
*/
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=\"report.pdf\"");
Response.BinaryWrite(result);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}

How to get wkhtmltopdf logging info in C#?

I'm using wkhtmltopdf to convert some html to pdf. I think I'm getting some javascrpot errors and I'd like to get access to some debug\logging from wkhtmltopdf. Does anyone know how to get the logging info?
var wkhtmlDir = Settings.HtmlToPdfFolderPath;
var wkhtml = Settings.HtmlToPdfExePath;
var p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = wkhtml;
p.StartInfo.WorkingDirectory = wkhtmlDir;
string switches = "";
switches += "--print-media-type --redirect-delay 800 ";
//switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
switches += "--page-size Letter ";
p.StartInfo.Arguments = switches + " " + url
p.Start();
//read output
byte[] buffer = new byte[32768];
byte[] file;
using (var ms = new MemoryStream())
{
while (true)
{
int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
break;
}
ms.Write(buffer, 0, read);
}
file = ms.ToArray();
}
// wait or exit
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
//return returnCode == 0 ? file : null;
return file;
You can read standard error and standard output:
String output =string.Format("STD: {0}\nErr: {1}", p.StandardOutput.ReadToEnd(),
p.StandardError.ReadToEnd());
Is that what you are looking for?

Process hangs when trying to read bytes from buffer to int. Wkhtmltopdf

My method creates PDF out of HTML content with Wkhtmltopdf program with Process. I can't find a reason why it hangs. When there is a big string with HTML, i suppose it hangs when there are 30 pages or more. But everything works fine if there are less pages. Wkhtmltopdf.exe process i can see at the Task Manager, it does not exit forever. When i stop my MVC project with hanged Wkhtmltopdf, it creates normally PDF like it would wait for something.. Manually, of course, Wkhtmltopdf creates everything without any problem.
This is not duplicate of this post. Here i have issues when trying to read bytes into int.
public IActionResult createPdf()
{
string html = "content";
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "...\\wkhtmltopdf.exe";
psi.WorkingDirectory = "...\\wkhtmltopdf\\bin";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.StandardOutputEncoding = System.Text.Encoding.UTF8;
psi.Arguments = "-O landscape --footer-left qwe --footer-center [page]/[topage] --footer-right --footer-font-size 9 --no-stop-slow-scripts --zoom 0.8 --dpi 300 - - ";
p = Process.Start(psi);
byte[] pdf = null;
try
{
// Get PDF as bytes without temp files
using(StreamWriter stdin = new StreamWriter(p.StandardInput.BaseStream, Encoding.UTF8))
{
stdin.AutoFlush = true;
stdin.Write(html);
}
byte[] buffer = new byte[32768];
using(var ms = new MemoryStream())
{
while(true)
{
// HANGS HERE!!!
int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if(read <= 0)
{
break;
}
ms.Write(buffer, 0, read);
}
pdf = ms.ToArray();
}
}
...
}
I managed to solve this problem through merging separated pdf files into one using PdfSharp, instead of passing concatenated content to wkhtmltopdf as one. It lasts a little bit longer, but at least it works. Except of PdfSharp library (if you use MVC as me, then PdfSharp.Core to exclude version warnings), probably you would need to install System.Text.Encoding.CodePages to exclude encoding error that PdfSharp may cause. My method does not use temp files and works only with bytes, at the end it sends created pdf to a browser.
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
public IActionResult createPdf()
{
string html = "";
byte[] pdf = null;
using(PdfDocument doc = new PdfDocument())
{
for(int i = 0; i < files.Length; i++)
{
html = "html content";
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "...\\wkhtmltopdf.exe";
psi.WorkingDirectory = "...\\wkhtmltopdf\\bin";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.StandardOutputEncoding = System.Text.Encoding.UTF8;
psi.Arguments = "-O landscape --footer-left qwe --footer-center [page]/[topage] --footer-right --footer-font-size 9 --no-stop-slow-scripts --zoom 0.8 --dpi 300 - - ";
p = Process.Start(psi);
using(StreamWriter stdin = new StreamWriter(p.StandardInput.BaseStream, Encoding.UTF8))
{
stdin.AutoFlush = true;
stdin.Write(html);
}
byte[] buffer = new byte[32768];
byte[] currentPdf = null;
using(var ms = new MemoryStream())
{
while(true)
{
int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if(read <= 0)
{
break;
}
ms.Write(buffer, 0, read);
}
currentPdf = ms.ToArray();
}
p.StandardOutput.Close();
p.WaitForExit(10000);
p.Close();
MemoryStream currentPDF = new MemoryStream(currentPdf);
// Merge separated pdfs into one
// Solves encoding errors
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using(PdfDocument pdfDoc = PdfReader.Open(currentPDF, PdfDocumentOpenMode.Import))
{
for(int j = 0; j < pdfDoc.PageCount; j++)
{
doc.AddPage(pdfDoc.Pages[j]);
}
}
currentPDF.Close();
}
// Get merged pdfs as bytes
MemoryStream rms = new MemoryStream();
doc.Save(rms, false);
pdf = rms.ToArray();
rms.Close();
}
MemoryStream PDF = new MemoryStream(pdf);
// Return PDF to browser
return new FileStreamResult(PDF, "application/x-msdownload")
{
FileDownloadName = "mergedPdfs.pdf"
};
}

Categories