I am working on Crystal Reports for Visual Studio 2005. I need to change the default printer, and the number of copies to 2 as compared to the default of 1.
I have succeeded to change the default printer using below code.
static int SetAsDefaultPrinter(string printerDevice)
{
int ret = 0;
try
{
string path = "win32_printer.DeviceId='" + printerDevice + "'";
using (ManagementObject printer = new ManagementObject(path))
{
ManagementBaseObject outParams =
printer.InvokeMethod("SetDefaultPrinter",
null, null);
ret = (int)(uint)outParams.Properties["ReturnValue"].Value;
}
}
}
How can I change the number of copies printed?
.Net Framework doesn't provide any mechanism to override the default print functionality. So I disabled the default print button, and added a button name Print.Code for the Event Handler follows below.
private void Print_Click(object sender, EventArgs e)
{
try
{
PrintDialog printDialog1 = new PrintDialog();
PrintDocument pd = new PrintDocument();
printDialog1.Document = pd;
printDialog1.ShowNetwork = true;
printDialog1.AllowSomePages = true;
printDialog1.AllowSelection = false;
printDialog1.AllowCurrentPage = false;
printDialog1.PrinterSettings.Copies = (short)this.CopiesToPrint;
printDialog1.PrinterSettings.PrinterName = this.PrinterToPrint;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
PrintReport(pd);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PrintReport(PrintDocument pd)
{
ReportDocument rDoc=(ReportDocument)crvReport.ReportSource;
// This line helps, in case user selects a different printer
// other than the default selected.
rDoc.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName;
// In place of Frompage and ToPage put 0,0 to print all pages,
// however in that case user wont be able to choose selection.
rDoc.PrintToPrinter(pd.PrinterSettings.Copies, false, pd.PrinterSettings.FromPage,
pd.PrinterSettings.ToPage);
}
Related
I am new to C# and reports. What am I doing wrong or missing?
I have searched and searched and for the life of me can't figure this out.
I am using C# Windows Forms Application. I have report2.rdlc and everything works great in the report viewer, the text boxes and data in the tablix print as expected. When I print directly to the printer without using the report viewer, the text boxes print, but the data in the tablix does not print. Provided below is a screenshot of the Report Data window along with the coding and explanation.
Report Data Image
StatusCodes.cs form: Contains print button that has DialogResult. If "Yes" is clicked, StatusCodePreview.cs form opens. This has the report viewer (no problems here). If "No" is clicked, this triggers PrintWithoutReportViewer.cs and the report is printed directly to the default printer (problem: only text boxes and column headers are printing, data is not).
private void btn_CodePrint_Click(object sender, EventArgs e)
{
var message = "Do you wish to preview the report before printing?";
var title = "Preview Report";
DialogResult dg = MessageBox.Show(message, title, MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
StatusCodePreview scp = new StatusCodePreview();
scp.Show();
}
else if (dg == DialogResult.No)
{
DataTable dt = new StatusCodesPrintDataSet.DataTable1DataTable();
LocalReport report = new LocalReport {ReportEmbeddedResource = "Toolbar.Report2.rdlc"};
report.DataSources.Add(new ReportDataSource("StatCodePrintDataSet1", dt));
report.PrintToPrinter();
}
}
Code for PrintWithoutReportViewer.cs
public static class PrintWithoutReportViewer
{
private static int m_CurrentPageIndex;
private static IList<Stream> m_Streams;
private static PageSettings m_PageSettings;
public static Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
{
Stream stream = new MemoryStream();
m_Streams.Add(stream);
return stream;
}
public static void Export(LocalReport report, bool print = true)
{
PaperSize paperSize = m_PageSettings.PaperSize;
Margins margins = m_PageSettings.Margins;
string deviceInfo = string.Format(
CultureInfo.InvariantCulture,
"<DeviceInfo>" +
"<OutputFormat>EMF</OutputFormat>" +
"<PageWidth>{5}</PageWidth>" +
"<PageHeight>{4}</PageHeight>" +
"<MarginTop>{0}</MarginTop>" +
"<MarginLeft>{1}</MarginLeft>" +
"<MarginRight>{2}</MarginRight>" +
"<MarginBottom>{3}</MarginBottom>" +
"</DeviceInfo>",
ToInches(margins.Top),
ToInches(margins.Left),
ToInches(margins.Right),
ToInches(margins.Bottom),
ToInches(paperSize.Height),
ToInches(paperSize.Width));
Warning[] warnings;
m_Streams = new List<Stream>();
report.Render("Image", deviceInfo, CreateStream,
out warnings);
foreach (Stream stream in m_Streams)
stream.Position = 0;
if (print)
{
Print();
//PrintDialog startPrint = new PrintDialog();
//startPrint.ShowDialog();
}
}
public static void PrintPage(object sender, PrintPageEventArgs e)
{
Stream pageToPrint = m_Streams[m_CurrentPageIndex];
pageToPrint.Position = 0;
using (Metafile pageMetaFile = new Metafile(pageToPrint))
{
Rectangle adjustedRect = new Rectangle(
e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
e.PageBounds.Width,
e.PageBounds.Height);
e.Graphics.FillRectangle(Brushes.White, adjustedRect);
e.Graphics.DrawImage(pageMetaFile, adjustedRect);
m_CurrentPageIndex++;
e.HasMorePages = m_CurrentPageIndex < m_Streams.Count;
}
}
public static void Print()
{
if (m_Streams == null || m_Streams.Count == 0)
throw new Exception("Error: no stream to print.");
PrintDocument printDoc = new PrintDocument();
if (!printDoc.PrinterSettings.IsValid)
{
throw new Exception("Error: cannot find the default printer.");
}
else
{
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
m_CurrentPageIndex = 0;
printDoc.Print();
}
}
public static void PrintToPrinter(this LocalReport report)
{
m_PageSettings = new PageSettings();
ReportPageSettings reportPageSettings = report.GetDefaultPageSettings();
m_PageSettings.PaperSize = reportPageSettings.PaperSize;
m_PageSettings.Margins = reportPageSettings.Margins;
Export(report);
}
public static void DisposePrint()
{
if (m_Streams != null)
{
foreach (Stream stream in m_Streams)
stream.Close();
m_Streams = null;
}
}
private static string ToInches(int hundrethsOfInch)
{
double inches = hundrethsOfInch / 100.0;
return inches.ToString(CultureInfo.InvariantCulture) + "in";
}
}
I was originally trying to print using PrintDialog (I was wanting this option to allow user to still be able to select a printer), but that doesn't work at all and just led me to getting so frustrated. I am now just trying to use Print();
Like I said at the beginning, I am new at this and I'm lost. It would be greatly appreciated if anyone can help me with this.
On 1 Form I have two buttons (one to print to PDF printer, second to normal printer). I print some bitmap image. However behaviour of the program is strange. Sometimes both buttons work as expected. Sometimes normal printer prints blank, while pdf prints proper, sometimes normal printer do not print anything while pdf printer prints some "code".
Below my code
private void printBtn_Click(object sender, EventArgs e)
{ ... BmpToPrint = new Bitmap(tmp_bmp);
tmp_bmp.Dispose();
string file = "sometext";
pdoc.PrinterSettings.PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer"];
pdoc.DocumentName = file;
pdoc.DefaultPageSettings.Landscape = false;
ppv.Document = pdoc; //printpreviewdialog ppv, printdocument pdoc
printDialog1.Document = pdoc;
if (printDialog1.PrinterSettings.IsValid) { pdoc.Print(); } }
private void printPdfBtn_Click(object sender, EventArgs e)
{... BmpToPrint = new Bitmap(tmp_bmp);
tmp_bmp.Dispose();
string file = "sometext" + ".pdf";
if (!Directory.Exists(directory)) { directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); }
pdoc.PrinterSettings.PrinterName = System.Configuration.ConfigurationManager.AppSettings["PdfPrinter"];
pdoc.PrinterSettings.PrintToFile = true;
pdoc.DocumentName = file;
pdoc.PrinterSettings.PrintFileName = Path.Combine(directory, file);
pdoc.DefaultPageSettings.Landscape = false;
ppv.Document = pdoc;
printDialog1.Document = pdoc;
if (printDialog1.PrinterSettings.IsValid) { pdoc.Print(); } }
private void pdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.Clear(Color.White);
Point PktWst = new Point(5, 0);
e.Graphics.DrawImage(BmpToPrint, PktWst);
e.HasMorePages = false;
}
sometimes in pdf instead of image appears this
Sometimes it works perfectly printing image both to pdf and printer while sometimes the same image as before is either not printed/blank printed/ or pdf has this artifacts instead.
Shall I reset some settings while using second printer or clean some data somehow?
We have aspx page that is being used as a dialog box.
Page has ascx control which has Text box to search available users from oracle DB tables.
Every search click posts back to same control and renders search results.
If I click search and before response is back from server I close the dialog aspx page, then next time I try to open same dialog box it takes forever to render.
Please suggest what could be happening, going wrong?
Any help is highly appreciated
Here is the code
protected void UserListControl_PreRender(object sender, EventArgs e)
{
//set UI text
m_objTitle.Text = TITLE_LABEL;
//Set Properties of search
m_objSearchResults.CacheResults = true;
m_objSearchResults.RefreshCache = true;
m_objSearchResults.DoSearch = true;
m_objSearchResults.Pageable = true;
m_objSearchResults.NoRecordsMessage = NO_RECORDS_MSG;
m_objSearchResults.PageSize = 25;
m_objSearchResults.SearchType = m_sSearchType;
//Add items to the dropdown
if (m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(AVAIL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT).Value = AVAIL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(ALL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT).Value = ALL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(SEARCH_USER_TEXT);
m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT).Value = SEARCH_USER_VALUE;
}
if (this.Page.IsPostBack == false)
{
m_objStatusDropDown.SelectedValue = SEARCH_USER_VALUE;
}
if (IsPostBack)
{
try
{
m_objUserInstructionText.Text = "";
//add the DAO Parameters
string assignmentTypeSelected = Request.QueryString["AssignmentType"];
m_objSearchResults.DAOParams.Add("RequestType", Request.QueryString["RequestType"]);
m_objSearchResults.DAOParams.Add("AssignmentID", Request.QueryString["AssignmentID"]);
m_objSearchResults.DAOParams.Add("AssignmentType", assignmentTypeSelected);
m_objSearchResults.DAOParams["StatusFilter"] = m_objStatusDropDown.SelectedValue.ToUpper();
m_objSearchResults.DAOParams["Name"] = m_objSearchTextBox.Value.Trim();
if (null == SetApplCode(assignmentTypeSelected))
{
throw new ApplicationException("Invalid Assignment Type.");
}
else
{
m_objSearchResults.DAOParams["ApplCode"] = SetApplCode(assignmentTypeSelected).ToUpper();
}
//add searchControl
m_objListPH.Controls.Add(m_objSearchResults);
// Get the values from the ResultsForm
string sRecordsDisplayed = m_objSearchResults.RecordsDisplayed;
string sTableWidth = m_objSearchResults.TableWidth;
bool bPageable = m_objSearchResults.Pageable;
int iCurrentPageIndex = m_objSearchResults.CurrentPageIndex;
int iPageSize = m_objSearchResults.PageSize;
int iRecordCount = m_objSearchResults.RecordCount;
int iEndRecord = m_objSearchResults.EndRecord;
// Create the html if we are paging data
m_objNavigation.Visible = bPageable;
m_objNavigation.DisplayViewAllButton = false;
m_objNavigation.PageSize = iPageSize;
m_objNavigation.Count = iRecordCount;
m_objNavigation.ItemsDisplayText = "Users";
m_objNavigation.CurrentPage = iCurrentPageIndex + 1;
}
catch (ApplicationException ex)
{
m_objInvalidAssignTypeErr.Text = ex.Message;
m_objUserInstructionText.Text = "";
}
}
}
I have the codes below
fName =E:\Csharp\NewMacaron\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\\data00.txt"
From a method within my program I create, into application folder, a series of datas as fName above
After lunching the printing form I have the printcontroller preview on screen with Previous Next and some other buttons for printing and zooming.
On form_load I have ShowPage();
PrintPageEventHandler does not work and nothing is displayed.
However when I click the print_button correct page is printed:
What is wrong with the printpreviewcontroller ?
I'am using .net 3.5 and c# 2008
private void ShowPage()
{
try
{
streamToPrint = new StreamReader(fName, Encoding.UTF8);
pd = new PrintDocument();
pd.DocumentName = fName;
PrinterSettings ps = new PrinterSettings();
printFont = new Font("Courier", 10);
pd.PrinterSettings.PrinterName = prnName; // GetDefaultPrinter returns prName
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("PaperA4", 840, 1180);
ppc = new PrintPreviewControl();
ppc.Document = pd;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
}
catch (Exception es)
{
MessageBox.Show(es.Message.ToString());
}
}
private void print_button(object sender, EventArgs e)
{
streamToPrint = new StreamReader(fName, Encoding.UTF8);
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
try
{
pd.Print();
}
catch (Win32Exception es)
{
MessageBox.Show(es.Message.ToString());
streamToPrint.Close();
}
streamToPrint.Close();
PublicVariables.PrintFormStat = false;
PublicVariables.PrintData = 0;
this.Hide();
I have a CRIMINAL BUG in the program the printform was named ppc and the printpreviewcontroller also.
I don't know how assembly has accepted that.
After the correction of that tI can only use one time printpreviewcontroller
The second page is not displayed.
This is similar to older posts on this site but I keep getting an error message. I want to create a button in C # WPF that opens a dialogbox and saves a text file to be read at a later date. This code works for windows 32, but crashes on windows 64. How can I change this code to get it to work on both systems? I am a beginner at programming.
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog(); //throws error message here
private void savebutton_Click(object sender, RoutedEventArgs e)
{
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain (*.cur)|*.cur";
saveFile.FilterIndex = 2;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
bool? result = saveFile.ShowDialog();
if (result.HasValue && result.Value)
{
clsSaveFile.s_FilePath = saveFile.FileName;
int iDotLoc = clsSaveFile.s_FilePath.LastIndexOf('.');
string strExtTest = clsSaveFile.s_FilePath.Substring(iDotLoc);
if (strExtTest != ".cur")
clsSaveFile.s_FilePath += ".cur";
FileInfo sourceFile = new FileInfo(clsSaveFile.s_FilePath);
clsSaveFile.saveFile();
}
}
You're setting an invalid FilterIndex, that might have something to do with it.
There is no 2nd filter in the filter string as written:
"CCurtain (*.cur)|*.cur"
Try setting the FilterIndex to 1 or adding another filter to the string.
You should try adding a catch around the statement to get a better idea as to what is going on.
try
{
code here
}
catch (Exception ex)
{
ex.message contains the info
}
Also, check for null:
bool? result = saveFile.ShowDialog();
if (result != null && (result.HasValue && result.Value))
{
// code
}
I would create the dialogbox IN the event. And you don't have two different filters.
private void savebutton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain|*.cur";;
saveFile.FilterIndex = 1;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
// Show open file dialog box
Nullable<bool> result = saveFile.ShowDialog();
// Process open file dialog box results
if (result == true)
{
string filename = saveFile.FileName;
// are you sure you need to check the extension.
// if so extension is a a fileinfo property
}