WPF Printing from a TextBox - c#

I am having trouble printing from a TextBox in WPF
My Textbox will only contain a number between 1 and 999
I wanted to print font size 72 and the text enclosed within a 4" box (so they can cut around the edges)
private void InvokePrint(String contentToPrint)
{
// Create the print dialog object and set options
PrintDialog pDialog = new PrintDialog();
pDialog.PageRangeSelection = PageRangeSelection.AllPages;
pDialog.UserPageRangeEnabled = true;
// Display the dialog. This returns true if the user presses the Print button.
Nullable<Boolean> print = pDialog.ShowDialog();
if (print == true)
{
FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Printing Label");
}
}
I got the code from Microsoft's site but they are using an XPS printer. I want to use the default selected printer (usually an HP).
Any help would greatly be appreciated

Related

WPF RichTexBox printing is creating unexpected line breaks

In RichTextBox of my WPF app, following print method is creating unexpected line breaks. Question: What I may be missing here, and how can we fix the issue?
For example, when I enter the following text in the RichTextBox (RTB), the RTB looks like as shown in image 1. But when I call the following two print methods the first one does not create the unexpected line breaks, but the second method does create unexpected line breaks:
MainWindow.xaml
<StackPanel>
<RichTextBox Name="richTB" />
<Button Click="PrintCommand1">Print RTB Content</Button>
<Button Click="PrintCommand2">Print RTB Content</Button>
</StackPanel>
Method 1
private void PrintCommand1(Object sender, RoutedEventArgs args)
{
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
pd.PrintVisual(richTB as Visual, "printing as visual");
}
}
Method 2
private void PrintCommand2(Object sender, RoutedEventArgs args)
{
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");
}
}
The text I enter [Note: There is only one line break]
This is a test for testing purpose only. Another test: x6. Let us do some background and foreground colors.
This is a new line with formatting, as well.
Snapshot of the RichTexBox with above text
Snapshot of "Print to PDF" (on Windows 10) using Method 1 [Printed correctly with one real line break]
Snapshot of "Print to PDF" (on Windows 10) using Method 2 [Printed incorrectly with unexpected line breaks]
Because of the DocumentPaginator class takes context of the FlowDocument and split in into multiple pages to get desired result some of FlowDocument parameters should be configured before printing:
private void PrintCommand2(Object sender, RoutedEventArgs args)
{
var pd = new PrintDialog();
if (pd.ShowDialog() == true)
{
FlowDocument doc = richTB.Document;
// Save all settings that will be configured for printing.
double pageHeight = doc.PageHeight;
double pageWidth = doc.PageWidth;
double columnGap = doc.ColumnGap;
double columnWidth = doc.ColumnWidth;
// Make the FlowDocument page match the printed page.
doc.PageHeight = pd.PrintableAreaHeight;
doc.PageWidth = pd.PrintableAreaWidth;
doc.ColumnGap = 5;
// Set the minimum desired width of the column in the System.Windows.Documents.FlowDocument.
doc.ColumnWidth = doc.PageWidth - doc.ColumnGap - doc.PagePadding.Left - doc.PagePadding.Right;
pd.PrintDocument(((IDocumentPaginatorSource)doc).DocumentPaginator, "A Flow Document");
// Reapply the old settings.
doc.PageHeight = pageHeight;
doc.PageWidth = pageWidth;
doc.ColumnGap = columnGap;
doc.ColumnWidth = columnWidth;
}
}
With respect to Matthew MacDonald this way of the flow document content printing and more advanced techniques described in his book Pro WPF 4.5 in C# Windows Presentation Foundation in .NET 4.5 (Chapter 29).

Windows Presentation Foundation Print Label (Zebra Printer)

I am trying to print text to display vertical in Windows Forms Host. The label is printing with report viewer in WPF. Here is my code:
// boolean is based on true or false, when printing labels
private bool _isReportViewerLoaded;
// method to display data in .rdlc
private void ReportViewer_Load(object sender, EventArgs e)
{
// if equal false run this code isReportViewerLoaded
if (!_isReportViewerLoaded)
{
// get the lot based on the parameter Id
Lot lot = BottleLotRespository.GetLotById(this.Parameter);
// settings the page settings
PageSettings pg = new PageSettings();
pg.PrinterSettings
.DefaultPageSettings
.Margins = new Margins(0, 0, 0, 0);
pg.Landscape = false;
PaperSize size = new PaperSize("110.0 x 74.0", 433, 100);
BottleLotDataSet bottleLotDataSet = new BottleLotDataSet();
DataTable reportDataTable = bottleLotDataSet.LotDataTable;
DataRow lotRow = reportDataTable.NewRow();
lotRow["Id"] = lot.Id;
lotRow["Number"] = lot.Number.ToString();
reportDataTable.Rows
.Add(lotRow);
bottleLotDataSet.BeginInit();
this._reportViewer.SetPageSettings(pg);
this.reportDataSource.Name = "DataSet1";
this.reportDataSource.Value = reportDataTable;
this._reportViewer
.LocalReport
.DataSources
.Add(this.reportDataSource);
this._reportViewer
.LocalReport
.ReportEmbeddedResource = "BottleLotWPF.View.Report1.rdlc";
bottleLotDataSet.EndInit();
_reportViewer.RefreshReport();
_isReportViewerLoaded = true;
}
}
My problem is that the Report1.rdlc is not allowing me to rotate the text and there is no settings for it. Is there away of adding a setting to it to rotate the text?
In RDLC we have the option to print vertically it seems.
please take look at the existing thread here and see if it helps.
display-text-vertically-start-

How to print multiple datagridview's using printdocument c#

I have a winform app that will show the user 3 different datagridviews with the relevant data they are enquiring about. I have allowed for the user to select which grids to print out. I can print the first page fine but after that it get an index error. I want it to be setup like any other print out where this one dialog box and they all print out in one document. Example if they select all 3 then 3 pages print. If they select just one then just that one. If they select two then those two print. How beyond the first page can you add the other grids?
Print button click event:
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDocument1;
printDialog.Document = printDocument2;
printDialog.Document = printDocument3;
printDialog.UseEXDialog = true;
if (DialogResult.OK == printDialog.ShowDialog())
{
if (chkBoxByScale.Checked)
{
printDocument1.DocumentName = "Project Report";
printDocument1.Print();
}
if (chkBoxByUser.Checked)
{
printDocument2.DocumentName = "Project Report 2";
printDocument2.Print();
}
if (chkBoxByLine.Checked)
{
printDocument3.DocumentName = "Project Report 3";
printDocument3.Print();
}
}
If you want me to provide nay of the PrintBegin or PrintPage let me know. Seemed very lengthy for posting all.

WPF Printing prints on 1 system and not on other

I have a WPF application in which I have 3 forms of prints. In 2 ways, I use directly a window's visual and use PrintVisual(myPanel, "Title") to print it. And in 3rd, I got to print multiple pages so I am using FlowDocument, StackPanel and finally IDocumentPaginatorSource and call PrintDocument to print.
All the code is working perfectly on my system. I can perform Print on OneNote and XPS and it works as expected. But the same app, when I try to run on other system it shows blank page for all 3 prints. PrintVisual is supported on .NET 3.0, 3.5, 4.0, 4.5, so I can't find a reason for it not to work.
I will also share my some code, for better clarity :
// 1 PRINT
public void PrintRegister()
{
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == true)
pd.PrintVisual(this, "Register Window");
return;
}
// 2 PRINT
public static void PrintAttendanceOf(System.Data.DataRow r1) {
PrintLayoutWindowPORT plw = PrintUtility.CreatePrintLayoutWindowPORTObject(r1); // PORTRAIT
Canvas p1 = PrintUtility.CloneCanvas(plw._PrintCanvas, 5);
Grid myPanel = new Grid();
myPanel.Margin = new Thickness(10);
myPanel.Children.Add(p1);
PrintDialog pd = new PrintDialog();
pd.PageRangeSelection = PageRangeSelection.AllPages;
PrintQueue pq = pd.PrintQueue;
pq.DefaultPrintTicket.PageOrientation = PageOrientation.Portrait;
pd.PrintTicket = pq.DefaultPrintTicket;
double pageWidth = pd.PrintableAreaWidth;
double pageHeight = pd.PrintableAreaHeight;
myPanel.Measure(new Size(pageWidth, pageHeight));
//myPanel.Arrange(new Rect(new Point(1, 1), myPanel.DesiredSize));
myPanel.UpdateLayout();
if (pd.ShowDialog().GetValueOrDefault(false))
{
pd.PrintVisual(myPanel, "Attendance Chart");
}
pd = null;
plw.Close();
plw = null;
myPanel = null;
p1 = null;
return;
}
Code for the 3rd Print i.e. Multiple Pages is quiet long, hence have not added it now here. If required, can post it.
Can anyone help me know the reason for printing blank page and no contents on other system. I feel some sort of compatibility or system or resource may be required or what else?
Any help is highly appreciated.
Thanks

c# print function hide window

I have my main form and then launch a new form. The new form is in the front. I send data to the printer which opens a print window popup. (prints to default, no printer to select) It then defaults back to my first form and I have to do a BringtoFront on the 2nd form after 1ms. This is an ok fix because it is only a small blip, but is there a way to hide that print window popup all together so that it just prints in the background?
// code to print
PrintDocument prnDocument;
string printername; //Get the default printer name.
prnDocument = new PrintDocument();
printername = Convert.ToString(prnDocument.PrinterSettings.PrinterName);
if (string.IsNullOrEmpty(printername))
throw new Exception("No default printer is set.Printing failed!");
prnDocument.PrintPage += new PrintPageEventHandler(prnDoc_PrintPage);
prnDocument.Print();
According to this SO post, you should be able to hide the print dialog by doing the following:
PrintDocument printDocument = new PrintDocument();
PrintController printController = new StandardPrintController();
printDocument.PrintController = printController;
Is this what you mean?

Categories

Resources