private static void saveAsXPS(string file, DocumentViewModel viewModel) { // Deselect shapes while saving. List <ShapeViewModelBase> selectedItems = new List <ShapeViewModelBase>(viewModel.vm_CanvasViewModel.SelectedItem.Shapes); viewModel.vm_CanvasViewModel.SelectedItem.Clear(); // Get a rectangle representing the page. Rectangle page = viewModel._CommandUtility.GetDocumentRectangle(); try { using (Package package = Package.Open(file, FileMode.Create)) { using (XpsDocument xpsDocument = new XpsDocument(package)) { // Write the document. System.Windows.Xps.XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument); xpsWriter.Write(page); } } } finally { // Reselect shapes. viewModel.vm_CanvasViewModel.SelectedItem.SelectShapes(selectedItems); } }
public static void SaveToPdf(UIElement ui, string name) { //MigraDoc.DocumentObjectModel.Document doc = new MigraDoc.DocumentObjectModel.Document(); //MigraDoc.Rendering.DocumentRenderer renderer = new DocumentRenderer(doc); //MigraDoc.Rendering.PdfDocumentRenderer pdfRenderer = new MigraDoc.Rendering.PdfDocumentRenderer(); //pdfRenderer.PdfDocument = pDoc; //pdfRenderer.DocumentRenderer = renderer; //using (MemoryStream ms = new MemoryStream()) //{ // pdfRenderer.Save(ms, false); // byte[] buffer = new byte[ms.Length]; // ms.Seek(0, SeekOrigin.Begin); // ms.Flush(); // ms.Read(buffer, 0, (int)ms.Length); //} string path = string.Format(name + "_{0}.pdf", DateTime.Now.ToString("MMddyyyy_hhmmss")); FileOperations.EnsureFileFolderExist(path); MemoryStream lMemoryStream = new MemoryStream(); Package package = Package.Open(lMemoryStream, FileMode.Create); System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(package); System.Windows.Xps.XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(ui); doc.Close(); package.Close(); PdfSharp.Xps.XpsModel.XpsDocument pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream); PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, path, 0); }
private void cmdShowAllAnotations_Click(object sender, RoutedEventArgs e) { IList <Annotation> annotations = service.Store.GetAnnotations(); foreach (Annotation annotation in annotations) { // Check for text information. if (annotation.Cargos.Count > 1) { string base64Text = annotation.Cargos[1].Contents[0].InnerText; byte[] decoded = Convert.FromBase64String(base64Text); MemoryStream m = new MemoryStream(); m.Write(decoded, 0, decoded.Length); m.Position = 0; StreamReader r = new StreamReader(m); string annotationXaml = r.ReadToEnd(); MessageBox.Show(annotationXaml); } } PrintDialog dialog = new PrintDialog(); bool? result = dialog.ShowDialog(); if (result != null && result.Value) { System.Windows.Xps.XpsDocumentWriter writer = System.Printing.PrintQueue.CreateXpsDocumentWriter(dialog.PrintQueue); AnnotationDocumentPaginator adp = new AnnotationDocumentPaginator( ((IDocumentPaginatorSource)docReader.Document).DocumentPaginator, service.Store); writer.Write(adp); } }
private void DoThePrint() { FlowDocument copy = mathBox.CloneDocument(); foreach (var mathBox in copy.FindChildren <MathBox>()) { mathBox.BorderThickness = new Thickness(0); } // 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. System.Printing.PrintDocumentImageableArea ia = null; System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.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; //copy.PageWidth = 528; // allow the page to be the natural with of the output device // Send content to the printer. docWriter.Write(paginator); } }
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); }
private void Imprimer() { DocumentPaginator Doc = MEP.Paginer(_Doc); // 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; System.Windows.Xps.XpsDocumentWriter docWriter = PrintQueue.CreateXpsDocumentWriter(ref ia); if (docWriter != null && ia != null) { docWriter.Write(Doc); } }
private void DoThePrint(FlowDocument copy) { // 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. //System.IO.MemoryStream s = new System.IO.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); // Create a XpsDocumentWriter object, implicitly opening a Windows common print dialog, // and allowing the user to select a printer. var theme = ThemeManager.GetAppTheme(Hub.Instance.Settings.Theme); var accent = ThemeManager.GetAccent("VSLight"); ThemeManager.ChangeAppStyle(copy.Resources, accent, theme); // get information about the dimensions of the seleted printer+media. System.Printing.PrintDocumentImageableArea ia = null; System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.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; //copy.PageWidth = 528; // allow the page to be the natural with of the output device // Send content to the printer. docWriter.Write(paginator); } }
private void btnPrintRTB_Click(object sender, RoutedEventArgs e) { //Print RTB file try { FlowDocument document = rtbEditor.Document; //Make copy of FlowDocument for pritning - witch pictures string copyString = XamlWriter.Save(rtbEditor.Document); FlowDocument kopiaFlowDocument = XamlReader.Parse(copyString) as FlowDocument; MemoryStream memorySrteam = new MemoryStream(); //Przygotowanie się do przechowywania zawartości w pamięci System.Printing.PrintDocumentImageableArea ia = null; System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia); //tu następuje otwarcie okno dialogowego drukowania który zwraca prarametr - referencje: ia //parametr (ia) reprezentuje informacje o obszarze obrazowania i wymiarze nośnika. if (docWriter != null && ia != null) { DocumentPaginator paginator = ((IDocumentPaginatorSource)kopiaFlowDocument).DocumentPaginator; ///Dzielenie zawartości na strony. //Change size PageSize and PagePadding of document - for CanvasSize paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight); //Ustawia rozmiar stron zgodnie z wymiarem fizycznym kartki papieru. (793/1122) Thickness t = new Thickness(margines + kopiaFlowDocument.PagePadding.Left); //Ustawiam marginesy wydruku w PagePadding. Należy zastosować korektę o starowy margines drukarki . Tu daje tyle co RichTextBox Domyślnie pobiera z drukarki i wynoszą (5,0,5,0) piksela kopiaFlowDocument.PagePadding = new Thickness( //Ustawienie nowego obszaru zadrukowania strony PagePadding 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)); kopiaFlowDocument.ColumnWidth = double.PositiveInfinity; //Ustawienie szerokości kolumny drukowanej. double.PositiveInfinity - reprezentuje nieskończoności dodatniej. To pole jest stałe. // Send content to the printer. docWriter.Write(paginator); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); memorySrteam.Dispose(); } catch (Exception ex) { ErrorMessage(ex); } }
private void DoThePrint(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 doc = GetPrintFlowDocument(); ForceRenderFlowDocument(doc); // get information about the dimensions of the seleted printer+media. System.Printing.PrintDocumentImageableArea ia = null; System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia); if (docWriter != null && ia != null) { DocumentPaginator paginator = ((IDocumentPaginatorSource)doc).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; doc.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)); doc.ColumnWidth = double.PositiveInfinity; //copy.PageWidth = 528; // allow the page to be the natural with of the output device // Send content to the printer. docWriter.Write(paginator); } }
private void Print() { // create header var cntlHeader = new TechDataHeaderControl(); cntlHeader.SetContents(this.thePackage, this.theDefs, this.theDefaultLang, this.theSubmodel); // create footer var cntlFooter = new TechDataFooterControl(); cntlFooter.SetContents(this.thePackage, this.theDefs, this.theDefaultLang, this.theSubmodel); // render this var bitmapHeader = RenderControl(cntlHeader, 600, 200, false); var bitmapFooter = RenderControl(cntlFooter, 600, 100, false); // create middle part var cntlProps = new TechDataPropertiesControl(); cntlProps.SetContents(this.thePackage, this.theDefs, this.theDefaultLang, this.theSubmodel); var document = cntlProps.CreateFlowDocument( this.thePackage, this.theDefs, this.theDefaultLang, this.theSubmodel); // 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. System.IO.MemoryStream s = new System.IO.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); // 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. System.Printing.PrintDocumentImageableArea ia = null; System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia); if (docWriter != null && ia != null) { // some more definitions var pdefs = new PimpedPaginator.Definition(); pdefs.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight); pdefs.HeaderHeight = 200; pdefs.FooterHeight = 100; pdefs.RepeatTableHeaders = true; // draw header pdefs.Header = (DrawingContext context, Rect bounds, int pageNr) => { context.DrawImage(bitmapHeader, bounds); }; // draw footer pdefs.Footer = (DrawingContext context, Rect bounds, int pageNr) => { context.DrawImage(bitmapFooter, bounds); }; // make suitable paginator var paginator = new PimpedPaginator(copy, pdefs); // 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 = 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 Public.ImageStream RenderXps() { Public.ImageStream renderedImage = new Public.ImageStream(); System.IO.MemoryStream renderedContent = new System.IO.MemoryStream(); String contentUriName = ("memorystream://rendered" + Guid.NewGuid().ToString().Replace("-", "") + ".xps"); Uri contentUri = new Uri(contentUriName, UriKind.Absolute); // FOR TESTING, OUTPUT TO DISK FILE BY CHANGING OPEN FROM MEMORY STREAM TO FILE LOCATION System.IO.Packaging.Package xpsPackage = System.IO.Packaging.Package.Open(renderedContent, System.IO.FileMode.Create); System.IO.Packaging.PackageStore.AddPackage(contentUri, xpsPackage); System.Windows.Xps.Packaging.XpsDocument renderedXpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsPackage, System.IO.Packaging.CompressionOption.Normal, contentUriName); System.Windows.Xps.XpsDocumentWriter xpsWriter = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(renderedXpsDocument); System.Windows.Xps.Packaging.IXpsFixedDocumentSequenceWriter contentSequenceWriter; contentSequenceWriter = renderedXpsDocument.AddFixedDocumentSequence(); List <System.Windows.Xps.Packaging.XpsDocument> xpsContents = new List <System.Windows.Xps.Packaging.XpsDocument> (); // LOAD CORRESPONDENCE RECORD TO SEE IF THERE IS ANY CONTENT AVAILABLE Reference.Correspondence renderCorrespondence = application.CorrespondenceGet(correspondenceId); if (renderCorrespondence == null) { throw new ApplicationException("Unable to load base Correspondence to Render Content."); } if (renderCorrespondence.Content.Count == 0) { throw new ApplicationException("No Content to Render for Correspondence."); } renderCorrespondence.LoadContentAttachments(); foreach (Reference.CorrespondenceContent currentCorrespondenceContent in renderCorrespondence.Content.Values) { System.Windows.Xps.Packaging.XpsDocument xpsContent = null; switch (currentCorrespondenceContent.ContentType) { case Reference.Enumerations.CorrespondenceContentType.Report: #region Generate Report Content Reporting.ReportingServer reportingServer = application.ReportingServerGet(currentCorrespondenceContent.ReportingServerId); if (reportingServer == null) { throw new ApplicationException("Unable to load Reporting Server to Render Content."); } System.Reflection.Assembly reportingServerAssembly = System.Reflection.Assembly.LoadFrom(reportingServer.AssemblyReference); Type reportingServerType = reportingServerAssembly.GetType(reportingServer.AssemblyClassName); if (reportingServerType == null) { throw new ApplicationException("Unable to find Class [" + reportingServer.AssemblyClassName + "] in referenced Assembly [" + reportingServer.AssemblyReference + "]."); } Public.Reporting.IReportingServer reportingServerObject = (Public.Reporting.IReportingServer)Activator.CreateInstance(reportingServerType); Dictionary <String, String> reportParameters = new Dictionary <String, String> (); reportParameters.Add("entityCorrespondenceId", id.ToString()); // SSRS RENDER TIFF, CONVERT TO XPS Public.ImageStream imageStream = reportingServerObject.Render(reportingServer.WebServiceHostConfiguration, currentCorrespondenceContent.ReportName, reportParameters, "image", reportingServer.ExtendedProperties); xpsContent = imageStream.TiffToXps(); xpsContents.Add(xpsContent); #endregion break; case Reference.Enumerations.CorrespondenceContentType.Attachment: #region Load Attachment contentUriName = ("memorystream://attachment" + Guid.NewGuid().ToString().Replace("-", "") + ".xps"); contentUri = new Uri(contentUriName, UriKind.Absolute); System.IO.MemoryStream attachmentStream = new System.IO.MemoryStream(); System.IO.Packaging.Package attachmentPackage = System.IO.Packaging.Package.Open(currentCorrespondenceContent.Attachment); System.IO.Packaging.PackageStore.AddPackage(contentUri, attachmentPackage); xpsContent = new System.Windows.Xps.Packaging.XpsDocument(attachmentPackage, System.IO.Packaging.CompressionOption.Normal, contentUriName); xpsContents.Add(xpsContent); #endregion break; } } #region Merge XPS Contents foreach (System.Windows.Xps.Packaging.XpsDocument currentContentDocument in xpsContents) { foreach (System.Windows.Xps.Packaging.IXpsFixedDocumentReader currentContentDocumentReader in currentContentDocument.FixedDocumentSequenceReader.FixedDocuments) { System.Windows.Xps.Packaging.IXpsFixedDocumentWriter contentDocumentWriter = contentSequenceWriter.AddFixedDocument(); foreach (System.Windows.Xps.Packaging.IXpsFixedPageReader currentContentPageReader in currentContentDocumentReader.FixedPages) { System.Windows.Xps.Packaging.IXpsFixedPageWriter contentPageWriter = contentDocumentWriter.AddFixedPage(); System.Xml.XmlWriter xmlPageWriter = contentPageWriter.XmlWriter; String pageContent = CommonFunctions.XmlReaderToString(currentContentPageReader.XmlReader); #region Resource Dictionaries foreach (System.Windows.Xps.Packaging.XpsResourceDictionary currentXpsDictionary in currentContentPageReader.ResourceDictionaries) { System.Windows.Xps.Packaging.XpsResourceDictionary xpsDictionary = contentPageWriter.AddResourceDictionary(); System.IO.Stream xpsDictionaryStream = xpsDictionary.GetStream(); // GET DESTINATION STREAM TO COPY TO currentXpsDictionary.GetStream().CopyTo(xpsDictionaryStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsDictionary.Uri.ToString(), xpsDictionary.Uri.ToString()); xpsDictionary.Commit(); } #endregion #region Color Contexts foreach (System.Windows.Xps.Packaging.XpsColorContext currentXpsColorContext in currentContentPageReader.ColorContexts) { System.Windows.Xps.Packaging.XpsColorContext xpsColorContext = contentPageWriter.AddColorContext(); System.IO.Stream xpsColorContextStream = xpsColorContext.GetStream(); // GET DESTINATION STREAM TO COPY TO currentXpsColorContext.GetStream().CopyTo(xpsColorContextStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsColorContext.Uri.ToString(), xpsColorContext.Uri.ToString()); xpsColorContext.Commit(); } #endregion #region Fonts foreach (System.Windows.Xps.Packaging.XpsFont currentXpsFont in currentContentPageReader.Fonts) { System.Windows.Xps.Packaging.XpsFont xpsFont = contentPageWriter.AddFont(false); xpsFont.IsRestricted = false; System.IO.MemoryStream deobfuscatedStream = new System.IO.MemoryStream(); currentXpsFont.GetStream().CopyTo(deobfuscatedStream); String fontResourceName = currentXpsFont.Uri.ToString(); fontResourceName = fontResourceName.Split('/')[fontResourceName.Split('/').Length - 1]; if (fontResourceName.Contains(".odttf")) { fontResourceName = fontResourceName.Replace(".odttf", String.Empty); Guid fontGuid = new Guid(fontResourceName); deobfuscatedStream = CommonFunctions.XmlFontDeobfuscate(currentXpsFont.GetStream(), fontGuid); } System.IO.Stream xpsFontStream = xpsFont.GetStream(); // GET DESTINATION STREAM TO COPY TO deobfuscatedStream.CopyTo(xpsFontStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsFont.Uri.ToString(), xpsFont.Uri.ToString()); xpsFont.Commit(); } #endregion #region Images foreach (System.Windows.Xps.Packaging.XpsImage currentXpsImage in currentContentPageReader.Images) { // FILE EXTENSION TO DETERMINE IMAGE TYPE System.Windows.Xps.Packaging.XpsImageType imageType = System.Windows.Xps.Packaging.XpsImageType.TiffImageType; String fileExtension = currentXpsImage.Uri.ToString().Split('.')[1]; switch (fileExtension.ToLower()) { case "jpeg": case "jpg": imageType = System.Windows.Xps.Packaging.XpsImageType.JpegImageType; break; case "png": imageType = System.Windows.Xps.Packaging.XpsImageType.PngImageType; break; case "wdp": imageType = System.Windows.Xps.Packaging.XpsImageType.WdpImageType; break; case "tif": case "tiff": default: imageType = System.Windows.Xps.Packaging.XpsImageType.TiffImageType; break; } System.Windows.Xps.Packaging.XpsImage xpsImage = contentPageWriter.AddImage(imageType); System.IO.Stream xpsImageStream = xpsImage.GetStream(); // GET DESTINATION STREAM TO COPY TO currentXpsImage.GetStream().CopyTo(xpsImageStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsImage.Uri.ToString(), xpsImage.Uri.ToString()); // xpsImage.Uri = currentXpsImage.Uri; xpsImage.Commit(); } #endregion // COPY XAML CONTENT xmlPageWriter.WriteRaw(pageContent); contentPageWriter.Commit(); } contentDocumentWriter.Commit(); } } #endregion contentSequenceWriter.Commit(); renderedXpsDocument.Close(); xpsPackage.Close(); renderedImage.Image = renderedContent; renderedImage.Name = "EntityCorrespondence" + id.ToString() + ".xps"; renderedImage.Extension = "xps"; renderedImage.MimeType = "application/vnd.ms-xpsdocument"; renderedImage.IsCompressed = false; return(renderedImage); }
public static Boolean Creer(DocumentPaginator document, String Chemin) { if (String.IsNullOrWhiteSpace(Chemin)) { return(false); } try { // Convertion du document en xps MemoryStream strm = new MemoryStream(); Package pkg = Package.Open(strm, FileMode.OpenOrCreate); String pack = "pack://" + Guid.NewGuid().ToString() + ".xps"; PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument xpsDoc = new XpsDocument(pkg, CompressionOption.Maximum, pack); XpsSerializationManager xpsSM = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false); xpsSM.SaveAsXaml(document); // Enregistrement du xps dans un fichier tmp String tmpXpsFileName = Path.Combine(Path.GetTempPath(), "Gestion_" + DateTime.Now.Ticks + ".xps"); XpsDocument xpsd = new XpsDocument(tmpXpsFileName, FileAccess.ReadWrite); System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); xw.Write(xpsDoc.GetFixedDocumentSequence()); xpsd.Close(); PdfSharp.Xps.XpsConverter.Convert(tmpXpsFileName, Chemin, 0); //// Convertion du xps en pdf //PdfDocument pdfDoc = new PdfDocument(); //pdfDoc.LoadFromXPS(tmpXpsFileName); //Byte[] pdfFile; //using (MemoryStream stream = new MemoryStream()) //{ // pdfDoc.SaveToStream(stream); // pdfFile = stream.ToArray(); //} //// Ecriture du fichier //ByteArrayToFile(Chemin, pdfFile); //Byte[] pdfFile; //using (MemoryStream stream = new MemoryStream()) //{ // PdfSharp.Xps.XpsModel.XpsDocument xpsDocument = PdfSharp.Xps.XpsModel.XpsDocument.Open(tmpXpsFileName); // PdfSharp.Xps.XpsConverter.ConvertToPdfInMemory(xpsDocument, stream, 0); // xpsDocument.Close(); // pdfFile = stream.ToArray(); //} // Ecriture du fichier //ByteArrayToFile(Chemin, pdfFile); // Suppression du fichier tmp File.Delete(tmpXpsFileName); return(true); } catch { } return(false); }
public System.Windows.Xps.Packaging.XpsDocument TiffToXps() { System.Drawing.Image[] tiffPages = TiffPages(); // INITIALIZE XPS System.IO.MemoryStream xpsStream = new System.IO.MemoryStream(); System.IO.Packaging.Package xpsPackage = System.IO.Packaging.Package.Open(xpsStream, System.IO.FileMode.Create); System.Windows.Xps.Packaging.XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsPackage); xpsDocument.Uri = new Uri("http://www.quebesystems.com", UriKind.Absolute); System.Windows.Xps.XpsDocumentWriter xpsWriter = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(xpsDocument); // SET UP XPS DOCUMENT AND FIRST FIXED DOCUMENT System.Windows.Xps.Packaging.IXpsFixedDocumentSequenceWriter xpsFixedDocumentSequenceWriter = xpsDocument.AddFixedDocumentSequence(); System.Windows.Xps.Packaging.IXpsFixedDocumentWriter xpsFixedDocumentWriter = xpsFixedDocumentSequenceWriter.AddFixedDocument(); // WRITE TIFF IMAGES AS PAGES IN XPS foreach (System.Drawing.Image currentTiffPage in tiffPages) { // ADD A NEW PAGE, THEN EMBED IMAGE TO THE PAGE System.Windows.Xps.Packaging.IXpsFixedPageWriter xpsFixedPageWriter = xpsFixedDocumentWriter.AddFixedPage(); System.Windows.Xps.Packaging.XpsImage xpsImage = xpsFixedPageWriter.AddImage(System.Windows.Xps.Packaging.XpsImageType.TiffImageType); System.IO.Stream xpsImageStream = xpsImage.GetStream(); // GET DESTINATION STREAM TO COPY TO // COPY TIFF IMAGE TO XPS IMAGE currentTiffPage.Save(xpsImageStream, System.Drawing.Imaging.ImageFormat.Tiff); xpsImage.Commit(); // IMAGE IS EMBED, BUT PAGE HAS NOT BEEN CREATED, CREATE PAGE System.Xml.XmlWriter xmlPageWriter = xpsFixedPageWriter.XmlWriter; xmlPageWriter.WriteStartElement("FixedPage"); // XPS PAGE STARTS WITH A FIXED PAGE TAG xmlPageWriter.WriteAttributeString("xmlns", "http://schemas.microsoft.com/xps/2005/06"); xmlPageWriter.WriteAttributeString("xml:lang", "en-US"); xmlPageWriter.WriteAttributeString("Width", currentTiffPage.Width.ToString()); xmlPageWriter.WriteAttributeString("Height", currentTiffPage.Height.ToString()); xmlPageWriter.WriteStartElement("Path"); xmlPageWriter.WriteAttributeString("Data", "M 0,0 H " + currentTiffPage.Width.ToString() + " V " + currentTiffPage.Height.ToString() + " H 0 z"); xmlPageWriter.WriteStartElement("Path.Fill"); xmlPageWriter.WriteStartElement("ImageBrush"); xmlPageWriter.WriteAttributeString("TileMode", "None"); xmlPageWriter.WriteAttributeString("ViewboxUnits", "Absolute"); xmlPageWriter.WriteAttributeString("ViewportUnits", "Absolute"); xmlPageWriter.WriteAttributeString("Viewbox", "0, 0, " + currentTiffPage.Width.ToString() + ", " + currentTiffPage.Height.ToString()); xmlPageWriter.WriteAttributeString("Viewport", "0, 0, " + currentTiffPage.Width.ToString() + ", " + currentTiffPage.Height.ToString()); xmlPageWriter.WriteAttributeString("ImageSource", xpsImage.Uri.ToString()); xmlPageWriter.WriteEndElement(); // IMAGE BRUSH xmlPageWriter.WriteEndElement(); // PATH.FILL xmlPageWriter.WriteEndElement(); // PATH // PAGE END ELEMENT xmlPageWriter.WriteEndElement(); // FIXED PAGE // PAGE COMMIT xpsFixedPageWriter.Commit(); } // COMMIT DOCUMENT WRITER xpsFixedDocumentWriter.Commit(); xpsFixedDocumentSequenceWriter.Commit(); xpsDocument.Close(); xpsPackage.Close(); //System.IO.FileStream fileStream = new System.IO.FileStream (@"C:\MERCURY\TEST7.XPS", System.IO.FileMode.Create); //fileStream.Write (xpsStream.ToArray (), 0, Convert.ToInt32 (xpsStream.Length)); //fileStream.Flush (); //fileStream.Close (); String contentUriName = ("memorystream://content" + Guid.NewGuid().ToString().Replace("-", "") + ".xps"); Uri contentUri = new Uri(contentUriName, UriKind.Absolute); System.IO.Packaging.Package attachmentPackage = System.IO.Packaging.Package.Open(xpsStream); System.IO.Packaging.PackageStore.AddPackage(contentUri, attachmentPackage); System.Windows.Xps.Packaging.XpsDocument xpsContent = new System.Windows.Xps.Packaging.XpsDocument(attachmentPackage, System.IO.Packaging.CompressionOption.Normal, contentUriName); return(xpsContent); }
protected MatrixBase() { this.CommandCopyToClipboard = new DelegateCommand( this.CopyToClipboard, () => { return(this.HasData); }); this.CommandPrint = new DelegateCommand( () => { var section = Helpers.FormatHelper.MatrixToFlowDocumentSectionWithTable(this); var flowDocument = new System.Windows.Documents.FlowDocument(section); flowDocument.FontSize = 11d; System.Windows.Controls.PrintDialog pd = new System.Windows.Controls.PrintDialog(); System.Printing.PrintTicket pt = new System.Printing.PrintTicket(); pt.PageOrientation = System.Printing.PageOrientation.Landscape; pd.PrintTicket = pd.PrintQueue.MergeAndValidatePrintTicket(pd.PrintQueue.DefaultPrintTicket, pt).ValidatedPrintTicket; System.Windows.Documents.IDocumentPaginatorSource fdd = flowDocument; flowDocument.PageWidth = pd.PrintableAreaWidth; flowDocument.PageHeight = pd.PrintableAreaHeight; flowDocument.ColumnWidth = pd.PrintableAreaWidth; flowDocument.PagePadding = new Thickness(30.0, 50.0, 20.0, 30.0); flowDocument.IsOptimalParagraphEnabled = true; flowDocument.IsHyphenationEnabled = true; var ms = new System.IO.MemoryStream(); using (var pkg = System.IO.Packaging.Package.Open(ms, System.IO.FileMode.Create)) { using (System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(pkg)) { System.Windows.Xps.XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(fdd.DocumentPaginator); } } ms.Position = 0; var pkg2 = System.IO.Packaging.Package.Open(ms); // Read the XPS document into a dynamically generated // preview Window var url = new Uri("memorystream://printstream"); System.IO.Packaging.PackageStore.AddPackage(url, pkg2); try { using (System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(pkg2, System.IO.Packaging.CompressionOption.SuperFast, url.AbsoluteUri)) { System.Windows.Documents.FixedDocumentSequence fds = doc.GetFixedDocumentSequence(); Window wnd = new Window(); wnd.Title = string.Format("Предварительный просмотр :: {0}", this.Header); wnd.Owner = Application.Current.MainWindow; System.Windows.Media.TextOptions.SetTextFormattingMode(wnd, System.Windows.Media.TextFormattingMode.Display); wnd.Padding = new Thickness(2); wnd.Content = new System.Windows.Controls.DocumentViewer() { Document = fds, }; wnd.ShowDialog(); } } finally { System.IO.Packaging.PackageStore.RemovePackage(url); } }, () => { return(this.HasData); }); this.CommandRefresh = new DelegateCommand(this.Build, () => this.HasData); }
public FlowDocumentPackage(string xamlFlowDocument) { toDispose = new List <IDisposable>(); TempFolder = new DirectoryInfo(TempPath + "\\XamlToPDF\\" + DateTime.Now.Ticks.ToString()); if (!TempFolder.Exists) { TempFolder.Create(); } /*Stream = File.Create(TempFolder.FullName + "\\a.xps"); * toDispose.Add(Stream); * * Package = Package.Open(Stream, FileMode.Create, FileAccess.ReadWrite); * toDispose.Add(Package); * * pack = "pack://" + DateTime.Now.Ticks + ".xps"; * PackageStore.AddPackage(new Uri(pack), Package); * * * * XpsDoc = new XpsDocument(Package, CompressionOption.NotCompressed, pack);*/ XpsDoc = new XpsDocument(TempFolder.FullName + "\\a.xps", FileAccess.ReadWrite, CompressionOption.NotCompressed); toDispose.Add(new InlineDisposable(() => XpsDoc.Close())); System.Windows.Xps.XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(XpsDoc); xamlFlowDocument = ReplaceImages(writer, xamlFlowDocument); flowDoc = XamlServices.Parse(xamlFlowDocument) as FlowDocument; IDocumentPaginatorSource src = flowDoc as IDocumentPaginatorSource; if (double.IsNaN(flowDoc.PageHeight)) { flowDoc.PageHeight = 792; } if (double.IsNaN(flowDoc.PageWidth)) { flowDoc.PageWidth = 612; } /*XPolicy = new XpsPackagingPolicy(XpsDoc); * toDispose.Add(XPolicy); * * XSrm = new XpsSerializationManager(XPolicy, false); * toDispose.Add(XSrm);*/ DocumentPaginator pgn = src.DocumentPaginator; //XSrm.SaveAsXaml(pgn); writer.Write(pgn); var seq = XpsDoc.GetFixedDocumentSequence(); DocumentReference reff = seq.References.First(); Document = reff.GetDocument(true); }
private string ReplaceImages(System.Windows.Xps.XpsDocumentWriter writer, string xamlFlowDocument) { XDocument doc = XDocument.Parse(xamlFlowDocument); foreach (XElement img in doc.Descendants().Where(x => x.Name.LocalName == "Image" && x.Attributes().Any(a => a.Name.LocalName == "Source"))) { var at = img.Attributes().FirstOrDefault(x => x.Name.LocalName == "Source"); if (at == null) { continue; } string url = at.Value; //if (url.StartsWith("http://") || url.StartsWith("https://")) { string urlKey = at.Value.ToLower(); DownloadItem file = null; if (!Cache.TryGetValue(urlKey, out file)) { file = new DownloadItem { FilePath = TempFolder + "\\" + Cache.Count + ".dat", Url = url }; Cache[urlKey] = file; } file.Nodes.Add(img); } } Parallel.ForEach(Cache.Values, DownloadFile); foreach (var item in Cache.Values) { //var pp = Package.CreatePart(new Uri(item.PackgeUri, UriKind.Relative), "image/jpeg", CompressionOption.NotCompressed); //using (Stream ss = pp.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite)) { // using (FileStream fs = File.OpenRead(item.FilePath)) { // fs.CopyTo(ss); // } //} //Trace.WriteLine(pack + item.PackgeUri); ////Package.CreateRelationship(new Uri(pack + item.PackgeUri), TargetMode.External, "http://schemas.microsoft.com/xps/2005/06/required-resource"); //foreach (var node in item.Nodes) //{ // node.Value = pack + ",,," + item.PackgeUri; //} foreach (var node in item.Nodes) { node.Name = XName.Get("InlineImage", node.Name.NamespaceName); XCData d = new XCData(Convert.ToBase64String(File.ReadAllBytes(item.FilePath))); node.Add(d); XAttribute a = node.Attributes().FirstOrDefault(x => x.Name.LocalName == "Source"); a.Remove(); } } using (StringWriter sw = new StringWriter()){ doc.Save(sw, SaveOptions.OmitDuplicateNamespaces); xamlFlowDocument = sw.ToString(); }; return(xamlFlowDocument); }