/// <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 static PrintTicket ModifyPrintTicket(PrintTicket ticket, string featureName, string newValue) { if (ticket == null) { throw new ArgumentNullException("ticket"); } var xmlDoc = new XmlDocument(); xmlDoc.Load(ticket.GetXmlStream()); var manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI); var xpath = string.Format("//psf:Feature[contains(@name, 'InputBin')]/psf:Option", featureName); var node = xmlDoc.SelectSingleNode(xpath, manager); if (node != null) { node.Attributes["name"].Value = newValue; } var printTicketStream = new MemoryStream(); xmlDoc.Save(printTicketStream); printTicketStream.Position = 0; var modifiedPrintTicket = new PrintTicket(printTicketStream); return modifiedPrintTicket; }
/// <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"); } }
protected void PrintData(string username, PrintTicket ticket, string printername, string jobname, byte[] data, string driver) { using (Ghostscript gs = new Ghostscript()) { if (driver != null) { byte[] outdata = gs.ProcessData(ticket, data, driver, null, null); WindowsRawPrintJob pj = new WindowsRawPrintJob { JobName = jobname, PrinterName = printername, UserName = username, PrintData = outdata, RunAsUser = true }; pj.Print(); } else { gs.PrintData(username, ticket, printername, jobname, data, new string[] { }); } } }
private static CreateXpsFileResult InternalCreateFileFromXaml(FrameworkElement template, object dataContext) { string xpsFile = Path.GetTempFileName() + ".xps"; using (var container = Package.Open(xpsFile, FileMode.Create)) using (var document = new XpsDocument(container, CompressionOption.SuperFast)) { var coupon = template; coupon.DataContext = dataContext; coupon.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); coupon.UpdateLayout(); var ticket = new PrintTicket() { PageMediaSize = new PageMediaSize(coupon.DesiredSize.Width, coupon.DesiredSize.Height) }; XpsDocument.CreateXpsDocumentWriter(document).Write(coupon, ticket); return new CreateXpsFileResult() { Path = xpsFile, Ticket = ticket }; } }
/// <summary> /// Ensure Queue and Ticket prepared /// </summary> private void VerifyPrintSettings() { if (mPrintQueue == null) mPrintQueue = DefaultPrintQueue(); if (mPrintTicket == null) mPrintTicket = DefaultPrintTicket(); }
public void PrintData(string username, PrintTicket ticket, string printername, string jobname, byte[] data, string[] inargs) { string[] devsetup = SetDeviceCommand("%printer%" + printername, jobname, "mswinpr2").ToArray(); string[] extraargs = new string[] { "-dNOSAFER" }; SetupUserPrinter(username, printername); ProcessData(username, ticket, data, inargs, extraargs, devsetup); }
protected PaginatedPrintData ProcessPCL(byte[] rawdata, Dictionary<string, string> pjljobattribs, PrintTicket ticket) { PCLXLPrintJob pcljob = new PCLXLPrintJob(rawdata); return new PaginatedPrintData { Prologue = PJLHelper.GetPJL(pjljobattribs, ticket, "PCLXL").Concat(pcljob.Prologue).ToArray(), PageData = pcljob.PageData.ToArray(), Epilogue = pcljob.Epilogue.Concat(PJLHelper.GetEndJobPJL()).ToArray(), }; }
public static byte[] GetPJL(Dictionary<string, string> jobattribs, PrintTicket ticket, string language) { Dictionary<string, string> pjlsettings = new Dictionary<string, string> { { "DUPLEX", ticket.Duplexing == Duplexing.OneSided ? "OFF" : "ON" }, { "BINDING", ticket.Duplexing == Duplexing.TwoSidedShortEdge ? "SHORTEDGE" : "LONGEDGE" }, { "COPIES", (ticket.CopyCount ?? 1).ToString() }, { "RENDERMODE", ticket.OutputColor == OutputColor.Color ? "COLOR" : "GRAYSCALE" }, { "STAPLE", GetStapling(ticket.Stapling) } }; return GetPJL(jobattribs, pjlsettings, language); }
/// <summary> /// Class constructor /// </summary> /// <param name="paginator"></param> /// <param name="pageSettings"></param> /// <param name="printTicket"></param> /// <param name="headerFooterfontFamily"></param> public DocumentPaginatorWrapper(DocumentPaginator paginator, PageSettings pageSettings, PrintTicket printTicket, FontFamily headerFooterfontFamily) { m_Margins = ConvertMarginsToPx(pageSettings.Margins); if (pageSettings.Landscape) m_PageSize = new Size((int)printTicket.PageMediaSize.Height, (int)printTicket.PageMediaSize.Width); else m_PageSize = new Size((int)printTicket.PageMediaSize.Width, (int)printTicket.PageMediaSize.Height); m_Paginator = paginator; m_Paginator.PageSize = new Size(m_PageSize.Width - m_Margins.Left - m_Margins.Right, m_PageSize.Height - m_Margins.Top - m_Margins.Bottom); m_Typeface = new Typeface(headerFooterfontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); }
public void Print(string username, byte[] data, string printername, string jobname, PrintTicket ticket) { PopplerGDIPrintJob pj = new PopplerGDIPrintJob { PrintData = data, PrinterName = printername, PrintTicket = ticket, JobName = jobname, RunAsUser = username != null, UserName = username }; pj.Print(); }
public PhotoBoothControlWindow() { if (Properties.Settings.Default.PrintTicket != null) { this.printerSetupTicket = Properties.Settings.Default.PrintTicket; } this.SaveFileFolder = Properties.Settings.Default.SaveFileFolder; this.CardBannerText = Properties.Settings.Default.CardBannerText; this.CardTopVerticalText = Properties.Settings.Default.CardTopVerticalText; this.CardBottomVerticalText = Properties.Settings.Default.CardBottomVerticalText; this.OneButtonOperation = Properties.Settings.Default.OneButtonOperation; this.KioskMode = Properties.Settings.Default.KioskMode; InitializeComponent(); this.DataContext = this; this.LoadPreviousImages(); }
/* Main print entry point */ public void Print(PrintQueue queu, XpsDocument xpsDocument, Print printcontrol, bool print_all, int from, int to, String filename, bool tempfile) { XpsDocumentWriter docwrite; FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence(); DocumentReference docReference = fixedDocSeq.References[0]; FixedDocument doc = docReference.GetDocument(false); PrintTicket Ticket = SetUpTicket(queu, printcontrol, fixedDocSeq, tempfile); docwrite = GetDocWriter(queu); m_busy = true; m_filename = filename; #if DISABLED_FOR_NOW docwrite.WritingPrintTicketRequired += new WritingPrintTicketRequiredEventHandler(PrintTicket); #endif PrintPages(docwrite, doc, print_all, from, to, Ticket); }
private void SetPrintTicket(PrintTicket printTicket) { //Determine the Duplexing value. if (rbDuplexing1.IsEnabled && rbDuplexing2.IsChecked == true) { printTicket.Duplexing = Duplexing.OneSided; } else if (rbDuplexing2.IsEnabled && rbDuplexing2.IsChecked == true) { printTicket.Duplexing = Duplexing.TwoSidedLongEdge; } else if (rbDuplexing3.IsEnabled && rbDuplexing3.IsChecked == true) { printTicket.Duplexing = Duplexing.TwoSidedShortEdge; } //Determine the Collation setting. if (rbCollation1.IsEnabled && rbDuplexing2.IsChecked == true) { printTicket.Collation = Collation.Collated; } else if (rbCollation2.IsEnabled && rbDuplexing2.IsChecked == true) { printTicket.Collation = Collation.Uncollated; } //Determine the Orientation value. if (rbOrientation1.IsEnabled && rbOrientation1.IsChecked == true) { printTicket.PageOrientation = PageOrientation.Landscape; } else if (rbOrientation2.IsEnabled && rbOrientation2.IsChecked == true) { printTicket.PageOrientation = PageOrientation.Portrait; } }
ValidateDocumentSize(Size documentSize, PrintTicket printTicket) { if (documentSize.Width == 0 || documentSize.Height == 0 || DoubleOperations.IsNaN(documentSize.Width) || DoubleOperations.IsNaN(documentSize.Height) || Double.IsPositiveInfinity(documentSize.Width) || Double.IsPositiveInfinity(documentSize.Height) || Double.IsNegativeInfinity(documentSize.Width) || Double.IsNegativeInfinity(documentSize.Height) ) { Size sz = new Size(0, 0); //if print ticket definied, use printTicket dimensions if (printTicket != null && printTicket.PageMediaSize != null && printTicket.PageMediaSize.Width.HasValue && printTicket.PageMediaSize.Height.HasValue) { // Swap the height and width if needed to obtain a landscape orientation. if (printTicket.PageOrientation == PageOrientation.Landscape || printTicket.PageOrientation == PageOrientation.ReverseLandscape) { sz.Width = printTicket.PageMediaSize.Height.Value; sz.Height = printTicket.PageMediaSize.Width.Value; } else { sz.Width = printTicket.PageMediaSize.Width.Value; sz.Height = printTicket.PageMediaSize.Height.Value; } } else { sz.Width = 96 * 8.5; sz.Height = 96 * 11; } return(sz); } return(documentSize); }
// ------------------------- AddPackageContent ---------------------------- /// <summary> /// Adds a predefined set of content to a given XPS document.</summary> /// <param name="xpsDocument"> /// The package to add the document content to.</param> /// <param name="attachPrintTicket"> /// true to include a PrintTicket with the /// document; otherwise, false.</param> private void AddPackageContent( XpsDocument xpsDocument, bool attachPrintTicket) { try { PrintTicket printTicket = GetPrintTicketFromPrinter(); // PrintTicket is null, there is no need to attach one. if (printTicket == null) { attachPrintTicket = false; } // Add a FixedDocumentSequence at the Package root IXpsFixedDocumentSequenceWriter documentSequenceWriter = xpsDocument.AddFixedDocumentSequence(); // Add the 1st FixedDocument to the FixedDocumentSequence. - - - - - IXpsFixedDocumentWriter fixedDocumentWriter = documentSequenceWriter.AddFixedDocument(); // Add content to the 1st document AddDocumentContent(fixedDocumentWriter); // Commit the 1st Document fixedDocumentWriter.Commit(); // If attaching PrintTickets, attach one at // the package FixedDocumentSequence level. if (attachPrintTicket) { documentSequenceWriter.PrintTicket = printTicket; } // Commit the FixedDocumentSequence documentSequenceWriter.Commit(); } catch (XpsPackagingException xpsException) { throw xpsException; } }// end:AddPackageContent()
private static void SaveSingleFixedContentDocument(FixedDocument fd, PrintTicket printTicket) { // Configure save file dialog box Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.DefaultExt = ".xps"; // Default file extension dlg.Filter = "XPS 文档|*.xps"; // Filter files by extension // Show save file dialog box Nullable <bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result != true) { return; } string pack = dlg.FileName; Uri uri = new Uri(pack); using (Package container = Package.Open(pack, FileMode.Create)) { PackageStore.AddPackage(uri, container); using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Fast, pack)) { XpsDocumentWriter xpsdw1 = XpsDocument.CreateXpsDocumentWriter(xpsDoc); xpsdw1.Write(fd.DocumentPaginator); // Write the FixedDocument as a document. } PackageStore.RemovePackage(uri); } string msg = "导出XPS文件成功,文件位置“" + pack + "”是否立即打开该文档?"; if (MessageBoxResult.Yes == MessageBox.Show(msg, "导出XPS", MessageBoxButton.YesNo, MessageBoxImage.Question)) { try { System.Diagnostics.Process.Start(pack); } catch (Exception ex) { Console.WriteLine(ex.Message); MessageBox.Show("采用默认的打开方式打开文件失败,请找到该文件,手动打开。", "打开XPS", MessageBoxButton.OK, MessageBoxImage.Information); } } }
AcquirePrintTicket( IntPtr devModeHandle, string printQueueName ) { PrintTicket printTicket = null; byte[] devModeData = null; // // Copy the devmode into a byte array // IntPtr pDevMode = IntPtr.Zero; try { pDevMode = UnsafeNativeMethods.GlobalLock(devModeHandle); NativeMethods.DEVMODE devMode = Marshal.PtrToStructure <NativeMethods.DEVMODE>(pDevMode); devModeData = new byte[devMode.dmSize + devMode.dmDriverExtra]; Marshal.Copy(pDevMode, devModeData, 0, devModeData.Length); } finally { if (pDevMode != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnlock(devModeHandle); } } // // Convert the devmode data to a PrintTicket object // using (PrintTicketConverter ptConverter = new PrintTicketConverter( printQueueName, PrintTicketConverter.MaxPrintSchemaVersion)) { printTicket = ptConverter.ConvertDevModeToPrintTicket(devModeData); } return(printTicket); }
private IntPtr AllocateAndInitializeDevMode(string printerName, PrintTicket printTicket) { byte[] array = null; SystemDrawingHelper.NewDefaultPrintingPermission().Assert(); try { using (PrintTicketConverter printTicketConverter = new PrintTicketConverter(printerName, PrintTicketConverter.MaxPrintSchemaVersion)) { array = printTicketConverter.ConvertPrintTicketToDevMode(printTicket, BaseDevModeType.UserDefault); } } finally { CodeAccessPermission.RevertAssert(); } IntPtr intPtr = Marshal.AllocHGlobal(array.Length); Marshal.Copy(array, 0, intPtr, array.Length); return(intPtr); }
}// end:PrintSingleVisual() // ----------------------- PrintMultipleVisuals ----------------------- /// <summary> /// Prints a collection of multiple visual elements.</summary> /// <param name="pq"> /// The print queue to print to.</param> /// <param name="async"> /// true to print asynchronously; false to print synchronously.</param> public void PrintMultipleVisuals(PrintQueue pq, bool async) { // Create a collection of visuals List <Visual> vc = new List <Visual>(); //Create Visuals Visual v; v = _wpfContent.CreateFirstVisual(true); Visual transformedVisual = PerformTransform(v, pq); vc.Add(transformedVisual); v = _wpfContent.CreateSecondVisual(true); transformedVisual = PerformTransform(v, pq); vc.Add(transformedVisual); v = _wpfContent.CreateThirdVisual(true); transformedVisual = PerformTransform(v, pq); vc.Add(transformedVisual); // Retrieve Print Ticket from PrintQueue and // change the orientation to Landscape. PrintTicket pt = pq.UserPrintTicket; pt.PageOrientation = PageOrientation.Landscape; // Create an printing XPSDocumentWriter XpsDocumentWriter xdwPrint = GetPrintXpsDocumentWriter(pq); // Print either asynchronously or synchronously. if (async) { PrintVisualsAsync(xdwPrint, vc); } else { // Print content using helper function PrintVisuals(xdwPrint, vc); } }// end:PrintMultipleVisuals()
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); } }
private void button3_Click(object sender, EventArgs e) { AlquileresVigentes veralquileres = new AlquileresVigentes(); Ticket unTicket = new Ticket(); veralquileres.dgvAlquileres.AllowUserToAddRows = false; string[] alquileres = new string[6]; foreach (Alquiler p in administracion.GetAlquileres()) { string datos = p.getClinete().Nombre + ";" + p.getClinete().Dni + ";" + p.getClinete().Telefono + ";" + Convert.ToString(p.DiasDeAlquiler) + ";" + p.Auto.Marca + ";" + p.Auto.Patente + ";" + p.Auto.Kms + ";" + (p.Auto.PrecioAlquiladoEnUDC * p.PrecioAlquilado * p.DiasDeAlquiler); alquileres = datos.Split(';'); veralquileres.dgvAlquileres.ColumnCount = alquileres.Length; veralquileres.dgvAlquileres.Rows.Add(alquileres); } if (veralquileres.ShowDialog() == DialogResult.OK) { try { devolucion = new Alquiler(); devolucion = administracion.GetAlquileres()[veralquileres.dgvAlquileres.CurrentRow.Index]; precio = administracion.Devolucion(veralquileres.dgvAlquileres.CurrentRow.Index, Convert.ToInt32(veralquileres.textBox1.Text), veralquileres.dgvAlquileres, veralquileres.dateTimePicker1.Value); unTicket.printPreviewControl1.Document = PrintTicket; ActualizarListboxs(); if (unTicket.ShowDialog() == DialogResult.OK) { PrintTicket.Print(); } } catch (Exception er) { MessageBox.Show(er.Message); } } }
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); } }
/// <summary> /// 設定を読み出して、印刷設定を取得する /// </summary> /// <param name="ps">ローカルプリントサーバー</param> /// <param name="pq">設定を入力するプリントキューへの参照</param> /// <param name="pt">設定を入力するプリントチケットへの参照</param> /// <returns>true:全て設定成功 false:システムデフォルト設定が混じった</returns> protected bool GetPrinterSetting(LocalPrintServer ps, ref PrintQueue pq, ref PrintTicket pt) { if (Settings.PrinterName != "") { try { //PrinterName設定のキューを取得する pq = ps.GetPrintQueue(Settings.PrinterName); //PrintTicket設定に中身があれば取得する if (Settings.PrintTicketSetting != null) { pt = Settings.PrintTicketSetting.Clone(); //両方取得できたらアプリ設定からの印刷設定取得に成功として返す return(true); } else { //中身がなければキューのデフォルト設定を取得する pt = ps.DefaultPrintQueue.UserPrintTicket.Clone(); } } catch { //失敗したらシステムのデフォルト設定を取得する MessageBox.Show("設定したプリンタが見つかりません"); pq = ps.DefaultPrintQueue; pt = ps.DefaultPrintQueue.UserPrintTicket.Clone(); } } else { //プリンタ設定がなければシステムのデフォルト設定を取得する pq = ps.DefaultPrintQueue; pt = ps.DefaultPrintQueue.UserPrintTicket.Clone(); } //ここまで来たらアプリ設定からの印刷設定取得に失敗している return(false); }
private void _pnlPrinting_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { ContentPresenter cp = (ContentPresenter)sender; var ef = ((MainWindow)Application.Current.MainWindow).Data.EditorFrame; if (ef == null || ef.XmlEditor == null || ef.XSDocument == null) { cp.Content = new Label { Content = "No file loaded" }; return; } PageSettings pageSettings = new PageSettings { Margins = new Margins(40, 40, 40, 40) }; PrintQueue printQueue = LocalPrintServer.GetDefaultPrintQueue(); PrintTicket printTicket = printQueue.DefaultPrintTicket; PrintPreviewControl printPreview = new PrintPreviewControl(); printPreview.DocumentViewer.FitToMaxPagesAcross(1); printPreview.DocumentViewer.PrintQueue = printQueue; if (pageSettings.Landscape) { printTicket.PageOrientation = PageOrientation.Landscape; } printPreview.DocumentViewer.PrintTicket = printTicket; printPreview.DocumentViewer.PrintQueue.DefaultPrintTicket.PageOrientation = printTicket.PageOrientation; printPreview.LoadDocument(Printing.CreateDocumentPaginatorToPrint(ef.XmlEditor, pageSettings, printTicket, ef.XSDocument.Filename)); // this is stupid, but must be done to view a whole page: DocumentViewer.FitToMaxPagesAcrossCommand.Execute("1", printPreview.DocumentViewer); cp.Content = printPreview; }
StartNewDocument() { try { Uri uri = _xpsManager.GenerateUniqueUri(XpsS0Markup.FixedDocumentContentType); _currentFixedDocumentUri = uri; IOpcPartUri partUri = GenerateIOpcPartUri(uri); if (_currentDocumentPrintTicket == null) { _currentDocumentPrintTicket = new PrintTicket(); } IXpsOMPrintTicketResource printTicketResource = GeneratePrintTicketResource(XpsS0Markup.FixedDocumentContentType, _currentDocumentPrintTicket); _currentFixedDocumentSequenceWriter.StartNewDocument(partUri, printTicketResource, null, null, null); _currentFixedDocumentWriterRef++; } catch (COMException) { Invalidate(); throw new PrintingCanceledException(); } }
static public void FixFont() { if (ExistFont("TEC1")) { MessageBox.Show("字体已经存在"); } else { string fn = Environment.SystemDirectory; fn = fn.Substring(0, fn.LastIndexOf("\\")) + "\\fonts\\tec.ttf"; string batfile = "c:\\fixfont.cmd"; FileStream fs = new FileStream(batfile, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("copy " + fn + " c:\\tec.ttf"); sw.WriteLine("del " + fn); sw.WriteLine("copy c:\\tec.ttf " + fn); sw.Close(); fs.Close(); PrintTicket.RunProgram("c:\\fixfont.cmd", ""); } }
protected void PrintData(string username, PrintTicket ticket, string printername, string jobname, byte[] data, Dictionary <string, string> pjljobattribs) { using (Ghostscript gs = new Ghostscript()) { string driver = ticket.OutputColor == OutputColor.Color ? "pxlcolor" : "pxlmono"; byte[] pcldata = gs.ProcessData(ticket, data, driver, null, null); PaginatedPrintData pcljob = ProcessPCL(pcldata, pjljobattribs, ticket); WindowsRawPrintJob job = new WindowsRawPrintJob { PagedData = pcljob, JobName = jobname, PrinterName = printername, UserName = username, RunAsUser = true }; job.Print(); } }
}// end:CreateFixedDocumentSequencePrintTicket() // ------------------ CreateFixedDocumentPrintTicket ------------------ /// <summary> /// Creates a FixedDocument compatible PrintTicket.</summary> /// <param name="isLandscaped"> /// true to output in landscape; false to output in portrait.</param> /// <returns> /// A FixedDocument compatible PrintTicket.</returns> private PrintTicket CreateFixedDocumentPrintTicket(bool isLandscaped) { // Create a local print server LocalPrintServer ps = new LocalPrintServer(); // Get the default print queue PrintQueue pq = ps.DefaultPrintQueue; // Get the default user print ticket PrintTicket pt = pq.UserPrintTicket; // Set Duplexing value for the document pt.Duplexing = Duplexing.TwoSidedLongEdge; if (isLandscaped) { pt.PageOrientation = PageOrientation.Landscape; } return(pt); }// end:CreateFixedDocumentPrintTicket()
protected void PrintData(string username, PrintTicket ticket, string printername, string jobname, byte[] data, Dictionary<string, string> pjljobattribs) { using (Ghostscript gs = new Ghostscript()) { string driver = ticket.OutputColor == OutputColor.Color ? "pxlcolor" : "pxlmono"; byte[] pcldata = gs.ProcessData(ticket, data, driver, null, null); PaginatedPrintData pcljob = ProcessPCL(pcldata, pjljobattribs, ticket); WindowsRawPrintJob job = new WindowsRawPrintJob { PagedData = pcljob, JobName = jobname, PrinterName = printername, UserName = username, RunAsUser = true }; job.Print(); } }
//We want to be able to scale the visual so it fits within the page. private Visual ScaleVisual(Visual v, PrintQueue pq) { ContainerVisual root = new ContainerVisual(); const double inch = 96; // Set the 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; root.Children.Add(v); root.Transform = new MatrixTransform(xScale, 0, 0, yScale, xMargin, yMargin); return(root); }
public void LoadPrintTicket(PrintDialog dialog) { string configFile = Path.Combine(Settings.SessionFolder, ServiceProvider.Settings.DefaultSession.Name + "_printer.xml"); PrintTicket defaultTicket; try { defaultTicket = dialog.PrintQueue.UserPrintTicket ?? dialog.PrintQueue.DefaultPrintTicket; } catch (Exception e) { Log.Error("Unable to load printer settings.", e); return; } if (File.Exists(configFile)) { try { using (FileStream stream = new FileStream(configFile, FileMode.Open)) { PrintTicket newTicket = new PrintTicket(stream); System.Printing.ValidationResult result = dialog.PrintQueue.MergeAndValidatePrintTicket(defaultTicket, newTicket); dialog.PrintTicket = result.ValidatedPrintTicket; stream.Close(); } } catch (Exception e) { Log.Error("Unable to load printer settings.", e); dialog.PrintTicket = defaultTicket; } } else { dialog.PrintTicket = defaultTicket; } }
/// PrintTicket #region PrintTickets /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public static PrintTicket GetPrintTicketFromPrinter(string path, out PrintJobSettings printJobSettings) { printJobSettings = null; if (String.IsNullOrWhiteSpace(path)) { return(null); } PrintQueue printQueue = null; PrintServer printServer = new PrintServer(); // Retrieving collection of local printer on user machine PrintQueueCollection localPrinterCollection = printServer.GetPrintQueues(); foreach (var printer in localPrinterCollection) { if (printer.Name == path) { printQueue = (PrintQueue)printer; } } if (printQueue == null) { return(null); } printQueue.Refresh(); // Get default PrintTicket from printer //PrintTicket printTicket = printQueue.DefaultPrintTicket; PrintTicket printTicket = printQueue.UserPrintTicket; PrintJobSettings settings = printQueue.CurrentJobSettings; //System.Printing.PrintJobSettings printJobSettings = settings; return(printTicket); }
private void PrintOnClick(object sender, RoutedEventArgs args) { PrintDialog dlg = new PrintDialog(); if (dlg.ShowDialog().GetValueOrDefault()) { //确定方位时垂直的(Portrait) PrintTicket prntkt = dlg.PrintTicket; prntkt.PageOrientation = PageOrientation.Portrait; dlg.PrintTicket = prntkt; //用户即使选择水平纸张,此处依旧会将其设置为垂直 //建立新的BannerDocumentPaginator对象 BannerDocumentPaginator paginator = new BannerDocumentPaginator(); paginator.Text = txtbox.Text; //根据纸张的尺寸,指定PageSize属性 paginator.PageSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight); //调用PrintDocument以打印出文件 dlg.PrintDocument(paginator, "Banner: " + txtbox.Text); } }
/// <param name="ticket"></param> /// <param name="ticketXMLString">If you wish to read/write to the cache, /// this must be set to the result of ticket.ToXmlString(). /// This an optional performance enhancement.</param> private byte[] GetDevmode(PrintTicket ticket, String ticketXMLString) { Debug.Assert(ticket != null); // The cached devmode is not modified by internal printing code // and not exposed to client code so it is safe to pass the byte array // by reference instead of making a copy byte[] result = null; if (ticketXMLString != null && m_printTicketCache.TryGetDevMode(ticketXMLString, out result)) { } // 10ms slowpath. else { Toolbox.EmitEvent(EventTrace.Event.WClientDRXGetDevModeBegin); (new PrintingPermission(PrintingPermissionLevel.DefaultPrinting)).Assert(); // BlessedAssert try { result = ConvertPrintTicketToDevMode(ticket); if (ticketXMLString != null) { m_printTicketCache.CacheDevMode(ticketXMLString, result); } } finally { PrintingPermission.RevertAssert(); } Toolbox.EmitEvent(EventTrace.Event.WClientDRXGetDevModeEnd); } return(result); }
private void GetPrintDialog() { var localPrintServer = new LocalPrintServer(); var localPrinterQueueCollection = localPrintServer.GetPrintQueues(); var printerQueue = localPrinterQueueCollection.FirstOrDefault(); PrintTicket printTicket = null; if (null != printerQueue) { printTicket = printerQueue.DefaultPrintTicket; } _printDialog = new PrintDialog { PrintTicket = printTicket ?? new PrintTicket { PageOrientation = PageOrientation.Portrait, //TODO-Print-Configuration : PageOrientation CopyCount = 1, PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4) //TODO-Print-Configuration : PageMediaSize } }; }
/// <summary> /// Creates DevMode structure from Ticket /// </summary> /// <param name="printerName"></param> /// <param name="printTicket"></param> /// <returns></returns> IntPtr InitializeDevMode(string printerName, PrintTicket printTicket) { Helpers.SecurityAssert(); byte[] dMode = null; try { using (PrintTicketConverter converter = new PrintTicketConverter(printerName, PrintTicketConverter.MaxPrintSchemaVersion)) { dMode = converter.ConvertPrintTicketToDevMode(printTicket, BaseDevModeType.UserDefault); } } finally { Helpers.SecurityRevert(); } IntPtr ptrDevMode = Marshal.AllocHGlobal(dMode.Length); Marshal.Copy(dMode, 0, ptrDevMode, dMode.Length); return(ptrDevMode); }
/* Send it */ private void PrintPages(XpsDocumentWriter xpsdw, FixedDocument fixdoc, bool print_all, int from, int to, PrintTicket Ticket) { m_docWriter = xpsdw; xpsdw.WritingCompleted += new WritingCompletedEventHandler(AsyncCompleted); xpsdw.WritingProgressChanged += new WritingProgressChangedEventHandler(AsyncProgress); DocumentPaginator paginator = fixdoc.DocumentPaginator; try { if (print_all) { m_first_page = 1; m_num_pages = paginator.PageCount; xpsdw.Write(paginator, Ticket); } else { /* Create an override paginator to pick only the pages we want */ GSDocumentPaginator gspaginator = new GSDocumentPaginator(paginator, from, to); m_first_page = from; m_num_pages = paginator.PageCount; xpsdw.Write(gspaginator, Ticket); } } catch (Exception) { /* Something went wrong with this particular print driver * simply notify the user and clean up everything */ gsPrintEventArgs info = new gsPrintEventArgs(PrintStatus_t.PRINT_ERROR, false, 0, this.m_first_page, this.m_num_pages, this.m_filename); PrintUpdate(this, info); return; } }
protected byte[] ProcessData(string username, PrintTicket ticket, byte[] data, string[] inargs, string[] extraargs, string[] devsetup) { string[] pagesetup = PostscriptHelper.SetPageDeviceCommand(ticket).ToArray(); string[] args = new string[] { "-dNOPAUSE", "-dBATCH" } .Concat(inargs ?? new string[] { }) .Concat(extraargs ?? new string[] { }) .Concat(new string[] { "-sOutputFile=%stdout" }) .Concat(new string[] { "-c" }) .Concat(devsetup ?? new string[] { }) .Concat(pagesetup) .Concat(new string[] { "-" }) .ToArray(); MemoryStream outstream = new MemoryStream(); MemoryStream errstream = new MemoryStream(); MemoryStream instream = new MemoryStream(data); int exitcode; if (username != null) { exitcode = RunCommandAsUser(username, args, instream, outstream, errstream); } else { exitcode = RunCommand(args, instream, outstream, errstream); } string errstr = Encoding.UTF8.GetString(errstream.ToArray()); if (exitcode != 0) { Logger.Log(LogLevel.Warning, "Ghostscript returned code {0}\n\nError:\n{1}", exitcode, errstr); throw new InvalidOperationException(String.Format("Ghostscript error {0}\n{1}", exitcode, errstr)); } return(outstream.ToArray()); }
protected void Print(CloudPrintJob job, bool runAsUser, bool usePJL, Dictionary <string, string> pjljobattribs, Dictionary <string, string> pjlsettings) { PrintTicket ticket = job.GetPrintTicket(); PaginatedPrintData pagedjob = PostscriptHelper.FromPDF(job.GetPrintData(), ticket); if (usePJL) { pagedjob.Prologue = PJLHelper.GetPJL(pjljobattribs, pjlsettings, "POSTSCRIPT").Concat(pagedjob.Prologue).ToArray(); } WindowsRawPrintJob pj = new WindowsRawPrintJob { PagedData = pagedjob, JobName = job.JobTitle, PrinterName = job.Printer.Name, UserName = job.Username, PrintTicket = ticket, RunAsUser = runAsUser }; pj.Print(); }
AcquireDefaultPrintTicket( PrintQueue printQueue ) { PrintTicket printTicket = null; try { if (printQueue != null) { printTicket = printQueue.UserPrintTicket; if (printTicket == null) { printTicket = printQueue.DefaultPrintTicket; } } } catch (PrintSystemException) { // // The printing subsystem can throw an exception in certain cases when // the print ticket is unavailable. If it does we will handle this // below. There is no real need to bubble this up to the application. // printTicket = null; } // // If the printing subsystem could not give us a print ticket either due to // a failure or because a user/system default was not available, then just // create a blank/empty one. // if (printTicket == null) { printTicket = new PrintTicket(); } return(printTicket); }
/// <summary> /// Creates DevMode structure from Ticket /// </summary> /// <param name="printerName"></param> /// <param name="printTicket"></param> /// <returns></returns> IntPtr InitializeDevMode(string printerName, PrintTicket printTicket) { new PrintingPermission(PrintingPermissionLevel.DefaultPrinting).Assert(); byte[] dMode = null; try { using (PrintTicketConverter converter = new PrintTicketConverter(printerName, PrintTicketConverter.MaxPrintSchemaVersion)) { dMode = converter.ConvertPrintTicketToDevMode(printTicket, BaseDevModeType.UserDefault); } } finally { CodeAccessPermission.RevertAssert(); } IntPtr ptrDevMode = Marshal.AllocHGlobal(dMode.Length); Marshal.Copy(dMode, 0, ptrDevMode, dMode.Length); return(ptrDevMode); }
public void LoadSetting() { XmlMasterSettings xmlTerminal; XmlPrinterSettings xmlPrinter; try { var xmlFile = XmlWorker.LoadXmlFile("Settings", "Setting.xml"); if (xmlFile == null) { return; } xmlTerminal = XmlMasterSettings.LoadXmlSetting(xmlFile); xmlPrinter = XmlPrinterSettings.LoadXmlSetting(xmlFile); } catch (FileNotFoundException ex) { ErrorString = ex.ToString(); return; } catch (Exception ex) { ErrorString = "ОШИБКА в узлах дерева XML файла настроек: " + ex; return; } try { MasterTcpIp = new MasterTcpIp(xmlTerminal); PrintTicket = new PrintTicket(xmlPrinter); } catch (Exception ex) { ErrorString = ex.ToString(); } }
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 static PrintTicket ModifyPrintTicket(PrintTicket ticket, string featureName, string newValue) { if (ticket == null) { throw new ArgumentNullException("ticket"); } // read Xml of the PrintTicket XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(ticket.GetXmlStream()); // create NamespaceManager and add PrintSchemaFrameWork-Namespace hinzufugen (should be on DocumentElement of the PrintTicket) // Prefix: psf NameSpace: xmlDoc.DocumentElement.NamespaceURI = "http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework" XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI); // search node with desired feature we're looking for and set newValue for it string xpath = string.Format("//psf:Feature[@name='{0}']/psfSurpriseption", featureName); XmlNode node = xmlDoc.SelectSingleNode(xpath, manager); if (node != null) { node.Attributes["name"].Value = newValue; } // create a new PrintTicket out of the XML MemoryStream printTicketStream = new MemoryStream(); xmlDoc.Save(printTicketStream); printTicketStream.Position = 0; PrintTicket modifiedPrintTicket = new PrintTicket(printTicketStream); // for testing purpose save the printticket to file //FileStream stream = new FileStream("modPrintticket.xml", FileMode.CreateNew, FileAccess.ReadWrite); //modifiedPrintTicket.GetXmlStream().WriteTo(stream); return modifiedPrintTicket; }
public abstract void WriteAsync(Visual visual, PrintTicket printTicket);
//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���� ���Ϲ��� //�������� ���������ִ� �� ����. } }
public abstract void WriteAsync(Visual visual, PrintTicket printTicket, object userState);
public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket, object userState) { throw new NotSupportedException(); }
public override void Write(FixedDocument fixedDocument, PrintTicket printTicket) { SerializeObjectTree(fixedDocument); }
public override void Write(FixedPage fixedPage, PrintTicket printTicket) { SerializeObjectTree(fixedPage); }
public override void Write(DocumentPaginator documentPaginator, PrintTicket printTicket) { SerializeObjectTree(documentPaginator.Source); }
public override SerializerWriterCollator CreateVisualsCollator(PrintTicket documentSequencePT, PrintTicket documentPT) { throw new NotSupportedException(); }
/* Print ticket handling. You can customize for PrintTicketLevel at FixedDocumentSequencePrintTicket, FixedDocumentPrintTicket, or FixedPagePrintTicket. We may want to play around with this some */ private void PrintTicket(Object sender, WritingPrintTicketRequiredEventArgs e) { if (e.CurrentPrintTicketLevel == PrintTicketLevel.FixedDocumentSequencePrintTicket) { PrintTicket pts = new PrintTicket(); pts.PageOrientation = PageOrientation.Portrait; e.CurrentPrintTicket = pts; } }
public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket) { throw new NotSupportedException(); }
public byte[] ProcessData(PrintTicket ticket, byte[] data, string driver, string[] inargs, string[] devsetup) { string[] extraargs = new string[] { "-sDEVICE=" + driver }; return ProcessData(null, ticket, data, inargs, extraargs, devsetup); }
public override void Write(Visual visual, PrintTicket printTicket) { SerializeObjectTree(visual); }
protected byte[] ProcessData(string username, PrintTicket ticket, byte[] data, string[] inargs, string[] extraargs, string[] devsetup) { string[] pagesetup = PostscriptHelper.SetPageDeviceCommand(ticket).ToArray(); string[] args = new string[] { "-dNOPAUSE", "-dBATCH" } .Concat(inargs ?? new string[] { }) .Concat(extraargs ?? new string[] { }) .Concat(new string[] { "-sOutputFile=%stdout" }) .Concat(new string[] { "-c" }) .Concat(devsetup ?? new string[] { }) .Concat(pagesetup) .Concat(new string[] { "-" }) .ToArray(); MemoryStream outstream = new MemoryStream(); MemoryStream errstream = new MemoryStream(); MemoryStream instream = new MemoryStream(data); int exitcode; if (username != null) { exitcode = RunCommandAsUser(username, args, instream, outstream, errstream); } else { exitcode = RunCommand(args, instream, outstream, errstream); } string errstr = Encoding.UTF8.GetString(errstream.ToArray()); if (exitcode != 0) { Logger.Log(LogLevel.Warning, "Ghostscript returned code {0}\n\nError:\n{1}", exitcode, errstr); throw new InvalidOperationException(String.Format("Ghostscript error {0}\n{1}", exitcode, errstr)); } return outstream.ToArray(); }
public static void PrintPreview(Window owner, FormData data) { using (MemoryStream xpsStream = new MemoryStream()) { using (Package package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite)) { string packageUriString = "memorystream://data.xps"; Uri packageUri = new Uri(packageUriString); PackageStore.AddPackage(packageUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUriString); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); Form visual = new Form(data); PrintTicket printTicket = new PrintTicket(); printTicket.PageMediaSize = A4PaperSize; writer.Write(visual, printTicket); FixedDocumentSequence document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); PrintPreviewWindow printPreviewWnd = new PrintPreviewWindow(document); printPreviewWnd.Owner = owner; printPreviewWnd.ShowDialog(); PackageStore.RemovePackage(packageUri); } } }
public void PreparePrinting(PrintTicket printTicket, Size pageSize) { printTicket.PageOrientation = pageSize.Height >= pageSize.Width ? PageOrientation.Portrait : PageOrientation.Landscape; var printExtension = _reportProvider as IReportPrintExtension; if (printExtension != null) printExtension.PreparePrinting(printTicket, pageSize); }