Set margin to printing document while wpf control is printing - c#

I am trying to print a treeview control in wpf using the following code
PrintDialog printDlg = new PrintDialog();
printDlg.PrintVisual(trv, "GTree Printing.");
The treeview is printing, but it prints to right side and some data is cutting off. How do I set margin in this case? Also It won't print the entire tree structure, only the visible portion is printing. Please do advise on this.
This is in desktop application
Thanks,
Sivajith

public static void Print(IEnumerable<UIElement> dataForPrint, string printerName)
{
try
{
var printDialog = new PrintDialog();
using (var printQueue = new PrintQueue(new PrintServer(), printerName))
{
printDialog.PrintQueue = printQueue;
var area = printDialog.PrintQueue.GetPrintCapabilities();
if (area.PageImageableArea == null) throw new Exception("Failed to load printer settings.");
var flowDocument = new FlowDocument
{
PagePadding = new Thickness(area.PageImageableArea.OriginWidth, 0, 0, 0),
PageWidth = area.PageImageableArea.ExtentWidth + area.PageImageableArea.OriginWidth
};
foreach (var uiElement in dataForPrint)
{
flowDocument.Blocks.Add(new BlockUIContainer(uiElement));
}
var paginator = ((IDocumentPaginatorSource) flowDocument).DocumentPaginator;
printDialog.PrintDocument(paginator, "A Flow Document");
}
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
Log(e);
}
}
If you show Printer Dialog you haven't to create PrintQueue. Just access to PrintDialog.PrintQueue property

Related

How to Change the Default Printing Page Size to A3 from A4 on C# WinForm?

I have tried to make a printing program on C#, I can customize all other settings except the page size. Is there a way to change the default printing page size? I have tried to change the page size to A3 by the RawKind, but the output would always be A4. Here is my code:
using (var form = new PrintDialog())
using (var document = _document.CreatePrintDocument(DefaultPrintMode))
try
{
form.AllowSomePages = true;
form.Document = document;
form.Document.PrinterSettings.PrinterName = printername;
//============Paper Size
PaperSize ps = form.Document.DefaultPageSettings.PaperSize;
ps.RawKind = Convert.ToInt32(PaperKind.A3);
try
{
if (form.Document.PrinterSettings.FromPage <= _document.PageCount)
form.Document.Print();
}
catch
{
}
}
catch (Exception e)
{
MessageBox.Show(this, e.Message.ToString());
}

C# WinForms: Data in report is not printing.

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.

Printpreview controller does not display the file

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.

How to get this UI output in printout?

I am working on WPF application.Here i have to work on some print formats.To solve paging issue for print i am using the following code :
private void Button_Click(object sender, RoutedEventArgs e)
{
// Create a PrintDialog
PrintDialog printDlg = new PrintDialog();
// Create a FlowDocument dynamically.
FlowDocument doc = CreateFlowDocument();
doc.Name = "FlowDoc";
doc.PageHeight = printDlg.PrintableAreaHeight;
doc.PageWidth = printDlg.PrintableAreaWidth;
// Create IDocumentPaginatorSource from FlowDocument
IDocumentPaginatorSource idpSource = doc;
// Call PrintDocument method to send document to printer
printDlg.PrintDocument(idpSource.DocumentPaginator, "Hello WPF Printing.");
}
and
private FlowDocument CreateFlowDocument()
{
// Create a FlowDocument
FlowDocument doc = new FlowDocument();
int i = 0;
while (i <2)
{
// Create first Paragraph
Paragraph p1 = new Paragraph();
MyUserControl comp = new MyUserControl ();
p1.BorderBrush = new SolidColorBrush(Color.FromRgb(79, 129, 189));
p1.BorderThickness = new Thickness(3);
p1.Inlines.Add(comp);
// Add Paragraph to Section
doc.Blocks.Add(p1);
// Add Section to FlowDocument
//doc.Blocks.Add(sec);
i++;
}
return doc;
}
this code works fine for me.
Problem :
I just have problem with UI which i am getting using this code.
This is the print which i am getting now on paper :
and this is the print which i require on paper:
Please provide some idea and code so that i can clear this problem.
Thanks in advance.

Change number of copies displayed in PrintDialog box

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);
}

Categories