/// <summary> /// Get a print dialog, defaulted to default printer and default printer's preferences. /// </summary> protected override void OnPrintCommand() { // get a print dialog, defaulted to default printer and default printer's preferences. PrintDialog printDialog = new PrintDialog(); printDialog.PrintQueue = mPrintQueue; printDialog.PrintTicket = mPrintTicket; if (printDialog.ShowDialog() == true) { mPrintQueue = printDialog.PrintQueue; mPrintTicket = printDialog.PrintTicket; printDialog.PrintDocument(this.Document.DocumentPaginator, "PrintPreviewJob"); } }
public CloudPrinterImpl(PrintQueue queue) { PrintTicket defaults = queue.DefaultPrintTicket.Clone(); defaults.OutputColor = OutputColor.Monochrome; defaults.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4); this.Name = queue.FullName; this.Description = queue.Description; this.Capabilities = XDocument.Load(queue.GetPrintCapabilitiesAsXml()).ToString(); this.Defaults = new StreamReader(defaults.GetXmlStream(), Encoding.UTF8, false).ReadToEnd(); this.CapsHash = GetMD5Hash(Encoding.UTF8.GetBytes(Capabilities)); PrinterConfigurationSection printerconfigs = Config.PrinterConfigurationSection; if (printerconfigs != null) { this.PrinterConfiguration = printerconfigs.Printers.OfType<PrinterConfiguration>().SingleOrDefault(p => p.Name == this.Name); if (this.PrinterConfiguration != null) { this.JobPrinterType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.Name == this.PrinterConfiguration.JobPrinter && typeof(JobPrinter).IsAssignableFrom(t))).SingleOrDefault(); } else { this.JobPrinterType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.Name == printerconfigs.DefaultJobPrinter && typeof(JobPrinter).IsAssignableFrom(t))).SingleOrDefault(); } } if (this.JobPrinterType == null) { this.JobPrinterType = PrinterConfiguration.DefaultJobPrinterType; } }
internal static void PrintFlowDocument(PrintQueue pq, FlowDocument flowDocument) { if (pq == null) return; // Create a XpsDocumentWriter object, open a Windows common print dialog. // This methods returns a ref parameter that represents information about the dimensions of the printer media. XpsDocumentWriter docWriter = PrintQueue.CreateXpsDocumentWriter(pq); PageImageableArea ia = pq.GetPrintCapabilities().PageImageableArea; PrintTicket pt = pq.UserPrintTicket; if (ia != null) { DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator; // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device. paginator.PageSize = new Size((double)pt.PageMediaSize.Width, (double)pt.PageMediaSize.Height); Thickness pagePadding = flowDocument.PagePadding; flowDocument.PagePadding = new Thickness( Math.Max(ia.OriginWidth, pagePadding.Left), Math.Max(ia.OriginHeight, pagePadding.Top), Math.Max((double)pt.PageMediaSize.Width - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right), Math.Max((double)pt.PageMediaSize.Height - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom)); flowDocument.ColumnWidth = double.PositiveInfinity; // Send DocumentPaginator to the printer. docWriter.Write(paginator); } }
/// <summary> /// Invokes a System.Windows.Controls.PrintDialog to print the TextEditor.Document with specified title. /// </summary> public static void PrintDialog(this TextEditor textEditor, string title) { Printing.mDocumentTitle = title; Printing.InitPageSettings(); System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog(); printDialog.PrintQueue = mPrintQueue; if (mPageSettings.Landscape) Printing.mPrintTicket.PageOrientation = PageOrientation.Landscape; printDialog.PrintTicket = mPrintTicket; printDialog.PrintQueue.DefaultPrintTicket.PageOrientation = mPrintTicket.PageOrientation; if (printDialog.ShowDialog() == true) { Printing.mPrintQueue = printDialog.PrintQueue; Printing.mPrintTicket = printDialog.PrintTicket; printDialog.PrintDocument(CreateDocumentPaginatorToPrint(textEditor), "PrintJob"); } }
/// <summary> /// Ensure Queue and Ticket prepared /// </summary> private void VerifyPrintSettings() { if (mPrintQueue == null) mPrintQueue = DefaultPrintQueue(); if (mPrintTicket == null) mPrintTicket = DefaultPrintTicket(); }
/// <summary> /// https://blogs.msdn.microsoft.com/prajakta/2007/01/02/printing-contents-of-wpf-richtextbox/ /// を参考にした。感謝したい。 /// もう少し余白を空けたい。 /// </summary> private void PrintRichTextContent() { var sourceDocument = new TextRange(richTextBox_Body.Document.ContentStart, richTextBox_Body.Document.ContentEnd); var memstrm = new MemoryStream(); //flowDocumentを複製するために、一度MemoryStreamに書き込んでいる。 sourceDocument.Save(memstrm, DataFormats.XamlPackage); var flowDocumentCopy = new FlowDocument(); var copyDocumentRange = new TextRange(flowDocumentCopy.ContentStart, flowDocumentCopy.ContentEnd); //MemoryStreamから読み込み copyDocumentRange.Load(memstrm, DataFormats.XamlPackage); PrintDocumentImageableArea ia = null; var docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia); if (docWriter != null && ia != null) { var paginator = ((IDocumentPaginatorSource)flowDocumentCopy).DocumentPaginator; paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight); //var pagePadding = flowDocumentCopy.PagePadding; ////pagePaddingの中身がNaNになっている場合があるので、その場合はNaNを0とする。 //if (double.IsNaN(pagePadding.Left)) // pagePadding.Left = 0; //if (double.IsNaN(pagePadding.Top)) // pagePadding.Top = 0; //if (double.IsNaN(pagePadding.Right)) // pagePadding.Right = 0; //if (double.IsNaN(pagePadding.Bottom)) // pagePadding.Bottom = 0; //flowDocumentCopy.PagePadding = new Thickness( // Math.Max(ia.OriginWidth, pagePadding.Left), // Math.Max(ia.OriginHeight, pagePadding.Top), // Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right), // Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom) // ); flowDocumentCopy.PagePadding = new Thickness(50, 50, 50, 50); flowDocumentCopy.ColumnWidth = double.PositiveInfinity; docWriter.Write(paginator); } }
public ManualDuplex(FixedDocument document, PrintQueue printer, bool collated, int copies) { Document = document; Printer = printer; Collated = collated; Copies = copies; Print(); }
//Prints a FixedDocument public void PrintFixedDocument(PrintQueue printQueue) { FixedDocument fixedDocument = GetFixedDocument(); XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printQueue); writer.Write(fixedDocument); }
private void SetMsg(PrintQueue queue, string msg) { string stat = "Статус: "; string name = "Имя принтера: "; around.printerMessage.text1msg.Text = msg; around.printerMessage.text2stat.Text = $"{stat}{queue?.QueueStatus}".Replace("TonerLow", "IsReady"); around.printerMessage.text3name.Text = $"{name}{queue?.FullName}"; }
/// <summary> /// Writes <paramref name="documentPaginatorSource"/> to the printer. /// </summary> /// <param name="xpsPrinterDefinition"/> /// <param name="documentPaginatorSource"/> /// <param name="printTicketFactory"/> /// <exception cref="T:System.ArgumentNullException"><paramref name="xpsPrinterDefinition"/> is <see langword="null"/>.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="documentPaginatorSource"/> is <see langword="null"/>.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="printTicketFactory"/> is <see langword="null"/>.</exception> /// <exception cref="T:System.InvalidOperationException"/> /// <exception cref="T:System.Exception"/> public static void Print([NotNull] this IXpsPrinterDefinition xpsPrinterDefinition, [NotNull] IDocumentPaginatorSource documentPaginatorSource, [NotNull][InstantHandle] PrintTicketFactory printTicketFactory) { if (xpsPrinterDefinition == null) { throw new ArgumentNullException(nameof(xpsPrinterDefinition)); } if (documentPaginatorSource == null) { throw new ArgumentNullException(nameof(documentPaginatorSource)); } if (printTicketFactory == null) { throw new ArgumentNullException(nameof(printTicketFactory)); } using (var printServer = new PrintServer(xpsPrinterDefinition.Host)) { PrintQueue printQueue; try { printQueue = printServer.GetPrintQueue(xpsPrinterDefinition.Name); } catch (PrintQueueException printQueueException) { throw new InvalidOperationException($"Failed to get print queue '{xpsPrinterDefinition.Name}' on '{xpsPrinterDefinition.Host}'", printQueueException); } using (printQueue) { var xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printQueue); var printTicket = printTicketFactory.Invoke(printQueue); if (documentPaginatorSource is FixedDocumentSequence fixedDocumentSequence) { fixedDocumentSequence.PrintTicket = printTicket; xpsDocumentWriter.Write(fixedDocumentSequence, printTicket); } else if (documentPaginatorSource is FixedDocument fixedDocument) { fixedDocument.PrintTicket = printTicket; xpsDocumentWriter.Write(fixedDocument, printTicket); } else { xpsDocumentWriter.Write(documentPaginatorSource.DocumentPaginator, printTicket); } } } }
private void cmdPauseJob_Click(object sender, RoutedEventArgs e) { if (lstJobs.SelectedValue != null) { PrintQueue queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString()); PrintSystemJobInfo job = queue.GetJob((int)lstJobs.SelectedValue); job.Pause(); } }
public static void Add(List <PrintQueue> queue, ConsoleColor color, string spec, string message) { PrintQueue data = new PrintQueue(); data.m_color = color; data.m_message = message; data.m_spec = spec; queue.Add(data); }
UpdatePrintableAreaSize( ) { PrintQueue printQueue = null; PrintTicket printTicket = null; PickCorrectPrintingEnvironment(ref printQueue, ref printTicket); PrintCapabilities printCap = null; if (printQueue != null) { printCap = printQueue.GetPrintCapabilities(printTicket); } // PrintCapabilities OrientedPageMediaWidth/Height are Nullable if ((printCap != null) && (printCap.OrientedPageMediaWidth != null) && (printCap.OrientedPageMediaHeight != null)) { _printableAreaWidth = (double)printCap.OrientedPageMediaWidth; _printableAreaHeight = (double)printCap.OrientedPageMediaHeight; } else { // Initialize page size to portrait Letter size. // This is our fallback if PrintTicket doesn't specify the page size. _printableAreaWidth = 816; _printableAreaHeight = 1056; // PrintTicket's PageMediaSize could be null and PageMediaSize Width/Height are Nullable if ((printTicket.PageMediaSize != null) && (printTicket.PageMediaSize.Width != null) && (printTicket.PageMediaSize.Height != null)) { _printableAreaWidth = (double)printTicket.PageMediaSize.Width; _printableAreaHeight = (double)printTicket.PageMediaSize.Height; } // If we are using PrintTicket's PageMediaSize dimensions to populate the widht/height values, // we need to adjust them based on current orientation. PrintTicket's PageOrientation is Nullable. if (printTicket.PageOrientation != null) { PageOrientation orientation = (PageOrientation)printTicket.PageOrientation; // need to swap width/height in landscape orientation if ((orientation == PageOrientation.Landscape) || (orientation == PageOrientation.ReverseLandscape)) { double t = _printableAreaWidth; _printableAreaWidth = _printableAreaHeight; _printableAreaHeight = t; } } } }
/* Main print entry point */ public void Print(PrintQueue queu, FixedDocumentSequence fixdoc) { XpsDocumentWriter docwrite = GetDocWriter(queu); m_busy = true; docwrite.WritingPrintTicketRequired += new WritingPrintTicketRequiredEventHandler(PrintTicket); PrintPages(docwrite, fixdoc); }
private void PrintBtn_Click(object sender, RoutedEventArgs e) { PrintBtn.IsEnabled = false; Printer printer = (Printer)PrintersCombo.SelectedItem; System.Windows.Xps.XpsDocumentWriter xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printer.PrintQueue); xpsDocumentWriter.WritingCompleted += XpsDocumentWriter_WritingCompleted; xpsDocumentWriter.WriteAsync(PreviewViewer.Document.DocumentPaginator); }
//**************************************************************************************** // Construction //**************************************************************************************** /// <summary> /// Constructor for printing /// </summary> /// <param name="printQueue"></param> /// <param name="printTicket"></param> public WpfPrint(PrintQueue printQueue, PrintTicket printTicket) { PrintCapabilities capabilities = printQueue.GetPrintCapabilities(printTicket); Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); _fixedDocument = new FixedDocument(); _fixedDocument.DocumentPaginator.PageSize = sz; StartPage(); }
public static void PrintXPS() { // Create print server and print queue. LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); // Prompt user to identify the directory, and then create the directory object. Console.Write("Enter the directory containing the XPS files: "); String directoryPath = Console.ReadLine(); DirectoryInfo dir = new DirectoryInfo(directoryPath); // If the user mistyped, end the thread and return to the Main thread. if (!dir.Exists) { Console.WriteLine("There is no such directory."); } else { // If there are no XPS files in the directory, end the thread // and return to the Main thread. if (dir.GetFiles("*.xps").Length == 0) { Console.WriteLine("There are no XPS files in the directory."); } else { Console.WriteLine("\nJobs will now be added to the print queue."); Console.WriteLine("If the queue is not paused and the printer is working, jobs will begin printing."); // Batch process all XPS files in the directory. foreach (FileInfo f in dir.GetFiles("*.xps")) { String nextFile = directoryPath + "\\" + f.Name; Console.WriteLine("Adding {0} to queue.", nextFile); try { // Print the Xps file while providing XPS validation and progress notifications. PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob(f.Name, nextFile, false); } catch (PrintJobException e) { Console.WriteLine("\n\t{0} could not be added to the print queue.", f.Name); if (e.InnerException.Message == "File contains corrupted data.") { Console.WriteLine("\tIt is not a valid XPS file. Use the isXPS Conformance Tool to debug it."); } Console.WriteLine("\tContinuing with next XPS file.\n"); } } } } Console.WriteLine("Press Enter to end program."); Console.ReadLine(); }
/// UpdateJobData #region UpdateJobData /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="printerName"></param> /// <param name="host"></param> /// <returns></returns> private static bool UpdateJobData(ref PrintJobData data, string printerName, string host) { bool updated = false; try { LogHelper.LogDebug("INNER START " + printerName); PrintQueue queue = GetPrintQueue(printerName, host); if (queue == null) { return(false); } queue.Refresh(); if (queue.NumberOfJobs > 0) { bool quit = false; while (!quit) { try { LogHelper.LogDebug("jobs " + queue.GetPrintJobInfoCollection().Count() + " | " + queue.NumberOfJobs); foreach (PrintSystemJobInfo info in queue.GetPrintJobInfoCollection()) { info.Refresh(); string docName = info.Name; int NumberOfPages = info.NumberOfPages; int xxx = info.NumberOfPagesPrinted; LogHelper.LogDebug("Printing " + info.IsPrinting + " | Paused " + info.IsPaused + " | Spooling " + info.IsSpooling + " | IsDeleting " + info.IsDeleting); LogHelper.LogDebug("pages " + NumberOfPages + " printed " + xxx); if (data.PrintJobTitle.Document == docName && data.PrintJobTitle.TotalPages < xxx) { data.PrintJobTitle.TotalPages = xxx; updated = true; } } quit = true; } catch (Exception ex) { queue.Refresh(); LogHelper.LogDebug("refresh"); WPFNotifier.Error(ex); } } } } catch (Exception ex) { WPFNotifier.Error(ex); } LogHelper.LogDebug("INNER END " + printerName); return(updated); }
private void PrintOnClick(object sender, RoutedEventArgs args) { PrintDialog dlg = new PrintDialog(); if (prnqueue != null) { dlg.PrintQueue = prnqueue; } if (prntkt != null) { dlg.PrintTicket = prntkt; } if (dlg.ShowDialog().GetValueOrDefault()) { prnqueue = dlg.PrintQueue; prntkt = dlg.PrintTicket; DrawingVisual vis = new DrawingVisual(); DrawingContext dc = vis.RenderOpen(); Pen pn = new Pen(Brushes.Black, 1); Rect rectPage = new Rect(marginPage.Left , marginPage.Top , dlg.PrintableAreaWidth - (marginPage.Left + marginPage.Right) , dlg.PrintableAreaHeight - (marginPage.Top + marginPage.Bottom)); //绘制矩形,以反映用户的边界 dc.DrawRectangle(null, pn, rectPage); //建立格式化文字对象,将PrintableArea 属性显示出来 FormattedText formtxt = new FormattedText(string.Format("Hello, Printer! {0} x {1}", (dlg.PrintableAreaWidth / 96).ToString("F1"), (dlg.PrintableAreaHeight / 96).ToString("0.0")) // F1 同 0.0 , CultureInfo.CurrentCulture , FlowDirection.LeftToRight , new Typeface(new FontFamily("Times New Roman"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal) , 48 , Brushes.Black); //取得格式化文字的实际尺寸 Size sizeText = new Size(formtxt.Width, formtxt.Height); //计算将文字放置在页面中心点(有考虑边界) Point ptText = new Point(rectPage.Left + (rectPage.Width - formtxt.Width) / 2, rectPage.Top + (rectPage.Height - formtxt.Height) / 2); //绘制文字和周围的矩形 dc.DrawText(formtxt, ptText); dc.DrawRectangle(null, pn, new Rect(ptText, sizeText)); //关闭DrawingContext dc.Close(); //打印页面 dlg.PrintVisual(vis, this.Title); } }
private static int GetPrintQueueJobCount(string queueName) { using (LocalPrintServer server = new LocalPrintServer()) { using (PrintQueue queue = new PrintQueue(server, queueName, new PrintQueueIndexedProperty[] { PrintQueueIndexedProperty.NumberOfJobs })) { return(queue.NumberOfJobs); } } }
//</SnippetCreateFixedDocumentWithConfiguredPaginator> #region Create FixedPage methods // ---------------------- CreateFirstPageContent ---------------------- /// <summary> /// Creates the content for the first fixed page.</summary> /// <param name="pq"> /// The print queue to output to.</parm> /// <returns> /// The page content for the first fixed page.</returns> private PageContent CreateFirstPageContent(PrintQueue pq) { PageContent pageContent = new PageContent(); FixedPage fixedPage = CreateFirstFixedPage(); PerformTransform(ref fixedPage, pq); ((IAddChild)pageContent).AddChild(fixedPage); return(pageContent); }
private static void DeletePrintedFiles( PrintServer printServer, string queueName, ConcurrentQueue <QueuedFile> files) { using (PrintQueue printerQueue = printServer.GetPrintQueue(queueName)) { DeletePrintedFiles(files, printerQueue); } }
public ItemLabelsView() { InitializeComponent(); if (ps == null) { ps = new LocalPrintServer(); pq = ps.DefaultPrintQueue; } }
/// <summary> /// The print. /// </summary> public void Print() { PrintDocumentImageableArea area = null; XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(ref area); if (xpsdw != null) { xpsdw.Write(this.CreateFixedDocument(new Size(area.ExtentWidth, area.ExtentHeight))); } }
public static bool ImprimirCredencialVeiculo(ClasseVeiculosCredenciais.VeiculoCredencial veiculoCredencial) { try { //IEngine _sdk = Main.engine; Workspace m_workspace = PagePrincipalView.Workspace; bool _deletaCredencial = false; Cardholder _cardholder = _sdk.GetEntity((Guid)veiculoCredencial.CardHolderGuid) as Cardholder; if (_cardholder == null) { return(false); } Credential _credencial = _sdk.GetEntity((Guid)veiculoCredencial.CredencialGuid) as Credential; if (_credencial == null) { _credencial = CriarCredencialProvisoria(_cardholder, veiculoCredencial.Validade, new Guid(veiculoCredencial.LayoutCrachaGUID)); _deletaCredencial = true; } Guid _CrachaGUID = new Guid(veiculoCredencial.LayoutCrachaGUID); Guid _CHGUID = _credencial.CardholderGuid; // new Guid("227ee2c9-371f-408f-bf91-07cfb7ac8a74"); System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { PrintQueue printQueue = GetPrintQueue(); if (printQueue != null) { IBadgeService badgeService = m_workspace.Services.Get <IBadgeService>(); if (badgeService != null) { BadgeInformation info = new BadgeInformation(_CrachaGUID, _credencial.Guid); badgeService.BeginPrint(info, printQueue, OnBadgePrinted, null); } } })); if (_deletaCredencial) { _sdk.DeleteEntity(_credencial); } return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// 打印机状态检查 /// </summary> /// <param name="statusReport"></param> /// <param name="pq"></param> void SpotTroubleUsingQueueAttributes(ref String statusReport, PrintQueue pq) { if ((pq.QueueStatus & PrintQueueStatus.PaperProblem) == PrintQueueStatus.PaperProblem) { statusReport = statusReport + "Has a paper problem. "; } if ((pq.QueueStatus & PrintQueueStatus.NoToner) == PrintQueueStatus.NoToner) { statusReport = statusReport + "Is out of toner. "; } if ((pq.QueueStatus & PrintQueueStatus.DoorOpen) == PrintQueueStatus.DoorOpen) { statusReport = statusReport + "Has an open door. "; } if ((pq.QueueStatus & PrintQueueStatus.Error) == PrintQueueStatus.Error) { statusReport = statusReport + "Is in an error state. "; } if ((pq.QueueStatus & PrintQueueStatus.NotAvailable) == PrintQueueStatus.NotAvailable) { statusReport = statusReport + "Is not available. "; } if ((pq.QueueStatus & PrintQueueStatus.Offline) == PrintQueueStatus.Offline) { statusReport = statusReport + "Is off line. "; } if ((pq.QueueStatus & PrintQueueStatus.OutOfMemory) == PrintQueueStatus.OutOfMemory) { statusReport = statusReport + "Is out of memory. "; } if ((pq.QueueStatus & PrintQueueStatus.PaperOut) == PrintQueueStatus.PaperOut) { statusReport = statusReport + "Is out of paper. "; } if ((pq.QueueStatus & PrintQueueStatus.OutputBinFull) == PrintQueueStatus.OutputBinFull) { statusReport = statusReport + "Has a full output bin. "; } if ((pq.QueueStatus & PrintQueueStatus.PaperJam) == PrintQueueStatus.PaperJam) { statusReport = statusReport + "Has a paper jam. "; } if ((pq.QueueStatus & PrintQueueStatus.Paused) == PrintQueueStatus.Paused) { statusReport = statusReport + "Is paused. "; } if ((pq.QueueStatus & PrintQueueStatus.TonerLow) == PrintQueueStatus.TonerLow) { statusReport = statusReport + "Is low on toner. "; } if ((pq.QueueStatus & PrintQueueStatus.UserIntervention) == PrintQueueStatus.UserIntervention) { statusReport = statusReport + "Needs user intervention. "; } }
private void DoThePrint(System.Windows.Documents.FlowDocument document) { // Clone the source document's content into a new FlowDocument. // This is because the pagination for the printer needs to be // done differently than the pagination for the displayed page. // We print the copy, rather that the original FlowDocument. MemoryStream s = new MemoryStream(); TextRange source = new TextRange(document.ContentStart, document.ContentEnd); source.Save(s, DataFormats.Xaml); FlowDocument copy = new FlowDocument(); TextRange dest = new TextRange(copy.ContentStart, copy.ContentEnd); dest.Load(s, DataFormats.Xaml); string[] address = Address.Split(','); Paragraph price = new Paragraph(new Run("Total Price: " + m_Order.TotalPrice + "€")); price.TextAlignment = TextAlignment.Right; price.Margin = new Thickness(0, 30, 0, 0); Paragraph customerInfo = new Paragraph(new Run(String.Format("{0} {1}\n{2}\n{3}", FirstName, LastName, address[0].Trim(), address[1].Trim()))); customerInfo.Margin = new Thickness(0, 0, 0, 50); copy.Blocks.Add(price); copy.Blocks.InsertBefore(copy.Blocks.FirstBlock, customerInfo); // Create a XpsDocumentWriter object, implicitly opening a Windows common print dialog, // and allowing the user to select a printer. // get information about the dimensions of the seleted printer+media. PrintDocumentImageableArea ia = null; XpsDocumentWriter docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia); if (docWriter != null && ia != null) { DocumentPaginator paginator = ((IDocumentPaginatorSource)copy).DocumentPaginator; // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device. paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight); Thickness t = new Thickness(72); // copy.PagePadding; copy.PagePadding = new Thickness( Math.Max(ia.OriginWidth, t.Left), Math.Max(ia.OriginHeight, t.Top), Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), t.Right), Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), t.Bottom)); copy.ColumnWidth = double.PositiveInfinity; // Send content to the printer. docWriter.Write(paginator); } }
private void ExecuteHandler() { ExecutionServices.SystemTrace.LogDebug($"Plugin exec data print queues = {_printQueues.Count}"); foreach (var x in _printQueues) { ExecutionServices.SystemTrace.LogDebug($"Queue={x.QueueName}"); } // Check to make sure we have something in the pool... if (_printQueues.Count == 0) { var msg = "None of the selected print queues are available."; ExecutionServices.SystemTrace.LogDebug(msg); throw new PrintQueueNotAvailableException(msg); } // Pick a print queue and log the device/server if applicable PrintQueueInfo queueInfo = _printQueues.GetRandom(); LogDevice(_pluginData, queueInfo); LogServer(_pluginData, queueInfo); // Connect to the print queue ExecutionServices.SystemTrace.LogDebug($"Connecting to queue: {queueInfo.QueueName}"); PrintQueue printQueue = PrintQueueController.Connect(queueInfo); _serverName = printQueue.HostingPrintServer.Name.TrimStart('\\'); ExecutionServices.SystemTrace.LogDebug($"Connected to queue: {printQueue.FullName}"); // Select a document to print Document document = _documentIterator.GetNext(_pluginData.Documents); ActivityExecutionDocumentUsageLog documentLog = new ActivityExecutionDocumentUsageLog(_pluginData, document); ExecutionServices.DataLogger.Submit(documentLog); // Download the document and log the starting information for the print job Guid jobId = SequentialGuid.NewGuid(); FileInfo localFile = ExecutionServices.FileRepository.GetFile(document); PrintJobClientLog log = LogPrintJobStart(_pluginData, localFile, printQueue, jobId); // Print the job PrintingEngineResult result = _engine.Print(localFile, printQueue, jobId); _printJobId = result.UniqueFileId; if (result == null) { throw new FilePrintException($"Failed to print {localFile}."); } // Log the ending information LogPrintJobEnd(log, result); ExecutionServices.SystemTrace.LogDebug("Controller execution completed"); }
static GlobalClass() { try { if (!Directory.Exists(GlobalClass.AppDataPath)) { Directory.CreateDirectory(GlobalClass.AppDataPath); } if (File.Exists(GlobalClass.AppDataPath + @"\sysPrinter.dat")) { PrinterName = File.ReadAllText(GlobalClass.AppDataPath + @"\sysPrinter.dat"); printer = new PrintServer().GetPrintQueues().FirstOrDefault(x => x.FullName.Contains(PrinterName)); } if (File.Exists(Environment.SystemDirectory + "\\ParkingDBSetting.dat")) { dynamic connProps = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(File.ReadAllText(Environment.SystemDirectory + "\\ParkingDBSetting.dat")); DataConnectionString = string.Format("SERVER = {0}; DATABASE = {1}; UID = {2}; PWD = {3};", Encrypt(connProps.DataSource.ToString()), Encrypt(connProps.InitialCatalog.ToString()), Encrypt(connProps.UserID.ToString()), Encrypt(connProps.Password.ToString())); Terminal = Encrypt(connProps.Terminal.ToString()); } using (SqlConnection cnmain = new SqlConnection(DataConnectionString)) { UpdateDatabase(cnmain); var Setting = cnmain.Query(@"SELECT CompanyName, CompanyAddress, CompanyInfo, ISNULL(GraceTime, 5) GraceTime, ISNULL(ShowCollectionAmountInCashSettlement, 0) ShowCollectionAmountInCashSettlement, ISNULL(DisableCashAmountChange,0) DisableCashAmountChange, SettlementMode, ISNULL(AllowMultiVehicleForStaff,0) AllowMultiVehicleForStaff, ISNULL(SlipPrinterWidth, 58) SlipPrinterWidth, ISNULL(EnableStaff, 0) EnableStaff, ISNULL(EnableStamp, 0) EnableStamp, ISNULL(EnableDiscount, 0) EnableDiscount, ISNULL(EnablePlateNo, 0) EnablePlateNo, ISNULL(EnablePrepaid, 0) EnablePrepaid, ISNULL(PrepaidInfo, '{}') PrepaidInfo, MemberBarcodePrefix FROM tblSetting").First(); CompanyName = Setting.CompanyName; CompanyAddress = Setting.CompanyAddress; CompanyPan = Setting.CompanyInfo; GraceTime = Setting.GraceTime; SettlementMode = Setting.SettlementMode; SlipPrinterWith = Setting.SlipPrinterWidth; ShowCollectionAmountInCashSettlement = ((bool)Setting.ShowCollectionAmountInCashSettlement) ? Visibility.Visible : Visibility.Collapsed; DisableCashAmountChange = ((bool)Setting.DisableCashAmountChange) ? Visibility.Collapsed : Visibility.Visible; DiscountVisible = ((bool)Setting.EnableDiscount) ? Visibility.Visible : Visibility.Collapsed; StaffVisible = ((bool)Setting.EnableStaff) ? Visibility.Visible : Visibility.Collapsed; StampVisible = ((bool)Setting.EnableStamp) ? Visibility.Visible : Visibility.Collapsed; PrepaidVisible = ((bool)Setting.EnablePrepaid) ? Visibility.Visible : Visibility.Collapsed; EnablePlateNo = (bool)Setting.EnablePlateNo; MemberBarcodePrefix = Setting.MemberBarcodePrefix; PrepaidInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <JObject>(Setting.PrepaidInfo); AllowMultiVehicleForStaff = (byte)Setting.AllowMultiVehicleForStaff; TCList = cnmain.Query <PSlipTerms>("SELECT Description, Height from PSlipTerms"); FYID = cnmain.ExecuteScalar <byte>("SELECT FYID FROM tblFiscalYear WHERE CONVERT(VARCHAR,GETDATE(),101) BETWEEN BEGIN_DATE AND END_DATE"); FYNAME = cnmain.ExecuteScalar <string>("SELECT FYNAME FROM tblFiscalYear WHERE CONVERT(VARCHAR,GETDATE(),101) BETWEEN BEGIN_DATE AND END_DATE"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Parking Management", MessageBoxButton.OK, MessageBoxImage.Error); } }
public override void Start() { PrintServer PrintS = new PrintServer(); PrintQueue queue = new PrintQueue(PrintS, _window.PrintInformation.PrinterSettings.PrinterName); bool trouve; List <Document> tempDocToRemove; List <Document> tempDocInQueue; do { tempDocToRemove = new List <Document>(); tempDocInQueue = _window.DocumentsInQueue.ToList(); queue.Refresh(); foreach (Document theDoc in tempDocInQueue) { trouve = false; try { using (PrintJobInfoCollection jobinfo = queue.GetPrintJobInfoCollection()) { foreach (PrintSystemJobInfo job in jobinfo) { using (job) { if (job.Name.Contains(theDoc.Name)) { trouve = true; } } } } } catch (NullReferenceException) { } catch (RuntimeWrappedException) { } catch (InvalidOperationException) { } if (trouve == false) { tempDocToRemove.Add(theDoc); SetStatus(theDoc, State.Printed); } } foreach (Document theDoc in tempDocToRemove) { _window.DocumentsInQueue.Remove(theDoc); } } while (!_token.IsCancellationRequested || _stopWindow.Stopped); PrintS.Dispose(); queue.Dispose(); }
private void SetLocalPrinter() { foreach (var printer in Printers) { if (printer.HostingPrintServer.Name.Contains(SystemInformation.ComputerName)) { LocalPrinter = printer; break; } } }
private void cmdCancelJob_Click(object sender, RoutedEventArgs e) { if (lstJobs.SelectedValue != null) { PrintQueue queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString()); PrintSystemJobInfo job = queue.GetJob((int)lstJobs.SelectedValue); job.Cancel(); lstQueues_SelectionChanged(null, null); } }
private void lstQueues_SelectionChanged(object sender, SelectionChangedEventArgs e) { PrintQueue queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString()); lblQueueStatus.Text = "Queue Status: " + queue.QueueStatus.ToString(); lblJobStatus.Text = ""; lstJobs.DisplayMemberPath = "JobName"; lstJobs.SelectedValuePath = "JobIdentifier"; lstJobs.ItemsSource = queue.GetPrintJobInfoCollection(); }
private void printSetting() { PrintDialog dPrt; dPrt = new PrintDialog(); dPrt.PrintQueue = m_queueCrt; if (dPrt.ShowDialog() == true) { m_queueCrt = dPrt.PrintQueue; } }
private void Window_Loaded(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Maximized; m_queueCrt = getDefaultPrintQueue(); m_dYTime = canvasPreview.ActualHeight / 297.0; m_dXTime = m_dYTime; m_dAddX = (canvasPreview.ActualWidth - (m_dXTime * 210.0)) / 2.0; m_dAddY = 0; drawPreview(); }
// --------------------- AdjustFlowDocumentToPage --------------------- /// <summary> /// Fits a given flow document to a specified media size.</summary> /// <param name="ipd"> /// The document paginator containing the flow document.</param> /// <param name="pq"> /// The print queue the document will be output to. public Visual AdjustFlowDocumentToPage( DocumentPaginator idp, PrintQueue pq) { const double inch = 96; PrintTicket pt = pq.UserPrintTicket; // Get the media size. double width = pt.PageMediaSize.Width.Value; double height = pt.PageMediaSize.Height.Value; // Set the margins. double leftmargin = 1.25 * inch; double rightmargin = 1.25 * inch; double topmargin = 1 * inch; double bottommargin = 1 * inch; // Calculate the content size. double contentwidth = width - leftmargin - rightmargin; double contentheight = height - topmargin - bottommargin; idp.PageSize = new Size(contentwidth, contentheight); DocumentPage p = idp.GetPage(0); // Create a wrapper visual for transformation and add extras. ContainerVisual page = new ContainerVisual(); page.Children.Add(p.Visual); DrawingVisual title = new DrawingVisual(); using (DrawingContext ctx = title.RenderOpen()) { Typeface typeface = new Typeface("Times New Roman"); Brush pen = Brushes.Black; FormattedText text = new FormattedText("Page 0", System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 14, pen); ctx.DrawText(text, new Point(inch / 4, -inch / 2)); } page.Children.Add(title); page.Transform = new TranslateTransform(leftmargin, topmargin); return page; }
void PrintOnClick(object sender, RoutedEventArgs args) { PrintDialog dlg = new PrintDialog(); if (prnqueue != null) dlg.PrintQueue = prnqueue; if (prntkt != null) dlg.PrintTicket = prntkt; if (dlg.ShowDialog().GetValueOrDefault()) { prnqueue = dlg.PrintQueue; prntkt = dlg.PrintTicket; DrawingVisual vis = new DrawingVisual(); DrawingContext dc = vis.RenderOpen(); Pen pn = new Pen(Brushes.Black, 1); Rect rectPage = new Rect(marginPage.Left, marginPage.Top, dlg.PrintableAreaWidth - (marginPage.Left + marginPage.Right), dlg.PrintableAreaHeight - (marginPage.Top + marginPage.Bottom)); dc.DrawRectangle(null, pn, rectPage); FormattedText formtxt = new FormattedText( String.Format("Hello, Printer! {0} x {1}", dlg.PrintableAreaWidth/96, dlg.PrintableAreaHeight/96), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface( new FontFamily("Times New Roman"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal), 48, Brushes.Black); Size sizeText = new Size(formtxt.Width, formtxt.Height); Point ptText = new Point(rectPage.Left + (rectPage.Width - formtxt.Width) / 2, rectPage.Top + (rectPage.Height - formtxt.Height) / 2); dc.DrawText(formtxt, ptText); dc.DrawRectangle(null,pn, new Rect(ptText, sizeText)); dc.Close(); dlg.PrintVisual(vis, Title); } }
public ExportQueueItemWindow(PrintQueue.PrintQueueItem printQueueItem) : base(400, 250) { if (Path.GetExtension(printQueueItem.PrintItemWrapper.FileLocation).ToUpper() == ".GCODE") { partIsGCode = true; } string McExportFileTitleBeg = new LocalizedString("MatterControl").Translated; string McExportFileTitleEnd = new LocalizedString("Export File").Translated; string McExportFileTitleFull = string.Format("{0}: {1}", McExportFileTitleBeg, McExportFileTitleEnd); this.Title = McExportFileTitleFull; this.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; // TODO: Complete member initialization this.printQueueItem = printQueueItem; doLayout(); ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(reloadAfterPrinterProfileChanged, ref unregisterEvents); }
public static Dictionary<string, string> GetInputBins(PrintQueue printQueue) { var inputBins = new Dictionary<string, string>(); var printerCapXmlStream = printQueue.GetPrintCapabilitiesAsXml(); var xmlDoc = new XmlDocument(); xmlDoc.Load(printerCapXmlStream); var manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI); var nodeList = xmlDoc.SelectNodes("//psf:Feature[@name='psk:JobInputBin']/psf:Option", manager); foreach (XmlNode node in nodeList) { inputBins.Add(node.LastChild.InnerText, node.Attributes["name"].Value); } return inputBins; }
void PrintOnExecuted(object sender, ExecutedRoutedEventArgs args) { PrintDialog dlg = new PrintDialog(); // Get the PrintQueue and PrintTicket from previous invocations. if (prnqueue != null) dlg.PrintQueue = prnqueue; if (prntkt != null) dlg.PrintTicket = prntkt; if (dlg.ShowDialog().GetValueOrDefault()) { // Save PrintQueue and PrintTicket from dialog box. prnqueue = dlg.PrintQueue; prntkt = dlg.PrintTicket; // Create a PlainTextDocumentPaginator object. PlainTextDocumentPaginator paginator = new PlainTextDocumentPaginator(); // Set the paginator properties. paginator.PrintTicket = prntkt; paginator.Text = txtbox.Text; paginator.Header = strLoadedFile; paginator.Typeface = new Typeface(txtbox.FontFamily, txtbox.FontStyle, txtbox.FontWeight, txtbox.FontStretch); paginator.FaceSize = txtbox.FontSize; paginator.TextWrapping = txtbox.TextWrapping; paginator.Margins = marginPage; paginator.PageSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight); // Print the document. dlg.PrintDocument(paginator, Title); } }
public void Print(string printerName, string content) { try { using (PrintServer ps = new PrintServer()) { using (PrintQueue pq = new PrintQueue(ps, printerName, PrintSystemDesiredAccess.AdministratePrinter)) { using (PrintQueueStream pqs = new PrintQueueStream(pq, Guid.NewGuid().ToString())) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(pqs, Encoding.Unicode)) { writer.Write(content); writer.Flush(); } } } } } catch (Exception ex) { throw new Exception("Ошибка печати. " + ex.Message); } }
public void PrinterNotifyWaitCallback(Object state,bool timedOut) { if (_printerHandle == IntPtr.Zero) return; #region read notification details _notifyOptions.Count = 1; int pdwChange = 0; IntPtr pNotifyInfo = IntPtr.Zero; bool bResult = FindNextPrinterChangeNotification(_changeHandle, out pdwChange, _notifyOptions, out pNotifyInfo); //If the Printer Change Notification Call did not give data, exit code if ((bResult == false) || (((int)pNotifyInfo) == 0)) return; //If the Change Notification was not relgated to job, exit code bool bJobRelatedChange = ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_ADD_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_ADD_JOB) || ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_SET_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_SET_JOB) || ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_DELETE_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_DELETE_JOB) || ((pdwChange & PRINTER_CHANGES.PRINTER_CHANGE_WRITE_JOB) == PRINTER_CHANGES.PRINTER_CHANGE_WRITE_JOB); if (!bJobRelatedChange) return; #endregion #region populate Notification Information //Now, let us initialize and populate the Notify Info data PRINTER_NOTIFY_INFO info = (PRINTER_NOTIFY_INFO)Marshal.PtrToStructure(pNotifyInfo, typeof(PRINTER_NOTIFY_INFO)); int pData = (int)pNotifyInfo + Marshal.SizeOf(typeof(PRINTER_NOTIFY_INFO)); PRINTER_NOTIFY_INFO_DATA[] data = new PRINTER_NOTIFY_INFO_DATA[info.Count]; for (uint i = 0; i < info.Count; i++) { data[i] = (PRINTER_NOTIFY_INFO_DATA)Marshal.PtrToStructure((IntPtr)pData, typeof(PRINTER_NOTIFY_INFO_DATA)); pData += Marshal.SizeOf(typeof(PRINTER_NOTIFY_INFO_DATA)); } #endregion #region iterate through all elements in the data array for (int i = 0; i < data.Count(); i++) { if ( (data[i].Field == (ushort)PRINTERJOBNOTIFICATIONTYPES.JOB_NOTIFY_FIELD_STATUS) && (data[i].Type == (ushort)PRINTERNOTIFICATIONTYPES.JOB_NOTIFY_TYPE) ) { JOBSTATUS jStatus = (JOBSTATUS)Enum.Parse(typeof(JOBSTATUS), data[i].NotifyData.Data.cbBuf.ToString()); int intJobID = (int)data[i].Id; string strJobName = ""; PrintSystemJobInfo pji = null; try { _spooler = new PrintQueue(new PrintServer(), _spoolerName); pji = _spooler.GetJob(intJobID); if (!objJobDict.ContainsKey(intJobID)) objJobDict[intJobID] = pji.Name; strJobName = pji.Name; } catch { pji = null; objJobDict.TryGetValue(intJobID, out strJobName); if (strJobName == null) strJobName = ""; } if (OnJobStatusChange != null) { //Let us raise the event OnJobStatusChange(this,new PrintJobChangeEventArgs(intJobID,strJobName,jStatus,pji)); } } } #endregion #region reset the Event and wait for the next event _mrEvent.Reset(); _waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, true); #endregion }
public void RefreshWindow() { if (_report != null) { if (_report.CopyNumber >= 1) { NumberOfCopySpinner.Value = _report.CopyNumber; } //update spinner FirstPageSpinner.Maximum = _report.PagesCount; LastPageSpinner.Maximum = _report.PagesCount; FirstPageSpinner.Value = 1; LastPageSpinner.Value = _report.PagesCount; //Get all printer cboImprimanteNom.ItemsSource = _printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }).Cast<PrintQueue>(); cboImprimanteNom.DisplayMemberPath = "FullName"; cboImprimanteNom.SelectedValue = "FullName"; //Select Default printer _currentPrinter = LocalPrintServer.GetDefaultPrintQueue(); for (int i = 0; i < cboImprimanteNom.Items.Count; i++) { PrintQueue testPrint = (PrintQueue)cboImprimanteNom.Items[i]; if (testPrint.FullName.ToString() == _currentPrinter.FullName.ToString()) { cboImprimanteNom.SelectedIndex = i; } } //Check if printer is ready if (_currentPrinter.IsNotAvailable == false) { lblImprimanteStatus.Content = "Ready"; ImgSource = @"pack://*****:*****@"pack://application:,,,/RDLCPrinter;component/Resources/Button-Blank-Red.ico"; } ReadyImage.Source = new BitmapImage(new Uri(ImgSource)); } }
private void SetLocalPrinter() { foreach (var printer in Printers) { if (printer.HostingPrintServer.Name.Contains(SystemInformation.ComputerName)) { LocalPrinter = printer; break; } } }
public void Start() { OpenPrinter(_spoolerName, out _printerHandle, 0); if (_printerHandle != IntPtr.Zero) { //We got a valid Printer handle. Let us register for change notification.... _changeHandle = FindFirstPrinterChangeNotification(_printerHandle, (int)PRINTER_CHANGES.PRINTER_CHANGE_JOB, 0, _notifyOptions); // We have successfully registered for change notification. Let us capture the handle... _mrEvent.Handle = _changeHandle; //Now, let us wait for change notification from the printer queue.... _waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, true); } _spooler = new PrintQueue(new PrintServer(), _spoolerName); foreach (PrintSystemJobInfo psi in _spooler.GetPrintJobInfoCollection()) { objJobDict[psi.JobIdentifier] = psi.Name; } }
//PrintOnExecuted �̺�Ʈ ȣ��� �� void PrintOnExecuted(object sender, ExecutedRoutedEventArgs args) { PrintDialog dlg = new PrintDialog(); //PrintDialog ��ü����. if (prnqueue != null) dlg.PrintQueue = prnqueue; //���� ���� �����ߴ� ������ ���ٸ�..(ó���״ٸ�) �Ѿ�� �ִٸ� //���� printdlg�� �־��ش�. if (prntkt != null) dlg.PrintTicket = prntkt; //���� ����... (�̰��� ���γ� ���η� �������ϴ°Ͱ� ���� �ɼ�) if (dlg.ShowDialog().GetValueOrDefault()) { //ok�� ������... //PrintDialog���� ������ ������ �Է¹� �����´�. prnqueue = dlg.PrintQueue; prntkt = dlg.PrintTicket; //dlg���� ����� ���� �ɼ��� ���߿� �ٽ� �� �� �ֵ��� //�� ��ü�� �����Ѵ�. PlainTextDocumentPaginator paginator = new PlainTextDocumentPaginator(); //PlainTextDocumentPaginator ��ü ����. paginator.PrintTicket = prntkt; //������ ���� ������ �����´�. paginator.Text = txtbox.Text; //������ ������ �����´�. paginator.Header = strLoadedFile; //������ ������ִ� ������ �����´�. paginator.Typeface = new Typeface(txtbox.FontFamily, txtbox.FontStyle, txtbox.FontWeight, txtbox.FontStretch); //���� �۲ÿ� ���� ��Ÿ�ϵ��� �����ش�. (���⼭�� ���߽�Ÿ�� ���� �ȵ�) paginator.FaceSize = txtbox.FontSize; //�۲� ������ paginator.TextWrapping = txtbox.TextWrapping; //���õ� Wrapping ������ �����ش�. //����ڰ� ������ ��� text�� ���õ� �ΰ����� ������ paginator��ü�� �����ش�. paginator.Margins = marginPage; //���� ������ �����ش�. paginator.PageSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight); //������ ��ü ũ�⸦ �����ش�. dlg.PrintDocument(paginator, Title); //paginator ��ü�� �̿��Ͽ� ���� ����Ʈ�� �Ѵ�. //�� ���������� PlainTextDocumentPaginator.cs�� �ִ� GetPage���� ���Ϲ��� //�������� ���������ִ� �� ����. } }
/// <summary> /// Select user printer /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cboImprimanetNom_SelectionChanged(object sender, SelectionChangedEventArgs e) { lblImprimanteStatus.Content = ""; _currentPrinter = (PrintQueue)cboImprimanteNom.SelectedItem; if (_currentPrinter.IsNotAvailable == false) { lblImprimanteStatus.Content = "Ready"; _printer.PrinterSettings.PrinterName = _currentPrinter.FullName; lblEmplacementImprimante.Content = _currentPrinter.QueuePort.Name; ImgSource = @"pack://*****:*****@"pack://application:,,,/RDLCPrinter;component/Resources/Button-Blank-Red.ico"; } ReadyImage.Source = new BitmapImage(new Uri(ImgSource)); }
/// <summary> /// Invokes a PrintEngine.PrintPreviewDialog to print preview the TextEditor.Document with specified title. /// </summary> public static void PrintPreviewDialog(this TextEditor textEditor, string title) { Printing.mDocumentTitle = title; Printing.InitPageSettings(); PrintPreviewDialog printPreview = new PrintEngine.PrintPreviewDialog(); printPreview.DocumentViewer.FitToMaxPagesAcross(1); printPreview.DocumentViewer.PrintQueue = mPrintQueue; if (mPageSettings.Landscape) Printing.mPrintTicket.PageOrientation = PageOrientation.Landscape; printPreview.DocumentViewer.PrintTicket = mPrintTicket; printPreview.DocumentViewer.PrintQueue.DefaultPrintTicket.PageOrientation = mPrintTicket.PageOrientation; printPreview.LoadDocument(CreateDocumentPaginatorToPrint(textEditor)); // this is stupid, but must be done to view a whole page: DocumentViewer.FitToMaxPagesAcrossCommand.Execute("1", printPreview.DocumentViewer); // we never get a return code 'true', since we keep the DocumentViewer open, until user closes the window printPreview.ShowDialog(); mPrintQueue = printPreview.DocumentViewer.PrintQueue; mPrintTicket = printPreview.DocumentViewer.PrintTicket; }
//private private static XpsDocumentWriter GetPrintXpsDocumentWriter(PrintQueue printQueue) { XpsDocumentWriter xpsWriter = PrintQueue.CreateXpsDocumentWriter(printQueue); return xpsWriter; }
/// <summary> /// Kiểm tra tình trạng máy in. /// Nếu không có tài liệu chờ in trả về tình trạng sẵn sàng /// </summary> /// <param name="printer"></param> /// <returns></returns> private bool CheckPrinterStatus(PrintQueue printer) { try { if (printer == null) return false; printer.Refresh(); //Nếu không có tài liệu chờ in trả về tình trạng sẵn sàng if (printer.NumberOfJobs <= 0) return true; return false; } catch (Exception) { return false; } }
// ------------------------- PerformTransform ------------------------- /// <summary> /// Computes the render transfer for outputting a /// given fixed page to a specified print queue.</summary> /// <param name="fp"> /// The fixed page to computer the render transform for.</param> /// <param name="fp"> /// The print queue that the page will be output to.</param> private void PerformTransform(ref FixedPage fp, PrintQueue pq) { // ContainerVisual root = new ContainerVisual(); const double inch = 96; // Getting margins double xMargin = 1.25 * inch; double yMargin = 1 * inch; PrintTicket pt = pq.UserPrintTicket; Double printableWidth = pt.PageMediaSize.Width.Value; Double printableHeight = pt.PageMediaSize.Height.Value; Double xScale = (printableWidth - xMargin * 2) / printableWidth; Double yScale = (printableHeight - yMargin * 2) / printableHeight; fp.RenderTransform = new MatrixTransform(xScale, 0, 0, yScale, xMargin, yMargin); }
// --------------------- CreateFourthPageContent ---------------------- /// <summary> /// Creates the content for the fourth fixed page.</summary> /// <param name="pq"> /// The print queue to output to.</param> /// <returns> /// The page content for the fourth fixed page.</returns> private PageContent CreateFourthPageContent(PrintQueue pq) { PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); fixedPage.Background = Brushes.BlanchedAlmond; BitmapImage bitmapImage = new BitmapImage( new Uri(_contentDir + @"\tiger.jpg", UriKind.RelativeOrAbsolute)); Image image = new Image(); image.Source = bitmapImage; Canvas.SetTop(image, 0); Canvas.SetLeft(image, 0); fixedPage.Children.Add(image); Image image2 = new Image(); image2.Source = bitmapImage; image2.Opacity = 0.3; FixedPage.SetTop(image2, 150); FixedPage.SetLeft(image2, 150); fixedPage.Children.Add(image2); PerformTransform(ref fixedPage, pq); ((IAddChild)pageContent).AddChild(fixedPage); double pageWidth = 96 * 8.5; double pageHeight = 96 * 11; fixedPage.Width = pageWidth; fixedPage.Height = pageHeight; return pageContent; }
// Print button: Invoke PrintDialog. void PrintOnClick(object sender, RoutedEventArgs args) { PrintDialog dlg = new PrintDialog(); // Set PrintQueue and PrintTicket from fields. if (prnqueue != null) dlg.PrintQueue = prnqueue; if (prntkt != null) dlg.PrintTicket = prntkt; if (dlg.ShowDialog().GetValueOrDefault()) { // Save PrintQueue and PrintTicket from dialog box. prnqueue = dlg.PrintQueue; prntkt = dlg.PrintTicket; // Create DrawingVisual and open DrawingContext. DrawingVisual vis = new DrawingVisual(); DrawingContext dc = vis.RenderOpen(); Pen pn = new Pen(Brushes.Black, 1); // Rectangle describes page minus margins. Rect rectPage = new Rect(marginPage.Left, marginPage.Top, dlg.PrintableAreaWidth - (marginPage.Left + marginPage.Right), dlg.PrintableAreaHeight - (marginPage.Top + marginPage.Bottom)); // Draw rectangle to reflect user's margins. dc.DrawRectangle(null, pn, rectPage); // Create formatted text object showing PrintableArea properties. FormattedText formtxt = new FormattedText( String.Format("Hello, Printer! {0} x {1}", dlg.PrintableAreaWidth / 96, dlg.PrintableAreaHeight / 96), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(new FontFamily("Times New Roman"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal), 48, Brushes.Black); // Get physical size of formatted text string. Size sizeText = new Size(formtxt.Width, formtxt.Height); // Calculate point to center text within margins. Point ptText = new Point(rectPage.Left + (rectPage.Width - formtxt.Width) / 2, rectPage.Top + (rectPage.Height - formtxt.Height) / 2); // Draw text and surrounding rectangle. dc.DrawText(formtxt, ptText); dc.DrawRectangle(null, pn, new Rect(ptText, sizeText)); // Close DrawingContext. dc.Close(); // Finally, print the page(s). dlg.PrintVisual(vis, Title); } }
/// <summary> /// Constructor de la ventana principal. /// </summary> /// <param name="printServer">Servidor acutal de impresión</param> /// <param name="printQueueSelected">Impresora seleccionada</param> /// <param name="sqlConn">Datos de la conexión a la base de datos</param> public MainWindow(LocalPrintServer printServer, string printQueueSelected, SqlConnection sqlConn) { InitializeComponent(); //Centramos la ventana. WindowFormat.CenterWindowOnScreen(this); //Almacenamos los parametros recibidos en variables de instancia. _sqlConn = sqlConn; _currentPrintServer = printServer; //Creamos la cola de impresión, donde le indicamos el servidor de impresión, //la impresora seleccionada y los privilegios. _currentPrintQueue = new PrintQueue(printServer, printQueueSelected, PrintSystemDesiredAccess.AdministratePrinter); //Colocamos en el label el nombre de la impresora seleccionada. lblSelectedPrinter.Content = printQueueSelected; //Creamos el objeto que nos indica si se está imprimiendo o no un trabajo. _printJobWrapper = new PrintJobWrapper(false, null); //Creamos e iniciamos el hilo secundario. _secondThread = new Thread(new ThreadStart(SecondaryThread)); _secondThread.Start(); }
/* Create the document write */ private XpsDocumentWriter GetDocWriter(PrintQueue pq) { XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq); return xpsdw; }
public static void PrintFlowDocument(PrintQueue printQueue, DocumentPaginator document) { XpsDocumentWriter xpsDocumentWriter = GetPrintXpsDocumentWriter(printQueue); PrintDocumentPaginator(xpsDocumentWriter, document); }
/* Main print entry point */ public void Print(PrintQueue queu, FixedDocumentSequence fixdoc) { XpsDocumentWriter docwrite = GetDocWriter(queu); m_busy = true; docwrite.WritingPrintTicketRequired += new WritingPrintTicketRequiredEventHandler(PrintTicket); PrintPages(docwrite, fixdoc); }
/// <summary> /// Invokes a System.Windows.Controls.PrintDialog to print the TextEditor.Document with specified title. /// </summary> public static void PrintDialog(this TextEditor textEditor, string title, bool withHighlighting) { m_DocumentTitle = (title != null) ? title : String.Empty; InitPageSettings(); System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog(); printDialog.PrintQueue = m_PrintQueue; if (m_PageSettings.Landscape) { m_PrintTicket.PageOrientation = PageOrientation.Landscape; } printDialog.PrintTicket = m_PrintTicket; printDialog.PrintQueue.DefaultPrintTicket.PageOrientation = m_PrintTicket.PageOrientation; if (printDialog.ShowDialog() == true) { m_PrintQueue = printDialog.PrintQueue; m_PrintTicket = printDialog.PrintTicket; printDialog.PrintDocument(CreateDocumentPaginatorToPrint(textEditor, withHighlighting), "PrintJob"); } }
public void SaveUserPrintTicket(PrintQueue currentPrinter) { Stream outStream = new FileStream(GetSaveLocation(currentPrinter.FullName), FileMode.Create); currentPrinter.UserPrintTicket.SaveTo(outStream); outStream.Close(); }
// --------------------- CreateSecondPageContent ---------------------- /// <summary> /// Creates the content for the second fixed page.</summary> /// <param name="pq"> /// The print queue to output to.</param> /// <returns> /// The page content for the second fixed page.</returns> private PageContent CreateSecondPageContent(PrintQueue pq) { PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); fixedPage.Background = Brushes.LightGray; UIElement visual = CreateSecondVisual(false); FixedPage.SetLeft(visual, 0); FixedPage.SetTop(visual, 0); double pageWidth = 96 * 8.5; double pageHeight = 96 * 11; fixedPage.Width = pageWidth; fixedPage.Height = pageHeight; fixedPage.Children.Add((UIElement)visual); PerformTransform(ref fixedPage, pq); ((IAddChild)pageContent).AddChild(fixedPage); return pageContent; }