I'm trying to print from a WPF application, but struggling to set a default page size.
The content I'm printing is supposed to be on a C5-sized envelope, and most printers here default to A4 paper.
I'd like to show a dialog to the user to allow them to choose the printer to use - but if they just press OK to accept the default printer, it defaults to A4 paper.
How can I set the print defaults for a job to C5 envelop?
Can I still prompt the user for the printer?
private void PrintVisual_Sized(UIElement toPrint)
{
PrintDialog dlg = new PrintDialog();
PrintQueue queue = dlg.PrintQueue;
// Get C5 page size if possible from printer
var availPageSizes = queue.GetPrintCapabilities().PageMediaSizeCapability;
PageMediaSize pageSize = Utilities.GetPageSize(availPageSizes, PageMediaSizeName.ISOC5Envelope);
if (pageSize != null)
{
PrintTicket ticket = new PrintTicket
{
PageMediaSize = pageSize,
InputBin = InputBin.AutoSelect,
CopyCount = 1
};
dlg.UserPageRangeEnabled = false;
var result = dlg.PrintQueue.MergeAndValidatePrintTicket(dlg.PrintTicket, ticket);
Debug.Print(result.ConflictStatus.ToString());
// Try to get the page size honoured by someone!!!
dlg.PrintQueue.DefaultPrintTicket = result.ValidatedPrintTicket;
dlg.PrintQueue.UserPrintTicket = result.ValidatedPrintTicket;
dlg.PrintTicket = result.ValidatedPrintTicket;
// Height still seems to be A4 sized!?
Debug.Print("Height: " + dlg.PrintableAreaHeight);
}
// Ask user which printer they want...
if (dlg.ShowDialog().GetValueOrDefault(false))
{
Size printSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight);
toPrint.Measure(printSize);
toPrint.Arrange(new Rect(new Point(), printSize));
toPrint.UpdateLayout();
dlg.PrintVisual(toPrint, "My Print Job");
}
}
In the last section printSize is A4 unless the user manually selects another paper size.
Is there any way to display the dialog, with a non-default page size preset?
Related
I want to print full photo size A6 10*14 but my program don't have A6 size.
How I add paper size A6 in my program?
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
task = args.Request.CreatePrintTask("Print", OnPrintTaskSourceRequrested);
task.Completed += PrintTask_Completed;
task.Options.MediaSize = Windows.Graphics.Printing.PrintMediaSize.IsoA6;
PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(task.Options);
IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
// Create a new list option
PrintCustomItemListOptionDetails pageFormat = printDetailedOptions.CreateItemListOption("PageContent", "Pictures");
pageFormat.AddItem("PicturesText", "Image And Frame");
pageFormat.AddItem("PicturesOnly", "Pictures only");
// Add the custom option to the option list
displayedOptions.Add("PageContent");
printDetailedOptions.OptionChanged += printDetailedOptions_OptionChanged;
deferral.Complete();
}
If you want to print 10*14 Please set MediaSize as NorthAmerica10x14. And the size of IsoA6 is 4.13*5.83
protected override void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", async sourceRequestedArgs =>
{
printTask.Options.MediaSize = Windows.Graphics.Printing.PrintMediaSize.NorthAmerica10x14;
var deferral = sourceRequestedArgs.GetDeferral();
PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(printTask.Options);
IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
// Choose the printer options to be shown.
// The order in which the options are appended determines the order in which they appear in the UI
displayedOptions.Clear();
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Copies);
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Orientation);
displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.ColorMode);
// Create a new list option
PrintCustomItemListOptionDetails pageFormat = printDetailedOptions.CreateItemListOption("PageContent", "Pictures");
pageFormat.AddItem("PicturesText", "Pictures and text");
pageFormat.AddItem("PicturesOnly", "Pictures only");
pageFormat.AddItem("TextOnly", "Text only");
// Add the custom option to the option list
displayedOptions.Add("PageContent");
// Create a new toggle option "Show header".
PrintCustomToggleOptionDetails header = printDetailedOptions.CreateToggleOption("Header", "Show header");
// App tells the user some more information about what the feature means.
header.Description = "Display a header on the first page";
// Set the default value
header.TrySetValue(showHeader);
// Add the custom option to the option list
displayedOptions.Add("Header");
// Create a new list option
PrintCustomItemListOptionDetails margins = printDetailedOptions.CreateItemListOption("Margins", "Margins");
margins.AddItem("WideMargins", "Wide", "Each margin is 20% of the paper size", await wideMarginsIconTask);
margins.AddItem("ModerateMargins", "Moderate", "Each margin is 10% of the paper size", await moderateMarginsIconTask);
margins.AddItem("NarrowMargins", "Narrow", "Each margin is 5% of the paper size", await narrowMarginsIconTask);
// The default is ModerateMargins
ApplicationContentMarginTop = 0.1;
ApplicationContentMarginLeft = 0.1;
margins.TrySetValue("ModerateMargins");
// App tells the user some more information about what the feature means.
margins.Description = "The space between the content of your document and the edge of the paper";
// Add the custom option to the option list
displayedOptions.Add("Margins");
printDetailedOptions.OptionChanged += printDetailedOptions_OptionChanged;
// Print Task event handler is invoked when the print job is completed.
printTask.Completed += (s, args) =>
{
// Notify the user when the print operation fails.
if (args.Completion == PrintTaskCompletion.Failed)
{
MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage);
}
};
sourceRequestedArgs.SetSource(printDocumentSource);
deferral.Complete();
});
}
For more please refer PrintMediaSize Enum, This is official code sample
I have one user control in which i displayed the map and the data in the datagrid.
I have tried following code but it does not works.
PrintDialog printDialog = new PrintDialog();
// if user clicks on cancel button of print dialog box then no need to print the map control
if (!(bool)printDialog.ShowDialog())
{
return;
}
else // this means that user click on the print button
{
// do nothing
}
this.Measure(new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight));
this.Arrange(new Rect(new Point(20, 20), new Size(this.ActualWidth, this.ActualHeight)));
// print the map control
printDialog.PrintVisual(this, "Karte drucken");
Issue : When data grid has large number of records then user control gets scroll bar, but after printing the user control, only visible part of user control is printed and not the data present which we can see after scrolling down.I want to print whole content of user control.
Is there any solution for this, also how can we see print preview in wpf ?
Please check the following link, it should be helpful. Print Preview WPF
Code
PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
if (printDlg.ShowDialog() == true)
{
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
this.ActualHeight);
//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
//update the layout of the visual to the printer page size.
this.Measure(sz);
this.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
//now print the visual to printer to fit on the one page.
printDlg.PrintVisual(this, "First Fit to Page WPF Print");
}
I want to print my Crystal report direct to the printer. Currently I am having the export to PDF. But my client want this to go to Printer directly. How can I show the Print Dialog on click of Print Button to Print the report directly to Printer.
I would like to mention: I am using C# and asp.net for my project.
Thank you.
Try the following code
private void Button1_Click(object sender, EventArgs e)
{
CrystalReport1 report1 = new CrystalReport1();
PrintDialog dialog1 = new PrintDialog();
report1.SetDatabaseLogon("username", "password");
dialog1.AllowSomePages = true;
dialog1.AllowPrintToFile = false;
if (dialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int copies = dialog1.PrinterSettings.Copies;
int fromPage = dialog1.PrinterSettings.FromPage;
int toPage = dialog1.PrinterSettings.ToPage;
bool collate = dialog1.PrinterSettings.Collate;
report1.PrintOptions.PrinterName = dialog1.PrinterSettings.PrinterName;
report1.PrintToPrinter(copies, collate, fromPage, toPage);
}
report1.Dispose();
dialog1.Dispose();
}
you will have to change the "username" and the "password" with the credentials of your database.
EDIT
This code can be used for server side printing only.
No way; Cristal Report Viewer is intended for showing and browsing a report.
It never shows all report pages.
It has no buttons or methods for direct printing.
You could, instead, export directly the report in PDF so Report Viewer is never seen by users, and printing becomes 1-click operation.
PrintButton_click Event and add following code as you ..
//show Print Dialog
PrintDialog printDialog = new PrintDialog();
DialogResult dr = printDialog.ShowDialog();
if (dr == DialogResult.OK)
{
ReportDocument crReportDocument = (ReportDocument)CrystalReportViewer1.ReportSource;
System.Drawing.Printing.PrintDocument printDocument1 = new System.Drawing.Printing.PrintDocument();
//Get the Copy times
int nCopy = printDocument1.PrinterSettings.Copies;
//Get the number of Start Page
int sPage = printDocument1.PrinterSettings.FromPage;
//Get the number of End Page
int ePage = printDocument1.PrinterSettings.ToPage;
crReportDocument.PrintOptions.PrinterName =printDocument1.PrinterSettings.PrinterName;
//Start the printing process. Provide details of the print job
crReportDocument.PrintToPrinter(nCopy, false, sPage, ePage);
// Form_Printerd = true;
}
I am experiencing an odd issue with printing from a WPF project. I'm printing a screen capture of the application for reporting purposes, and all that works just fine. Currently the user presses print, the print dialog appears, and they print out the capture image.
However, I want to be able to print directly to the default printer without showing the dialog box. This should be easily done by commenting out the ShowDialog() statement and allowing the rest to just happen. The printer still prints, but the pages are always blank.
Can anyone explain this behavior?
private void PrintCurrentScreen()
{
PrintDialog PD = new PrintDialog();
PD.PrintTicket.OutputColor = OutputColor.Grayscale;
PD.PrintTicket.OutputQuality = OutputQuality.Draft;
PrintTicket PT = new PrintTicket();
PT.PageOrientation = PageOrientation.Landscape;
PT.CopyCount = 1;
PT.PageBorderless = System.Printing.PageBorderless.Borderless;
//---Blank pages print when commented out---//
//if (PD.ShowDialog() == true)
//{
PD.PrintTicket = PT;
DrawingVisual DV = new DrawingVisual();
DV.Offset = new Vector(20, 20);
DrawingContext DC = DV.RenderOpen();
DC.DrawImage(previewimage.Source, new Rect(new Size(PD.PrintableAreaWidth - 40, PD.PrintableAreaHeight - 40)));
DC.Close();
PD.PrintVisual(DV, "TEST");
//}
}
Try doing a Measure, Arrange, and UpdateLayout right before the printvisual, like this:
DV.Measure(new System.Windows.Size(PD.PrintableAreaWidth,
PD.PrintableAreaHeight));
DV.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0),
DV.DesiredSize));
DV.UpdateLayout();
PD.PrintVisual(DV, "TEST");
i try to print out the content of my editor:
PrintDialog pd = new PrintDialog();
pd.PageRangeSelection = PageRangeSelection.AllPages;
pd.UserPageRangeEnabled = true;
FlowDocument fd = DocumentPrinter.CreateFlowDocumentForEditor(CurrentDocument.Editor);
DocumentPaginator dp = ((IDocumentPaginatorSource)fd).DocumentPaginator;
bool? res = pd.ShowDialog();
if (res.HasValue && res.Value)
{
fd.PageHeight = pd.PrintableAreaHeight;
fd.PageWidth = pd.PrintableAreaWidth;
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;
pd.PrintDocument(dp, CurrentDocument.Editor.FileName);
}
The test-document i used has about 14 pages (with this pagesize-settings).
i tested it: the printdialog appears and I´ve chosen a pagerange (i typed "1-3" into the textbox) and clicked print. above the printdocument() I set a breakpoint and looked into the printdialog-object. it says pd.PageRangeSelection = PageRangeSelection.UserPage and pd.PageRange = {1-3}. I guess this is right, because I wanted to print out only page 1-3. then the printdocument() executed and in the output-pdf (for testing I use a pdf-printer) has 14 pages (the whole document was printed).
where is my mistake? why does the pagerange-setting not work?
thanks for your help
In your code you manually set:
pd.PageRangeSelection = PageRangeSelection.AllPages;
This is why your code prints all the pages.
The reason for this is because FlowDocument's DocumentPaginator does not handle UserPageRanges. You can see that FlowDocument implementation creates a FlowDocumentPaginator, and it doesn't take into account ranges.
If it did handle it, in FlowDocumentPaginator.(Async)GetPage you would see, code checking to see if the page requested to be printed is in an index of available pages; or maybe if a key exists in a Dictionary whose value is the DocumentPage to print.
In other words, and the reason the PrintDialog default has UserPageRangeEnabled set to false, is because in order to use that feature, you'll usually have to write your own DocumentPaginator or you have to add some logic to compile a new temporary document to hold only the pages you want to print.
Feel free to ask any questions.