/// <summary> /// Prints the card layout to the default printer /// </summary> private void btnPrint_Click(object sender, RoutedEventArgs e) { PrintLayout layout = new PrintLayout(); double videoWidth = CameraVideoDeviceControl.ActualWidth * WebcamDevice.thisDpiWidthFactor; double videoHeight = CameraVideoDeviceControl.ActualHeight * WebcamDevice.thisDpiHeightFactor; double imageWidth = layout.ImageToPrint.Width; double imageHeight = layout.ImageToPrint.Height; double widthRatio = videoWidth / imageWidth; double heightRatio = videoHeight / imageHeight; PrintDialog printDialog = new PrintDialog(); // Set image and adjust to new size layout.ImageToPrint.Source = OutputImage.Source; // Add face markers if (RecognizedFaces != null && RecognizedFaces.Length > 0) { int index = 0; foreach (var face in RecognizedFaces) { // Draw rectangles around faces FaceMarker fm = new FaceMarker(face.Attributes.Age.ToString(), face.Attributes.Gender); fm.Height = Math.Round(face.FaceRectangle.Height / heightRatio); fm.Width = Math.Round(face.FaceRectangle.Width / widthRatio); layout.FaceCanvas.Children.Add(fm); fm.HairlineColor = brushList[index]; Canvas.SetZIndex(fm, 1); Canvas.SetTop(fm, Math.Round(face.FaceRectangle.Top / heightRatio)); Canvas.SetLeft(fm, Math.Round(face.FaceRectangle.Left / widthRatio)); } } // Get printer settings and adjust to page size TransformGroup transGroup = new TransformGroup(); layout.CardToPrint.LayoutTransform = transGroup; System.Printing.PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket); transGroup.Children.Add(new ScaleTransform(capabilities.PageImageableArea.ExtentWidth / layout.CardToPrint.Width, capabilities.PageImageableArea.ExtentHeight / layout.CardToPrint.Height)); layout.CardToPrint.LayoutTransform = transGroup; Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); layout.CardToPrint.Measure(sz); layout.CardToPrint.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz)); // Print card layout printDialog.PrintVisual(layout.CardToPrint, "Results"); }
/// <summary> /// Print the current window ass best fit for a page /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintScreen_Button_Click(object sender, RoutedEventArgs e) { PrintDialog printDlg = new System.Windows.Controls.PrintDialog(); printDlg.PrintTicket.PageOrientation = PageOrientation.Landscape; 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, "Wpf controller"); } }
/// <summary> /// Prints this instance. /// </summary> public bool Print() { try { PrintDialog printDlg = new System.Windows.Controls.PrintDialog(); bool? results = printDlg.ShowDialog(); if (results == null || results == false) { return(false); } //get selected printer capabilities System.Printing.PrintCapabilities capabilities = printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket); //get the size of the printer page System.Windows.Size printSize = new System.Windows.Size( capabilities.PageImageableArea.ExtentHeight, capabilities.PageImageableArea.ExtentWidth); // Build print view this.Height = printSize.Height; this.Width = printSize.Width; Measure(printSize); Arrange(new System.Windows.Rect(printSize)); XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(printDlg.PrintQueue); printDlg.PrintTicket.PageOrientation = PageOrientation.Landscape; xpsdw.WriteAsync(this); } catch (Exception ex) { MessageBox.Show(ex.GetBaseException().Message, "Printing Error", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } return(true); }
private void _print() { try { PrintDialog printDlg = new System.Windows.Controls.PrintDialog(); printDlg.PrintTicket.PageMediaSize = new PageMediaSize((Double)395.0, (Double)220.0); //printDlg.ShowDialog(); //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.Width, capabilities.PageImageableArea.ExtentHeight / this.Height); //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, "BoxSlip_KrausUSA_A"); } catch (Exception) { } }
public static Visual Print(Visual v, bool canReturn = false) { try { System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement; if (e == null) { return(null); } PrintDialog pd = new PrintDialog(); bool?determiner = true; if (!canReturn) { determiner = pd.ShowDialog(); } if ((bool)determiner) { //store original scale Transform originalScale = e.LayoutTransform; //get selected printer capabilities System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket); //get scale of the print wrt to screen of WPF visual //double x = capabilities.PageImageableArea.ExtentWidth / e.ActualWidth; //double y = capabilities.PageImageableArea.ExtentHeight / e.ActualHeight; double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / e.ActualWidth, capabilities.PageImageableArea.ExtentHeight / e.ActualHeight); //Transform the Visual to scale e.LayoutTransform = new ScaleTransform(scale, scale); // e.LayoutTransform = new ScaleTransform(x, y); //get the size of the printer page System.Windows.Size sz = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); //update the layout of the visual to the printer page size. e.Measure(sz); e.Arrange(new System.Windows.Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz)); //now print the visual to printer to fit on the one page. if (!canReturn) { pd.PrintVisual(v, "My Print"); //apply the original transform. e.LayoutTransform = originalScale; MessageBox.Show("Printing SuccessFul", "Operation Successful", MessageBoxButton.OK, MessageBoxImage.Information); } } if (canReturn) { return(v); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(null); }
/// <summary> /// Gets the PrintCapabilities relative to the given PrintTicket. /// </summary> /// <param name="printTicket">The PrintTicket object based on which PrintCapabilities should be built.</param> /// <returns>The PrintCapabilities object.</returns> /// <remarks> /// The <paramref name="printTicket"/> parameter could be null, in which case /// the device's default PrintTicket will be used to construct the PrintCapabilities. /// </remarks> /// <exception cref="ObjectDisposedException"> /// The PrintTicketManager instance has already been disposed. /// </exception> /// <exception cref="ArgumentException"> /// The input PrintTicket specified by <paramref name="printTicket"/> is not well-formed. /// </exception> /// <exception cref="PrintQueueException"> /// The PrintTicketManager instance failed to retrieve the PrintCapabilities. /// </exception> public PrintCapabilities GetPrintCapabilities(PrintTicket printTicket) { MemoryStream pcStream = GetPrintCapabilitiesAsXml(printTicket); PrintCapabilities retCap = new PrintCapabilities(pcStream); pcStream.Close(); return(retCap); }
public static void alloPrint(object sender) { // Visual v = sender as Visual; // Visual v = song2Grid as Visual; // the object (it is a DataGrid) that you want to print out, not a window PrintDialog prtDlg = new PrintDialog(); if (prtDlg.ShowDialog() == true) { // because 96 pixels in an inch for WPF window double marginLeft = 96.0 * 0.75; // left margin is 0.75 inches double marginTop = 96.0 * 0.75; // top margin is 0.75 inches double marginRight = 96.0 * 0.75; // right margin is 0.75 inches double marginBottom = 96.0 * 0.75; // bottom margin is 0.75 inches // the following steps do not works for a WPF window FrameworkElement win = v as FrameworkElement; Transform oldLayoutTransform = win.LayoutTransform; Size oldSize = new Size(win.ActualWidth, win.ActualHeight); System.Printing.PrintCapabilities pCapability = prtDlg.PrintQueue.GetPrintCapabilities(prtDlg.PrintTicket); // calculate print area that you want double printWidth = (pCapability.PageImageableArea.ExtentWidth - pCapability.PageImageableArea.OriginWidth) - (marginLeft + marginRight); double printHeight = (pCapability.PageImageableArea.ExtentHeight - pCapability.PageImageableArea.OriginHeight) - (marginTop + marginBottom); // calculate the scale double scale = Math.Min(printWidth / oldSize.Width, printHeight / oldSize.Height); if (scale > 1.0) { // keep the original size and layout if printable area is greater than the object being printed scale = 1.0; } // store the original layoutTransform win.LayoutTransform = new ScaleTransform(scale, scale); // new size of the visual Size newSize = new Size(oldSize.Width * scale, oldSize.Height * scale); win.Measure(newSize); // centralize print area double xStartPrint = marginLeft + (printWidth - newSize.Width) / 2.0; double yStartPrint = marginTop + (printHeight - newSize.Height) / 2.0; win.Arrange(new Rect(new Point(xStartPrint, yStartPrint), newSize)); // print out the visual prtDlg.PrintVisual(win as Visual, "PrintTest"); // resotre the original layouttransform and size on screen win.LayoutTransform = oldLayoutTransform; win.Measure(oldSize); win.Arrange(new Rect(new Point(0, 0), oldSize)); } }
private void Button_Click(object sender, RoutedEventArgs e) { var viewModel = new PrintableUserControlViewModel(int.Parse(((ComboBoxItem)NumberOfLabelsToPrint.SelectedValue).Content.ToString()), (bool)FitToPage.IsChecked, (bool)NeedToShowDialog.IsChecked); for (int labelIndex = 0; labelIndex < viewModel.NumberOfLabelsToPrint; ++labelIndex) { viewModel.LabelViewModels[labelIndex].Text1 = string.Format("test{0}.1", labelIndex + 1); viewModel.LabelViewModels[labelIndex].Text2 = string.Format("test{0}.2", labelIndex + 1); viewModel.LabelViewModels[labelIndex].Text3 = string.Format("test{0}.3", labelIndex + 1); } var view = new PrintableUserControl(viewModel); PrintDialog printDialog = new PrintDialog(); bool printDialogResult = true; if (viewModel.NeedToShowDialog) { printDialogResult = printDialog.ShowDialog() ?? false; } else { printDialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue(); // can also select one of new PrintServer().GetPrintQueues(); printDialog.PrintTicket.CopyCount = 1; // number of copies printDialog.PrintTicket.PageOrientation = PageOrientation.Portrait; } if (viewModel.FitToPage) { //get selected printer capabilities System.Printing.PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket); //get scale of the printer to that of WPF control double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / view.ActualWidth, capabilities.PageImageableArea.ExtentHeight / view.ActualHeight); //Scare the control for printing size view.LayoutTransform = new ScaleTransform(scale, scale); Size sizeOfPrinterPage = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); //Update the layout of the control to the size of the printer page view.Measure(sizeOfPrinterPage); view.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sizeOfPrinterPage)); } //print the control to printer printDialog.PrintVisual(view, "Print title"); }
public static void Print(FixedPage page)//, string pageName { //page.UpdateLayout(); PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); //FixedPage若直接打印,则打印出来的内容为空白,因为height为0 //推测原因:没有render //但先保存为文件,或加载到FixedDocument中就能打印,奇怪 #region System.Printing.PrintCapabilities capabilities = defaultPrintQueue.GetPrintCapabilities(); FixedDocument document = new FixedDocument(); document.DocumentPaginator.PageSize = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); PageContent content = new PageContent(); ((IAddChild)content).AddChild(page); document.Pages.Add(content); #endregion #region 根据打印机打印区域缩放page大小 //System.Printing.PrintCapabilities capabilities = defaultPrintQueue.GetPrintCapabilities(); ////get scale of the print wrt to screen of WPF visual //double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / page.ActualWidth, capabilities.PageImageableArea.ExtentHeight / page.ActualHeight); ////Transform the Visual to scale //page.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. //page.Measure(sz); //page.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz)); #endregion try { //string path = SaveXPS(page, pageName); //PrintSystemJobInfo xpsPringtJob = defaultPrintQueue.AddJob(pageName + ".xps", path, true); XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(defaultPrintQueue);//如此会自动帮我们判定上面AddJob方法的第三个参数 xpsdw.Write(document); } catch (Exception e) { MessageBox.Show("打印失败,失败原因:" + e.Message); } finally { defaultPrintQueue.Dispose(); } }
void Print(PageItem Page) { try { Page.IsGridVisible = false; Page.IsPrinting = true; ContentControl cc = new ContentControl(); cc.ContentTemplate = this.FindResource("LogicPageItemTemplate1") as DataTemplate; cc.Content = Page; PrintDialog dlg = new System.Windows.Controls.PrintDialog(); dlg.PrintQueue = LocalPrintServer.GetDefaultPrintQueue(); dlg.PrintTicket = dlg.PrintQueue.DefaultPrintTicket; dlg.PrintTicket.PageOrientation = PageOrientation.Landscape; dlg.PrintTicket.OutputQuality = OutputQuality.High; //dlg.PrintTicket.OutputColor = OutputColor.Monochrome; dlg.PrintTicket.TrueTypeFontMode = TrueTypeFontMode.DownloadAsNativeTrueTypeFont; Nullable <bool> result = dlg.ShowDialog(); if (result == true) { System.Printing.PrintCapabilities capabilities = dlg.PrintQueue.GetPrintCapabilities(dlg.PrintTicket); double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / UnitConverter.CmToDip(42.0), capabilities.PageImageableArea.ExtentHeight / UnitConverter.CmToDip(29.7)); cc.LayoutTransform = new ScaleTransform(scale, scale); Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); cc.Measure(sz); cc.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz)); cc.UpdateLayout(); dlg.PrintVisual(cc, "Page"); } Page.IsGridVisible = true; Page.IsPrinting = false; } catch (Exception ex) { Debug.Print(ex.Message); } }
static void Main(string[] args) { string printerName = ""; string filePath = ""; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("/P") && i + 1 < args.Length) { printerName = args[i + 1]; } else if (args[i].Equals("/F") && i + 1 < args.Length) { filePath = args[i + 1]; } } PrintQueue queue = null; if (printerName.Equals(String.Empty)) { queue = LocalPrintServer.GetDefaultPrintQueue(); } else { queue = new PrintQueue(new System.Printing.PrintServer(), printerName); } System.Printing.PrintCapabilities printcap = queue.GetPrintCapabilities(); var ms = queue.GetPrintCapabilitiesAsXml(queue.UserPrintTicket); if (filePath.Equals(String.Empty)) { filePath = "C:\\Temp\\Caps.xml"; } FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write); ms.WriteTo(file); file.Close(); ms.Close(); }
/// <summary> /// Print visual object fit to page. /// </summary> /// <param name="printDialog"></param> /// <param name="project"></param> /// <param name="grid"></param> /// <see>http://www.a2zdotnet.com/View.aspx?id=66</see> private void PrintFitToPage(PrintDialog printDialog, Project project, Grid grid) { System.Printing.PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket); //get scale of the print wrt to screen of WPF visual double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / grid.ActualWidth, capabilities.PageImageableArea.ExtentHeight / grid.ActualHeight); //Transform the Visual to scale grid.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. grid.Measure(sz); grid.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz)); //now print the visual to printer to fit on the one page. printDialog.PrintVisual(grid, project.Guid.ToString());//Fit to Page WPF Print }
private PageContent generatePageContent(System.Drawing.Bitmap bmp, int top, int bottom, double pageWidth, double PageHeight, System.Printing.PrintCapabilities capabilities) { FixedPage printDocumentPage = new FixedPage(); printDocumentPage.Width = pageWidth; printDocumentPage.Height = PageHeight; int newImageHeight = bottom - top; System.Drawing.Bitmap bmpPage = bmp.Clone(new System.Drawing.Rectangle(0, top, bmp.Width, newImageHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb); // Create a new bitmap for the contents of this page Image pageImage = new Image(); BitmapSource bmpSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPage.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, newImageHeight)); pageImage.Source = bmpSource; pageImage.VerticalAlignment = VerticalAlignment.Top; // Place the bitmap on the page printDocumentPage.Children.Add(pageImage); PageContent pageContent = new PageContent(); ((System.Windows.Markup.IAddChild)pageContent).AddChild(printDocumentPage); FixedPage.SetLeft(pageImage, capabilities.PageImageableArea.OriginWidth); FixedPage.SetTop(pageImage, capabilities.PageImageableArea.OriginHeight); pageImage.Width = capabilities.PageImageableArea.ExtentWidth; pageImage.Height = capabilities.PageImageableArea.ExtentHeight; return(pageContent); }
public static void Print1(FrameworkElement visual, bool applyRtl = true) { var 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 / visual.ActualWidth, capabilities.PageImageableArea.ExtentHeight / visual.ActualHeight); var oldTransfomr = visual.LayoutTransform?.Clone(); if (applyRtl) { //Transform the Visual to scale visual.LayoutTransform = new ScaleTransform(-scale, scale); } else { //Transform the Visual to scale visual.LayoutTransform = new ScaleTransform(scale, scale); } //get the size of the printer page Size size = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); //update the layout of the visual to the printer page size. visual.Measure(size); visual.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), size)); //now print the visual to printer to fit on the one page. printDlg.PrintVisual(visual, "A1"); visual.LayoutTransform = oldTransfomr; } }
private void print_report_Click(object sender, RoutedEventArgs e) { //Create PrintDialog object PrintDialog printDlg = new System.Windows.Controls.PrintDialog(); //Get layout of UserControl Transform originalScale = this.LayoutTransform; 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 / dgUsers.ActualWidth, capabilities.PageImageableArea.ExtentHeight / dgUsers.ActualHeight); //Transform the Visual to scale dgUsers.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. dgUsers.Measure(sz); dgUsers.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(dgUsers, "דוח"); //Returns layout frame to original size dgUsers.LayoutTransform = originalScale; }
public static Task <DocumentPaginator> PrintOnMultiPage(object parameter, bool canReturn = false) { return(Task.Run(() => { if (parameter is FrameworkElement) { FrameworkElement objectToPrint = parameter as FrameworkElement; FixedDocument document = null; objectToPrint.Dispatcher.BeginInvoke(new Action(() => { Transform originalScale = objectToPrint.LayoutTransform; PrintDialog printDialog = new PrintDialog(); var determiner = true; if (!canReturn) { determiner = (bool)printDialog.ShowDialog().GetValueOrDefault(); } if (determiner) { // Mouse.OverrideCursor = Cursors.Wait; System.Printing.PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket); double dpiScale = 200.0 / 96.0; document = new FixedDocument(); try { // Change the layout of the UI Control to match the width of the printer page double scale = capabilities.PageImageableArea.ExtentWidth / objectToPrint.ActualWidth; objectToPrint.LayoutTransform = new ScaleTransform(scale, scale); // objectToPrint.Width = capabilities.PageImageableArea.ExtentWidth ; objectToPrint.UpdateLayout(); objectToPrint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); Size size = new Size(capabilities.PageImageableArea.ExtentWidth, objectToPrint.DesiredSize.Height); objectToPrint.Measure(size); //size = new Size(capabilities.PageImageableArea.ExtentWidth, objectToPrint.DesiredSize.Height); //objectToPrint.Measure(size); objectToPrint.Arrange(new Rect(size)); // Convert the UI control into a bitmap at 300 dpi double dpiX = 200; double dpiY = 200; RenderTargetBitmap bmp = new RenderTargetBitmap(Convert.ToInt32(capabilities.PageImageableArea.ExtentWidth * dpiScale), Convert.ToInt32(objectToPrint.ActualHeight * dpiScale), dpiX, dpiY, PixelFormats.Pbgra32); bmp.Render(objectToPrint); // Convert the RenderTargetBitmap into a bitmap we can more readily use PngBitmapEncoder png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(bmp)); System.Drawing.Bitmap bmp2; using (MemoryStream memoryStream = new MemoryStream()) { png.Save(memoryStream); bmp2 = new System.Drawing.Bitmap(memoryStream); } document.DocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); // break the bitmap down into pages int pageBreak = 0; int previousPageBreak = 0; int pageHeight = Convert.ToInt32(capabilities.PageImageableArea.ExtentHeight * dpiScale); while (pageBreak < bmp2.Height - pageHeight) { pageBreak += pageHeight; // Where we thing the end of the page should be // Keep moving up a row until we find a good place to break the page while (!IsRowGoodBreakingPoint(bmp2, pageBreak)) { pageBreak--; } PageContent pageContent = generatePageContent(bmp2, previousPageBreak, pageBreak, document.DocumentPaginator.PageSize.Width, document.DocumentPaginator.PageSize.Height, capabilities); document.Pages.Add(pageContent); previousPageBreak = pageBreak; } // Last Page PageContent lastPageContent = generatePageContent(bmp2, previousPageBreak, bmp2.Height, document.DocumentPaginator.PageSize.Width, document.DocumentPaginator.PageSize.Height, capabilities); document.Pages.Add(lastPageContent); } catch { // MessageBox.Show(ex.Message, "An Error Occured"); } finally { if (!canReturn) { printDialog.PrintDocument(document.DocumentPaginator, "Print Document Name"); MessageBox.Show("Printing SuccessFul", "Operation Successful", MessageBoxButton.OK, MessageBoxImage.Information); } // Scale UI control back to the original so we don't effect what is on the screen //objectToPrint.Width = double.NaN; //objectToPrint.UpdateLayout(); objectToPrint.LayoutTransform = originalScale; Size size = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); objectToPrint.Measure(size); objectToPrint.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), size)); // Mouse.OverrideCursor = null; } } })); if (!canReturn) { return null; } return document.DocumentPaginator; } return null; })); }
private void butPrintInfo_Click(object sender, EventArgs e) { System.Printing.LocalPrintServer theServer; theServer = new System.Printing.LocalPrintServer(); System.Printing.EnumeratedPrintQueueTypes[] myEnum = { EnumeratedPrintQueueTypes.Connections , EnumeratedPrintQueueTypes.Local }; System.Printing.PrintQueueCollection col = theServer.GetPrintQueues(myEnum); foreach (System.Printing.PrintQueue qit in col) { System.Diagnostics.Debug.WriteLine(qit.ClientPrintSchemaVersion); System.Diagnostics.Debug.WriteLine(qit.Comment); System.Diagnostics.Debug.WriteLine(qit.CurrentJobSettings.Description); System.Diagnostics.Debug.WriteLine(qit.Description); System.Diagnostics.Debug.WriteLine(qit.FullName); System.Printing.PrintCapabilities pc = qit.GetPrintCapabilities(); System.Diagnostics.Debug.WriteLine(pc.InputBinCapability.ToString()); System.Diagnostics.Debug.WriteLine(pc.MaxCopyCount); System.Diagnostics.Debug.WriteLine(pc.OrientedPageMediaHeight); System.Diagnostics.Debug.WriteLine(pc.OrientedPageMediaWidth); System.Diagnostics.Debug.WriteLine(pc.PageBorderlessCapability); System.Diagnostics.Debug.WriteLine(qit.QueueAttributes.ToString()); System.Diagnostics.Debug.WriteLine(qit.ShareName); System.Diagnostics.Debug.WriteLine(qit.QueueDriver.PropertiesCollection.ToString()); System.IO.MemoryStream str = qit.GetPrintCapabilitiesAsXml(); System.IO.StreamReader tr = new System.IO.StreamReader(str); String line; while ((line = tr.ReadLine()) != null) { System.Diagnostics.Debug.WriteLine(line); } foreach (DictionaryEntry entry in qit.PropertiesCollection) { PrintProperty prop; prop = (PrintProperty)entry.Value; if (prop.Value != null) { System.Diagnostics.Debug.WriteLine("Name " + prop.Name + " value " + prop.Value); } } } //System.Drawing.Printing.PaperKind.A4; //System.Printing.PrintDriver; //System.Printing.PrintJobSettings; //System.Printing.PrintDocumentImageableArea; //System.Printing.PrintDriver; //System.Printing.PrintJobStatus; //System.Printing.PrintQueue; //System.Printing.PrintQueueStringProperty; //System.Drawing.Printing.PrinterSettings; System.Drawing.Printing.PrinterSettings ps; ps = new System.Drawing.Printing.PrinterSettings(); ps.PrinterName = cmbPrinters.Text; System.Drawing.Printing.PrinterSettings.PaperSizeCollection papers; papers = ps.PaperSizes; foreach (System.Drawing.Printing.PaperSize ps2 in papers) { System.Diagnostics.Debug.WriteLine(ps2.PaperName + " " + ps2.Kind.ToString() + " " + ps2.Height.ToString() + " " + ps2.Width.ToString()); } }
/// <summary>Prints the FrameworkElement.</summary> /// <param name="fe">The FrameworkElement.</param> public static void Print(this FrameworkElement fe) { PrintDialog pd = new PrintDialog(); bool?result = pd.ShowDialog(); pd.PrintTicket.PageOrientation = PageOrientation.Portrait; if (!result.HasValue || !result.Value) { return; } System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket); try { fe.Dispatcher.Invoke(new Action(() => { //fe.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); //fe.Arrange(new Rect(fe.DesiredSize)); //fe.UpdateLayout(); // Change the layout of the UI Control to match the width of the printer page fe.Width = capabilities.PageImageableArea.ExtentWidth; fe.UpdateLayout(); fe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); Size size = new Size(capabilities.PageImageableArea.ExtentWidth, fe.DesiredSize.Height); fe.Measure(size); size = new Size(capabilities.PageImageableArea.ExtentWidth, fe.DesiredSize.Height); fe.Measure(size); fe.Arrange(new Rect(size)); }), System.Windows.Threading.DispatcherPriority.Render); int height = (int)pd.PrintTicket.PageMediaSize.Height; int width = (int)pd.PrintTicket.PageMediaSize.Width; int pages = (int)Math.Ceiling((fe.ActualHeight / height)); FixedDocument document = new FixedDocument(); for (int i = 0; i < pages; i++) { FixedPage page = new FixedPage(); page.Height = height; page.Width = width; page.PrintTicket = pd.PrintTicket; PageContent content = new PageContent(); content.Child = page; document.DocumentPaginator.PageSize = new Size(pd.PrintableAreaWidth + 50, pd.PrintableAreaHeight); document.Pages.Add(content); VisualBrush vb = new VisualBrush(fe); vb.AlignmentX = AlignmentX.Left; vb.AlignmentY = AlignmentY.Top; vb.Stretch = Stretch.None; vb.TileMode = TileMode.None; vb.Viewbox = new Rect(-11, i * height, width + 10, (i + 1) * height); vb.ViewboxUnits = BrushMappingMode.Absolute; RenderOptions.SetBitmapScalingMode(vb, BitmapScalingMode.Fant); Canvas canvas = new Canvas(); canvas.Background = vb; canvas.Height = height; canvas.Width = width; //FixedPage.SetLeft(canvas, 0); FixedPage.SetTop(canvas, 25); page.Children.Add(canvas); } pd.PrintDocument(document.DocumentPaginator, ((String.IsNullOrWhiteSpace(fe.Name) ? "Temp" : fe.Name) + " PRINT")); } finally { //// Scale UI control back to the original so we don't effect what is on the screen //fe.Width = double.NaN; //fe.UpdateLayout(); //fe.LayoutTransform = new ScaleTransform(1, 1); //Size size = new Size(capabilities.PageImageableArea.ExtentWidth, // capabilities.PageImageableArea.ExtentHeight); //fe.Measure(size); //fe.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, // capabilities.PageImageableArea.OriginHeight), size)); Mouse.OverrideCursor = null; } }