public PreviewWindow(CustomDocumentPaginator documentPaginator) { InitializeComponent(); //xps stream = new MemoryStream(); Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite); var uri = new Uri(@"memorystream://myXps.xps"); //already in packagestore, so remove if (PackageStore.GetPackage(uri) != null) { PackageStore.RemovePackage(uri); } PackageStore.AddPackage(uri, package); var xpsDoc = new XpsDocument(package); xpsDoc.Uri = uri; XpsDocument.CreateXpsDocumentWriter(xpsDoc).Write(documentPaginator); FixedDocumentSequence fds = xpsDoc.GetFixedDocumentSequence(); dv1.Document = (IDocumentPaginatorSource)fds; }
void Window2_Loaded(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); XpsDocument xpsdoc = new XpsDocument("xml.xps", System.IO.FileAccess.Read); FixedDocumentSequence fds = xpsdoc.GetFixedDocumentSequence(); documentViewer.Document = fds.References[0].GetDocument(true); }
private void Window_Loaded(object sender, EventArgs e) { XpsDocument doc = new XpsDocument("test.xps", FileAccess.ReadWrite); docViewer.Document = doc.GetFixedDocumentSequence(); doc.Close(); }
private void btnPrint_Click(object sender, EventArgs e) { //REFACTOR ME dtgParentReport.Update(); System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog(); Nullable<bool> print = printDialog.ShowDialog(); if (print == true) { try { XpsDocument xpsDocument = new XpsDocument("C:\\FixedDocumentSequence.xps", FileAccess.ReadWrite); FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence(); printDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job"); } catch (UnauthorizedAccessException e1) { const string message = "Unauthoried to access that printer."; const string caption = "Unauthoried Access"; var result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (PrintDialogException e2) { const string message = "Unknow error occurred."; const string caption = "Error Printing"; var result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public static void SaveToPdf(this FlowDocument flowDoc, string filename) { MemoryStream xamlStream = new MemoryStream(); XamlWriter.Save(flowDoc, xamlStream); File.WriteAllBytes("d:\\file.xaml", xamlStream.ToArray()); IDocumentPaginatorSource text = flowDoc as IDocumentPaginatorSource; xamlStream.Close(); MemoryStream memoryStream = new MemoryStream(); Package pkg = Package.Open(memoryStream, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://temp.xps"; PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); DocumentPaginator pgn = text.DocumentPaginator; rsm.SaveAsXaml(pgn); MemoryStream xpsStream = new MemoryStream(); var writer = new XpsSerializerFactory().CreateSerializerWriter(xpsStream); writer.Write(doc.GetFixedDocumentSequence()); MemoryStream outStream = new MemoryStream(); NiXPS.Converter.XpsToPdf(xpsStream, outStream); File.WriteAllBytes("file.pdf", outStream.ToArray()); }
private void window_Loaded(object sender, RoutedEventArgs e) { doc = new XpsDocument("ch19.xps", FileAccess.ReadWrite); docViewer.Document = doc.GetFixedDocumentSequence(); service = AnnotationService.GetService(docViewer); if (service == null) { Uri annotationUri = PackUriHelper.CreatePartUri(new Uri("AnnotationStream", UriKind.Relative)); Package package = PackageStore.GetPackage(doc.Uri); PackagePart annotationPart = null; if (package.PartExists(annotationUri)) { annotationPart = package.GetPart(annotationUri); } else { annotationPart = package.CreatePart(annotationUri, "Annotations/Stream"); } // Load annotations from the package. AnnotationStore store = new XmlStreamStore(annotationPart.GetStream()); service = new AnnotationService(docViewer); service.Enable(store); } }
private static void ShowXpsPreview(XpsDocument xpsDocument) { var previewWindow = new Window(); var docViewer = new DocumentViewer(); previewWindow.Content = docViewer; docViewer.Document = xpsDocument.GetFixedDocumentSequence(); previewWindow.ShowDialog(); }
private void HelpView_OnLoaded(object sender, RoutedEventArgs e) { var directory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); directory = Path.Combine(directory, "UserGuide"); var fileName = Path.Combine(directory, "HowToUseGuide.xps"); var doc = new XpsDocument(fileName, FileAccess.Read); HelpDocumentViewer.Document = doc.GetFixedDocumentSequence(); }
public static DeckModel OpenXPS(string file) { try { Misc.ProgressBarForm progressForm = new UW.ClassroomPresenter.Misc.ProgressBarForm("Opening \"" + file + "\"..."); progressForm.Show(); //Open Xps Document XpsDocument xpsDocument = null; xpsDocument = new XpsDocument(file, FileAccess.Read); //Create two DocumentPaginators for the XPS document. One is for local display, the other one is for the delivery to students. DocumentPaginator paginator = xpsDocument.GetFixedDocumentSequence().DocumentPaginator; //Create Deck Model Guid deckGuid = Guid.NewGuid(); DeckModel deck = new DeckModel(deckGuid, DeckDisposition.Empty, file); using (Synchronizer.Lock(deck.SyncRoot)) { deck.IsXpsDeck = true; //Iterate over all pages for (int i = 0; i < paginator.PageCount; i++) { DocumentPage page = paginator.GetPage(i); SlideModel newSlideModel = CreateSlide(page, deck); //Create a new Entry + reference SlideModel TableOfContentsModel.Entry newEntry = new TableOfContentsModel.Entry(Guid.NewGuid(), deck.TableOfContents, newSlideModel); //Lock the TOC using (Synchronizer.Lock(deck.TableOfContents.SyncRoot)) { //Add Entry to TOC deck.TableOfContents.Entries.Add(newEntry); } //Update the Progress Bar progressForm.UpdateProgress(0, paginator.PageCount , i+1); } } //Close Progress Bar progressForm.Close(); return deck; } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.ToString()); } GC.Collect(); return null; }
public void ViewDocument(string fileName) { if (System.IO.File.Exists(fileName) == true) { XpsDocument xpsDocument = new XpsDocument(fileName, System.IO.FileAccess.Read); this.Viewer.Document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); } }
public void OnLoaded(object sender, RoutedEventArgs args) { XpsDocument document = new XpsDocument(Window1.CombineFileInCurrentDirectory("CSharp 3.0 Specification.xps"), System.IO.FileAccess.Read); FixedDocument doc = new FixedDocument(); FixedDocumentSequence fixedDoc = document.GetFixedDocumentSequence(); viewer.Document = fixedDoc; viewer.FitToHeight(); }
public MarkingTool(MainUI main) { this.InitializeComponent(); // Insert code required on object creation below this point. this.main = main; doc = main.curDoc.getXPSCopy(); if (doc != null) docView.Document = doc.GetFixedDocumentSequence(); }
public HelpWindow() { InitializeComponent(); try { XpsDocument doc = new XpsDocument("zLabels User Guide.xps", FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); } catch(Exception ex) { MessageBox.Show("Couldn't open help document.\n" + ex.Message, "Even Help Can't Help"); } }
private void LoadQuickStartToDocummentViewer() { string fileName = @"Quick Start Guide.xps"; XpsDocument document = new XpsDocument(fileName, FileAccess.Read); this.documentViewer.Document = document.GetFixedDocumentSequence(); document.Close(); this.documentViewer.FitToWidth(); var contentHost = this.documentViewer.Template.FindName("PART_ContentHost", this.documentViewer) as ScrollViewer; var grid = contentHost?.Parent as Grid; grid?.Children.RemoveAt(0); }
public XpsPaginator(byte[] xpsDocument, string xpsPackageUri) { var packageUri = new Uri(xpsPackageUri); package = PackageStore.GetPackage(packageUri); if (package == null) { stream = new MemoryStream(xpsDocument); package = Package.Open(stream, FileMode.Open, FileAccess.Read); PackageStore.AddPackage(packageUri, package); } document = new XpsDocument(package, CompressionOption.Fast, xpsPackageUri); Sequence = document.GetFixedDocumentSequence(); }
private void btnPrintInvoke_Click(object sender, RoutedEventArgs e) { PrintDialog pDialog = new PrintDialog(); pDialog.PageRangeSelection = PageRangeSelection.AllPages; pDialog.UserPageRangeEnabled = true; Nullable<Boolean> print = pDialog.ShowDialog(); if (print == true) { XpsDocument xpsDocument = new XpsDocument("Entity.xps", FileAccess.ReadWrite); FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence(); pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job"); } }
public void Print(XpsDocument document) { // Create the print dialog object and set options PrintDialog pDialog = new PrintDialog(); pDialog.PageRangeSelection = PageRangeSelection.AllPages; pDialog.UserPageRangeEnabled = true; // Display the dialog. This returns true if the user presses the Print button. Nullable<Boolean> print = pDialog.ShowDialog(); if (print == true) { FixedDocumentSequence fixedDocSeq = document.GetFixedDocumentSequence(); pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Nieko Model Print job"); } }
/// <summary> /// Loads the specified DocumentPaginatorWrapper document for print preview. /// </summary> public void LoadDocument(DocumentPaginatorWrapper document) { m_Document = document; string temp = System.IO.Path.GetTempFileName(); if (File.Exists(temp)) { File.Delete(temp); } XpsDocument xpsDoc = new XpsDocument(temp, FileAccess.ReadWrite); XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); xpsWriter.Write(document); documentViewer.Document = xpsDoc.GetFixedDocumentSequence(); xpsDoc.Close(); }
private void PreviewClick(object sender, RoutedEventArgs e) { var printDialog = new PrintDialog(); var paginator = new Paginador(new ServicoDados().ObterClientes(), new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight)); using (var xpsDocument = new XpsDocument(Path.GetRandomFileName(), FileAccess.ReadWrite)) { var writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(paginator); var previewWindow = new PrintPreview { Document = xpsDocument.GetFixedDocumentSequence() }; previewWindow.ShowDialog(); } }
public UserGuide() { this.InitializeComponent(); // Insert code required on object creation below this point. try { string location = System.IO.Path.Combine(Environment.CurrentDirectory, @"..\..\Documents\UserGuide.xps"); XpsDocument xps = new XpsDocument(location, System.IO.FileAccess.Read); docView.Document = xps.GetFixedDocumentSequence(); } catch (Exception e) { } }
public static void DoPreview(string title, System.Windows.Media.Visual visual) { string fileName = System.IO.Path.GetTempFileName(); try { // write the XPS document using (XpsDocument doc = new XpsDocument(fileName, FileAccess.ReadWrite)) { XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(visual); } // Read the XPS document into a dynamically generated // preview Window using (XpsDocument doc = new XpsDocument(fileName, FileAccess.Read)) { FixedDocumentSequence fds = doc.GetFixedDocumentSequence(); string s = _previewWindowXaml; s = s.Replace("@@TITLE", title.Replace("'", "'")); using (var reader = new System.Xml.XmlTextReader(new StringReader(s))) { Window preview = System.Windows.Markup.XamlReader.Load(reader) as Window; DocumentViewer dv1 = LogicalTreeHelper.FindLogicalNode(preview, "dv1") as DocumentViewer; dv1.Document = fds as IDocumentPaginatorSource; preview.ShowDialog(); } } } finally { if (File.Exists(fileName)) { try { File.Delete(fileName); } catch//temporary file anyway so doesn't matter if can't delete { } } } }
void Window1_Loaded(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); XpsDocument xd = new XpsDocument("annotation.xps", System.IO.FileAccess.ReadWrite); dv.Document = xd.GetFixedDocumentSequence(); ans = new AnnotationService(dv); fs= new FileStream( "annotation.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); ans.Enable(new XmlStreamStore(fs)); ans.Store.AutoFlush = true; }
/// <summary> /// Restores a <see cref="Visual"/> from an array of bytes. /// </summary> /// <param name="data">The data to restore a <see cref="Visual"/> from.</param> /// <returns>The restored <see cref="Visual"/>.</returns> public static Visual LoadVisualFromByteArray(byte[] data) { // Open new package MemoryStream stream = new MemoryStream(data); Package pack = Package.Open(stream); Uri packUri = new Uri(@"memorystream://" + Guid.NewGuid().ToString(), UriKind.Absolute); PackageStore.AddPackage(packUri,pack); // Create new xps document based on the package opened XpsDocument doc = new XpsDocument(pack,CompressionOption.Normal,packUri.AbsoluteUri); Visual v = doc.GetFixedDocumentSequence().DocumentPaginator.GetPage(0).Visual; PackageStore.RemovePackage(packUri); pack.Close(); return v; }
internal IDocumentPaginatorSource DocumentOutput() { IDocumentPaginatorSource source = null; try { using (XpsDocument xpsDocument = new XpsDocument(DirectoriFileSave, FileAccess.Read)) { source = xpsDocument?.GetFixedDocumentSequence(); } } catch (Exception ex) { ShowError(ex.Message); } return(source); }
/// <summary> /// Loads the specified FlowDocument document for print preview. /// </summary> public void LoadDocument(FlowDocument document) { mDocument = document; string temp = System.IO.Path.GetTempFileName(); if (File.Exists(temp) == true) File.Delete(temp); XpsDocument xpsDoc = new XpsDocument(temp, FileAccess.ReadWrite); XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); xpsWriter.Write(((FlowDocument)document as IDocumentPaginatorSource).DocumentPaginator); documentViewer.Document = xpsDoc.GetFixedDocumentSequence(); xpsDoc.Close(); }
private void cmdShowFlow_Click(object sender, RoutedEventArgs e) { if (File.Exists("test2.xps")) File.Delete("test2.xps"); using (FileStream fs = File.Open("FlowDocument1.xaml", FileMode.Open)) { FlowDocument doc = (FlowDocument)XamlReader.Load(fs); XpsDocument xpsDocument = new XpsDocument("test2.xps", FileAccess.ReadWrite); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)doc).DocumentPaginator); // Display the new XPS document in a viewer. docViewer.Document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); } }
public MainWindow() { CompositionTarget.Rendering += CompositionTargetRendering; InitializeComponent(); viewModel = new ViewModel(); DataContext = viewModel; //bind dataGrids viewModel.DataGridMass = dataGridMass; viewModel.DataGridSpeed = dataGridSpeed; string taskDocName = "Task.xps"; string theoryDocName = "Theory.xps"; XpsDocument taskXpsDocument= new XpsDocument(System.IO.Path.Combine(Environment.CurrentDirectory, taskDocName),FileAccess.Read); XpsDocument theoryXpsDocument = new XpsDocument(System.IO.Path.Combine(Environment.CurrentDirectory, theoryDocName), FileAccess.Read); TaskDocumentViewer.Document = taskXpsDocument.GetFixedDocumentSequence(); TheoryDocumentViewer.Document = theoryXpsDocument.GetFixedDocumentSequence(); }
public void ShowDocument(string file) { YellowstonePathology.Business.OrderIdParser orderIdParser = new Business.OrderIdParser(file); string fileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser); fileName += file + ".xps"; FileStream fileStream = File.OpenRead(fileName); byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); MemoryStream memoryStream = new MemoryStream(bytes); string tempPath = "pack://" + file + ".xps"; System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream); m_Uri = new Uri(tempPath); System.IO.Packaging.PackageStore.AddPackage(m_Uri, package); m_Document = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum, tempPath); FixedDocumentSequence fixedDocumentSequence = m_Document.GetFixedDocumentSequence(); this.DocumentViewerReports.Document = fixedDocumentSequence as IDocumentPaginatorSource; }
public static IDocumentPaginatorSource CreateXpsDocument(MemoryStream ms, string ss) { if (ms != null) { try { System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(ms, FileMode.Open); string memoryStreamUri = "memorystream://printstream" + ss; Uri packageUri = new Uri(memoryStreamUri); try { System.IO.Packaging.PackageStore.RemovePackage(packageUri); } catch { } System.IO.Packaging.PackageStore.AddPackage(packageUri, package); XpsDocument xps = new XpsDocument(package, System.IO.Packaging.CompressionOption.SuperFast, memoryStreamUri); FixedDocumentSequence retValue = xps.GetFixedDocumentSequence(); return retValue; } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } } return null; }
private void LoadDocument() { var doc = new XpsDocument(FilepathXps, FileAccess.Read); Document = doc.GetFixedDocumentSequence(); }
private void Load() { XpsDocument doc = new XpsDocument("Documents/Merge_Excel.xps", System.IO.FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); }
private void Window_Activated(object sender, EventArgs e) { try { ReportDocument reportDocument = new ReportDocument(); StreamReader reader = new StreamReader(new FileStream(@"Templates\RequestReport.xaml", FileMode.Open, FileAccess.Read)); reportDocument.XamlData = reader.ReadToEnd(); reportDocument.XamlImagePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Templates\"); reader.Close(); ReportData data = new ReportData(); DataAccess da = new DataAccess(); // Таблица ТОВАРЫ В НАКЛАДНОЙ DataTable dt = new DataTable("mtable"); // описываем столбцы таблицы dt.Columns.Add("t1", typeof(string)); dt.Columns.Add("t2", typeof(string)); dt.Columns.Add("t3", typeof(string)); dt.Columns.Add("t4", typeof(string)); dt.Columns.Add("t5", typeof(string)); dt.Columns.Add("t6", typeof(string)); dt.Columns.Add("t7", typeof(string)); dt.Columns.Add("t8", typeof(string)); decimal sum1 = 0; // забиваем таблицу данными if (items == null) { items = da.GetSparesDemand(); } int maxLength = 40; try { for (int i = 0; i < items.Count; i++) { string nm = items[i].name; nm = nm.Substring(0, Math.Min(nm.Length, maxLength)); if (items[i].name.Length > maxLength) { nm += "..."; } decimal r1 = items[i].q_demand.Value; decimal r2 = (decimal)items[i].QRest.Value; decimal r = (r1 - r2); sum1 += r; dt.Rows.Add(new object[] { (i + 1).ToString(), nm, items[i].BrandName, items[i].codeShatem, items[i].code, items[i].q_demand, items[i].QRest, r }); } } catch (Exception exc) { Marvin.Instance.Log(exc.Message); throw exc; } string strDate = DateTime.Now.Day.ToString(); string mnth = ""; switch (DateTime.Now.Month) { case 1: mnth = "января"; break; case 2: mnth = "февраля"; break; case 3: mnth = "марта"; break; case 4: mnth = "апреля"; break; case 5: mnth = "мая"; break; case 6: mnth = "июня"; break; case 7: mnth = "июля"; break; case 8: mnth = "августа"; break; case 9: mnth = "сентября"; break; case 10: mnth = "октября"; break; case 11: mnth = "ноября"; break; case 12: mnth = "декабря"; break; } strDate += " " + mnth + " " + DateTime.Now.Year + " г."; data.ReportDocumentValues.Add("p1", strDate); // print date is now data.ReportDocumentValues.Add("sum1", sum1); data.DataTables.Add(dt); DateTime dateTimeStart = DateTime.Now; // start time measure here XpsDocument xps = reportDocument.CreateXpsDocument(data); documentViewer.Document = xps.GetFixedDocumentSequence(); } catch (Exception ex) { Marvin.Instance.Log(ex.Message); // show exception MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop); } }
private void selection(string prev_next) { //按照文章编号循环 //FixedDocument fixedDocumentPipei = new FixedDocument(); //var pageContent1 = new PageContent(); int i = current_paper; while (i >= 0 && i < paperList.Count) { string strFilepath = MainWindow.path_translate(paperList[i].xps文件); //string strOutput = "c://1.xps"; //Split(strFilepath, strOutput); XpsDocument xpsDocument = new XpsDocument(strFilepath, System.IO.FileAccess.Read); //查找文件里面的内容 StringBuilder sb = new StringBuilder(); var reader = xpsDocument.FixedDocumentSequenceReader; foreach (var document in reader.FixedDocuments) { int pageCount = document.FixedPages.Count; int j = current_page; if (current_page == 0) { j = 1; } while (j <= pageCount - 1 && j >= 1) { //if (current_page != 0) //{ if (prev_next == "next") { j++; } else { j--; } //} var page = document.FixedPages[j - 1]; //提取一页文字 XmlReader xrdr = page.XmlReader; while (xrdr.Read()) { switch (xrdr.NodeType) { case XmlNodeType.Element: if (xrdr.Name == "Glyphs") { sb.Append(xrdr["UnicodeString"]); } break; default: break; } } //关键词匹配 if (sb.ToString().IndexOf(keyword) > -1) { int pageNumber = page.PageNumber; documentViewer.Document = xpsDocument.GetFixedDocumentSequence(); documentViewer.GoToPage(j); xpsDocument.Close(); //更新文本框数据 string text = title + "\r\n" + sb.ToString(); xpsReferTabItemUserControl.SetText(text); return; //var fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence(); //DocumentReference docReference = xpsDoc.GetFixedDocumentSequence().References[documentNumber-1]; //FixedDocument doc = docReference.GetDocument(false); //PageContent content = doc.Pages[pageNumber]; //JsonSerializerSettings settings = new JsonSerializerSettings(); //settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //PageContent ss = JsonConvert.DeserializeObject<PageContent>(JsonConvert.SerializeObject(content, settings)); //MemoryStream ms = new MemoryStream(); //BinaryFormatter bf = new BinaryFormatter(); //bf.Serialize(ms, content); //ms.Position = 0; //PageContent ss = bf.Deserialize(ms) as PageContent; //fixedDocumentPipei.Pages.Add(ss); } sb.Clear(); //current_page = j; } } if (prev_next == "next") { i++; } else { i--; } current_paper = i; } }
private void CreateButtonClick(object sender, RoutedEventArgs e) { Logger.Write("Entering CreateButtonClick method"); var tab = TabControl.SelectedItem as TabItem; if (tab != null) { var reportProperty = tab.Content as UserControl; if (reportProperty != null) { // Create report IReport reportTemplate = null; IEnumerable <ReportItem> workItems = null; var selectedItem = TabControl.SelectedItem as TabItem; var project = projects[selectedItem]; reportTemplate = project.SelectedReport; workItems = project.WorkItems; var ms = new MemoryStream(); var pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); var pack = string.Format("pack://{0}.xps", Guid.NewGuid()); PackageStore.AddPackage(new Uri(pack), pkg); var compressionOption = CompressionOption.NotCompressed; var document = new XpsDocument(pkg, compressionOption, pack); var report = reportTemplate.Create(workItems); var writer = XpsDocument.CreateXpsDocumentWriter(document); writer.Write(report.DocumentPaginator); // Create doc var doc = new DocumentViewer { Document = document.GetFixedDocumentSequence() }; // Remove toolbar from DocumentViewer var contentHost = doc.Template.FindName("PART_ContentHost", doc) as ScrollViewer; if (contentHost != null) { var grid = contentHost.Parent as Grid; if (grid != null) { grid.Children.RemoveAt(0); } } doc.FitToMaxPagesAcross(1); var newReportTab = new TabItem { Header = string.Format("Report #{0}:{1}", reportNumber, reportTemplate.Description), Content = doc }; reportNumber++; TabControl.Items.Insert(1, newReportTab); TabControl.SelectedItem = newReportTab; projects[newReportTab] = project; TabSelectionChanged(null, null); } } }
private void Load() { XpsDocument doc = new XpsDocument("Documents/WhatDo.xps", FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); }
/// <summary> /// Window has been activated /// </summary> /// <param name="sender">sender</param> /// <param name="e">event details</param> private void Window_Activated(object sender, EventArgs e) { if (!_firstActivated) { return; } _firstActivated = false; try { ReportDocument reportDocument = new ReportDocument(); StreamReader reader = new StreamReader(new FileStream(@"Templates\SimpleReport.xaml", FileMode.Open, FileAccess.Read)); reportDocument.XamlData = reader.ReadToEnd(); reportDocument.XamlImagePath = Path.Combine(Environment.CurrentDirectory, @"Templates\"); reader.Close(); ReportData data = new ReportData(); // set constant document values data.ReportDocumentValues.Add("PrintDate", DateTime.Now); // print date is now //*************PRUEBAS************** Run Run1 = new Run("Registro Médico No. "); Run Run2 = new Run("Fecha" + DateTime.Today.Date); Label lblRegistro = new Label(); lblRegistro.Content = "99999"; InlineUIContainer lInlineUiContainer = new InlineUIContainer(); lInlineUiContainer.BaselineAlignment = BaselineAlignment.Bottom; lInlineUiContainer.Child = lblRegistro; Paragraph lParagraph = new Paragraph(); lParagraph.Inlines.Add(Run1); lParagraph.Inlines.Add(lInlineUiContainer); lParagraph.Inlines.Add(Run2); //*********************************** data.ReportDocumentValues.Add("label", lParagraph); // print date is now // sample table "Ean" DataTable table = new DataTable("Ean"); table.Columns.Add("Position", typeof(string)); table.Columns.Add("Item", typeof(string)); table.Columns.Add("EAN", typeof(string)); table.Columns.Add("Count", typeof(int)); Random rnd = new Random(1234); for (int i = 1; i <= 100; i++) { // randomly create some articles table.Rows.Add(new object[] { i, "Item " + i.ToString("0000"), "123456790123", rnd.Next(9) + 1 }); } data.DataTables.Add(table); DateTime dateTimeStart = DateTime.Now; // start time measure here XpsDocument xps = reportDocument.CreateXpsDocument(data); documentViewer.Document = xps.GetFixedDocumentSequence(); // show the elapsed time in window title Title += " - generated in " + (DateTime.Now - dateTimeStart).TotalMilliseconds + "ms"; } catch (Exception ex) { // show exception MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop); } }
private void Load() { XpsDocument doc = new XpsDocument("Documents/FirstCheckData.xps", System.IO.FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); }
public void LoadXps(string[] list) { MemoryStream ms2 = new MemoryStream(); Package container = Package.Open(ms2, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri2 = new Uri("pack://InMemoryDocument2.xps"); PackageStore.RemovePackage(DocumentUri2); PackageStore.AddPackage(DocumentUri2, container); XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Fast, DocumentUri2.AbsoluteUri); XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); FixedDocumentSequence seqNew = new FixedDocumentSequence(); #region 把FlowDocument放进去 //构造一个基于内存的xps document MemoryStream ms = new MemoryStream(); Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri = new Uri("pack://InMemoryDocument.xps"); PackageStore.RemovePackage(DocumentUri); PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri); //将flow document写入基于内存的xps document中去 XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator); var doc = xpsDocument.GetFixedDocumentSequence(); foreach (DocumentReference r in doc.References) { DocumentReference newRef = new DocumentReference(); (newRef as IUriContext).BaseUri = (r as IUriContext).BaseUri; newRef.Source = r.Source; seqNew.References.Add(newRef); } xpsDocument.Close(); #endregion foreach (string sourceDocument in list) { XpsDocument xpsOld = new XpsDocument(sourceDocument, FileAccess.Read); FixedDocumentSequence seqOld = xpsOld.GetFixedDocumentSequence(); foreach (DocumentReference r in seqOld.References) { DocumentReference newRef = new DocumentReference(); (newRef as IUriContext).BaseUri = (r as IUriContext).BaseUri; newRef.Source = r.Source; seqNew.References.Add(newRef); } xpsOld.Close(); } // NOTE: WORK-AROUND for memory-leak in FixedDocumentSequence!!! // UpdateLayout() must be called at least to one fixedpage!!! FixedPage page = (seqNew.DocumentPaginator.GetPage(0).Visual) as FixedPage; page.UpdateLayout(); xpsWriter.Write(seqNew); docViewer.Document = xpsDoc.GetFixedDocumentSequence(); xpsDoc.Close(); }
/* * OnErrorCodes_Clicked - Error Codes Documentation */ private void OnErrorCodes_Clicked(object sender, RoutedEventArgs e) { XpsDocument testDocument = new XpsDocument("../../manuals/documentation/ErrorCodes.xps", FileAccess.Read); libraryDocViewer.Document = testDocument.GetFixedDocumentSequence(); }
//Presents the user with an OpenFileDialog, used to get a path //to the XPS document they want to open. If this succeeds, //the XPS document is loaded and displayed in the document viewer, //ready for annotating. private void LoadFixedDocument() { //Get a path to the file to be opened. string fileName = GetDocumentPath(); //If we didn't get a valid file path, we're done. //You might want to log an error here. if (string.IsNullOrEmpty(fileName)) { return; } //Create a URI for the file path. documentUri = new Uri(fileName, UriKind.Absolute); try { //Attempts to open the specified xps document with //read and write permission. xpsDocument = new XpsDocument(fileName, FileAccess.ReadWrite); } catch (Exception) { //You may want to handle any errors that occur during //the loading of the XPS document. For example a //UnauthorizedAccessException will be thrown if the //file is marked as read-only. } //Get the document's Package from the PackageStore. xpsPackage = PackageStore.GetPackage(documentUri); //If either the package or document are null, the //document is not valid. if ((xpsPackage == null) || (xpsDocument == null)) { //You may want to log an error here. return; } //Get the FixedDocumentSequence of the loaded document. FixedDocumentSequence fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence(); //If the document's FixedDocumentSequence is not found, //the document is corrupt. if (fixedDocumentSequence == null) { //Handle as required. return; } //Load the document's FixedDocumentSequence into //the DocumentViewer control. dvViewer.Document = fixedDocumentSequence; //Enable user annotations on the document. StartFixedDocumentAnnotations(); hasOpenDocument = true; }
}// end:OnOpen() //<SnippetRmPkgViewOpenDoc> // --------------------------- OpenDocument --------------------------- /// <summary> /// Loads and displays a given XPS document file.</summary> /// <param name="filename"> /// The path and file name of the XPS /// document to load and display.</param> /// <returns> /// true if the document loads successfully; otherwise false.</returns> public bool OpenDocument(string xpsFile) { // Check to see if the document is encrypted. // If encrypted, use OpenEncryptedDocument(). if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile)) return OpenEncryptedDocument(xpsFile); // Document is not encrypted, open normally. ShowStatus("Opening '" + Filename(xpsFile) + "'"); _packageUri = new Uri(xpsFile, UriKind.Absolute); try { _xpsDocument = new XpsDocument(xpsFile, FileAccess.Read); } catch (System.IO.FileFormatException ex) { MessageBox.Show(xpsFile + "\n\nThe file " + "is not a valid XPS document.\n\n" + "Exception: " + ex.Message + "\n\n" + ex.GetType().ToString() + "\n\n" + ex.StackTrace, "Invalid File Format", MessageBoxButton.OK, MessageBoxImage.Error); return false; } // Get the document's PackageStore into which // new user annotations will be added and saved. _xpsPackage = PackageStore.GetPackage(_packageUri); if ((_xpsPackage == null) || (_xpsDocument == null)) { MessageBox.Show("Unable to get Package from file."); return false; } // Get the FixedDocumentSequence from the open document. FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence(); if (fds == null) { MessageBox.Show(xpsFile + "\n\nThe document package within " + "the specified file does not contain a " + "FixedDocumentSequence.", "Package Error"); return false; } // Load the FixedDocumentSequence to the DocumentViewer control. DocViewer.Document = fds; // Enable document menu controls. menuFileClose.IsEnabled = true; menuFilePrint.IsEnabled = true; menuViewIncreaseZoom.IsEnabled = true; menuViewDecreaseZoom.IsEnabled = true; // Give the DocumentViewer focus. docViewer.Focus(); this.Title = "RightsManagedPackageViewer SDK Sample - " + Filename(xpsFile); return true; }// end:OpenDocument()
private void Load() { XpsDocument doc = new XpsDocument("Documents/PreparationForLoadDB.xps", System.IO.FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); }
/// <summary> /// Previews the report. /// </summary> /// <param name="reportDocument">The report document.</param> /// <param name="data">The data.</param> public void PreviewReport(ReportDocument reportDocument, ReportData data, Action <int, int> PageGeneratedCallBack = null) { XpsDocument xps = reportDocument.CreateXpsDocument(data, PageGeneratedCallBack); DocumentViewer.Document = xps.GetFixedDocumentSequence(); }
public object GetDocument() { return(_document.GetFixedDocumentSequence()); }
private void Print_Click(object sender, RoutedEventArgs e) { var document = new FixedDocument(); var report_page = new FixedPage(); report_page.Width = document.DocumentPaginator.PageSize.Width; report_page.Height = document.DocumentPaginator.PageSize.Height; report_page.Margin = new Thickness(20, 50, 20, 50); //Створення та запис заголовку. var title_text = new TextBlock(); title_text.Text = "Звіт"; title_text.FontSize = 30; title_text.Margin = new Thickness(document.DocumentPaginator.PageSize.Width * 0.45, 0, 0, 50); report_page.Children.Add(title_text); //Створення та запис графіків. StringReader stringReader = new StringReader(gridXaml); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas newGrid = (Canvas)XamlReader.Load(xmlReader); report_page.Children.Add(newGrid); //Створення та запис правила. var main_text = new TextBlock(); main_text.Text = "Поточний рівень загрози: " + danger_level.Text; main_text.FontSize = 20; main_text.Margin = new Thickness(20, 700, 0, 0); report_page.Children.Add(main_text); var report_page_сontent = new PageContent(); ((IAddChild)report_page_сontent).AddChild(report_page); document.Pages.Add(report_page_сontent); using (MemoryStream xpsStream = new MemoryStream()) { using (Package package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite)) { string packageUriString = "memorystream://file_report.xps"; Uri packageUri = new Uri(packageUriString); PackageStore.AddPackage(packageUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUriString); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(document); FixedDocumentSequence document_report = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); PrintPreviewWindow printPreviewWnd = new PrintPreviewWindow(document_report); printPreviewWnd.Owner = Owner; printPreviewWnd.ShowDialog(); PackageStore.RemovePackage(packageUri); } } }
public static FixedDocumentSequence GetDocumentSequence(object dataContext, Stream inputStream, Size paperSize) { //承载一个可移植、高保真、格式固定的文档。 FixedDocument _document = new FixedDocument(); //为高保真度、固定格式的页面提供内容。 FixedPage page = new FixedPage(); //高度 page.Height = paperSize.Height; //宽度 page.Width = paperSize.Width; //提供有关FixedDocument中的FixedPage元素的信息。 PageContent content = new PageContent(); //Child:获取或设置与此PageContent关联的FixedPage。 content.Child = page; //属性Pages:获取文档的PageContent元素的集合。 //Add方法:向页集合中添加新页。 _document.Pages.Add(content); FrameworkElement template = (FrameworkElement)XamlReader.Load(inputStream); template.BeginInit(); template.DataContext = dataContext; template.Measure(paperSize); template.Arrange(new Rect(paperSize)); template.EndInit(); template.UpdateLayout(); page.Children.Add(template); //构造一个基于内存的xps document 为什么? MemoryStream ms = new MemoryStream(); //为XPS内容创建包 Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); //每个包都需要一个URI。形式:"pack:// syntax" Uri documentUri = new Uri("pack://InMemoryDocument.xps"); PackageStore.RemovePackage(documentUri); //加入该包 PackageStore.AddPackage(documentUri, package); //基于该包创建XPS的XpsDocument对象 XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, documentUri.AbsoluteUri); //将flow document写入基于内存的xps document中去 XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); //分页 writer.Write(((IDocumentPaginatorSource)_document).DocumentPaginator); //获取这个基于内存的xps document的fixed document FixedDocumentSequence pages = xpsDocument.GetFixedDocumentSequence(); //关闭基于内存的xps document 关闭流以释放内存 xpsDocument.Close(); return(pages); }
private void Load() { XpsDocument doc = new XpsDocument("Documents/FastInsertPassportIdIntoExcel.xps", System.IO.FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); }
public PrintPreview(XpsDocument xps) { InitializeComponent(); PrintPreviewViewer.Document = xps.GetFixedDocumentSequence(); }
/// <summary> /// Window has been activated /// </summary> /// <param name="sender">sender</param> /// <param name="e">event details</param> private void Window_Activated(object sender, EventArgs e) { if (!_firstActivated) { return; } _firstActivated = false; Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(delegate { try { ReportDocument reportDocument = new ReportDocument(); StreamReader reader = new StreamReader(new FileStream(@"Templates\BarcodeReport.xaml", FileMode.Open, FileAccess.Read)); reportDocument.XamlData = reader.ReadToEnd(); reportDocument.XamlImagePath = Path.Combine(Environment.CurrentDirectory, @"Templates\"); reader.Close(); ReportData data = new ReportData(); // set constant document values data.ReportDocumentValues.Add("PrintDate", DateTime.Now); // print date is now // sample table "Ean" DataTable table = new DataTable("Ean"); table.Columns.Add("Position", typeof(string)); table.Columns.Add("Item", typeof(string)); table.Columns.Add("EAN", typeof(string)); table.Columns.Add("Count", typeof(int)); Random rnd = new Random(1234); for (int i = 1; i <= 100; i++) { // randomly create some items StringBuilder sb = new StringBuilder(); for (int j = 1; j <= 13; j++) { sb.Append(rnd.Next(10)); } table.Rows.Add(new object[] { i, "Item " + i.ToString("0000"), sb.ToString(), rnd.Next(9) + 1 }); } data.DataTables.Add(table); DateTime dateTimeStart = DateTime.Now; // start time measure here XpsDocument xps = reportDocument.CreateXpsDocument(data); documentViewer.Document = xps.GetFixedDocumentSequence(); // show the elapsed time in window title Title += " - generated in " + (DateTime.Now - dateTimeStart).TotalMilliseconds + "ms"; } catch (Exception ex) { // show exception MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop); } finally { busyDecorator.IsBusyIndicatorHidden = true; } })); }
/// <summary> /// Window has been activated /// </summary> /// <param name="sender">sender</param> /// <param name="e">event details</param> private void Window_Activated(object sender, EventArgs e) { if (!_firstActivated) { return; } _firstActivated = false; try { ReportDocument reportDocument = new ReportDocument(); StreamReader reader = new StreamReader(new FileStream(@"Templates\ChartReport.xaml", FileMode.Open, FileAccess.Read)); reportDocument.XamlData = reader.ReadToEnd(); reportDocument.XamlImagePath = Path.Combine(Environment.CurrentDirectory, @"Templates\"); reader.Close(); ReportData data = new ReportData(); // set constant document values data.ReportDocumentValues.Add("PrintDate", DateTime.Now); // print date is now // sample table "Example1" DataTable table = new DataTable("Example1"); table.Columns.Add("Year", typeof(string)); table.Columns.Add("Value", typeof(decimal)); Random rnd = new Random(1234); for (int i = 1990; i <= 2009; i++) { // randomly create some values table.Rows.Add(new object[] { i, rnd.Next(100000) + 10000 }); } data.DataTables.Add(table); // sample table "Example2" table = new DataTable("Example2"); table.Columns.Add("Year", typeof(string)); table.Columns.Add("Value", typeof(decimal)); int citizens = rnd.Next(100000); for (int i = 1990; i <= 2009; i++) { // randomly create some values table.Rows.Add(new object[] { i, citizens }); citizens += rnd.Next(10000); } data.DataTables.Add(table); // sample table "Example3" table = new DataTable("Example3"); table.Columns.Add("Opinion", typeof(string)); table.Columns.Add("Percent", typeof(decimal)); table.Rows.Add(new object[] { "Yes", 36.2 }); table.Rows.Add(new object[] { "No", 21.5 }); table.Rows.Add(new object[] { "Unsure", 100 - 36.2 - 21.5 }); data.DataTables.Add(table); DateTime dateTimeStart = DateTime.Now; // start time measure here XpsDocument xps = reportDocument.CreateXpsDocument(data); // concat XPS files documentViewer.Document = xps.GetFixedDocumentSequence(); // show the elapsed time in window title Title += " - generated in " + (DateTime.Now - dateTimeStart).TotalMilliseconds + "ms"; } catch (Exception ex) { // show exception MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop); } }
private void ShowXpsDocument(string fileName) { XpsDocument xpsDocument = new XpsDocument(fileName, System.IO.FileAccess.Read); documentViewer.Document = xpsDocument.GetFixedDocumentSequence(); }
private void buttonPDF_Click(object sender, RoutedEventArgs e) { var wrd_name = Convert.ToString(comboBox.SelectedValue); var xls_name = textBoxExcelPath.Text; if (string.IsNullOrEmpty(wrd_name)) { MessageBox.Show("Выберите шаблон КП"); return; } ProgressWnd pw = new ProgressWnd("Создаем КП по шаблону..."); pw.Show(); string fn = ""; try { WordApp = new Wd.Application() { Visible = false }; WordDoc = WordApp.Documents.Open(wrd_name); fn = SaveW(WordApp, WordDoc); var ad = DataContext as AllData; ReplaceAll(WordDoc, "[OurCompany]", ad.Our.OurCompany); ReplaceAll(WordDoc, "[ForWho]", ad.ForWho); ReplaceAll(WordDoc, "[ContractPeriodYears]", ad.HowLongYears); ReplaceAll(WordDoc, "[ServiceType]", ad.ServiceType); ReplaceAll(WordDoc, "[DaysToStart]", ad.DaysToStart); ReplaceAll(WordDoc, "[DateStart]", ad.DateStart); ReplaceAll(WordDoc, "[CostMonthString]", ad.CostMonthString); ReplaceAll(WordDoc, "[CostMonth]", ad.CostMonth); ReplaceAll(WordDoc, "[CostYear]", (o2d(ad.CostMonth) * 12).ToString()); ReplaceAll(WordDoc, "[Address]", ad.Address); ReplaceAll(WordDoc, "[Date]", ad.Date); ReplaceAll(WordDoc, "[Area]", ad.Area.ToString()); ReplaceAll(WordDoc, "[NameObject]", ad.ForWho); int kk = 1; foreach (var ee in ad.e1) { var trg = "[Extra" + kk + "]"; if (ee.IsSelected == true) { ReplaceAll(WordDoc, trg, ee.Text); } else { WordDoc.Bookmarks["bExtra" + kk].Range.Delete(); ReplaceAll(WordDoc, trg, ""); } ++kk; } kk = 1; foreach (var ee in ad.e2) { var trg = "[Sod" + kk + "]"; if (ee.IsSelected == true) { ReplaceAll(WordDoc, trg, ee.Text); } else { WordDoc.Bookmarks["bSod" + kk].Range.Delete(); ReplaceAll(WordDoc, trg, ""); } ++kk; } if (radioButton.IsChecked == true) { ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn1); } else { ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn2); } if (checkBoxServicePlan.IsChecked == false) { Wd.Range delRange = WordDoc.Range(); delRange.Start = WordDoc.Bookmarks["b0"].Range.Start; delRange.End = WordDoc.Bookmarks["b1"].Range.End; delRange.Delete(); } ReplaceAll(WordDoc, "[ServicePlanStart]", ""); ReplaceAll(WordDoc, "[ServicePlanEnd]", ""); //ReplaceAll(WordDoc, "[NameCost]", ad.ForWho); //Sebestoimost Wd.Table tt = FindTable(WordDoc, WordDoc.Bookmarks["tab6"]); double total = 0; foreach (var s in ad.Sebestimost) { tt.Rows.Add(); tt.Cell(tt.Rows.Count, 1).Range.Text = s.Name; tt.Cell(tt.Rows.Count, 2).Range.Text = s.CostMonth.ToString(); total += s.CostMonth; } tt.Rows.Add(); tt.Cell(tt.Rows.Count, 1).Range.Text = "Итого"; tt.Cell(tt.Rows.Count, 2).Range.Text = total.ToString(); /// //FOT Wd.Table ttFOT = FindTable(WordDoc, WordDoc.Bookmarks["tab7"]); total = 0; foreach (var s in ad.ShtatRasstanovka) { ttFOT.Rows.Add(); ttFOT.Cell(tt.Rows.Count, 1).Range.Text = s.Num.ToString(); ttFOT.Cell(tt.Rows.Count, 2).Range.Text = s.Name; ttFOT.Cell(tt.Rows.Count, 3).Range.Text = s.Quant.ToString(); ttFOT.Cell(tt.Rows.Count, 4).Range.Text = s.Smena.ToString(); } //// //os sredstv Wd.Table ttOS = FindTable(WordDoc, WordDoc.Bookmarks["tab8"]); total = 0; foreach (var s in ad.OsnSredstva) { ttOS.Rows.Add(); ttOS.Cell(tt.Rows.Count, 1).Range.Text = s.Num.ToString() + "."; ttOS.Cell(tt.Rows.Count, 2).Range.Text = s.Name; ttOS.Cell(tt.Rows.Count, 3).Range.Text = s.Quant.ToString(); ttOS.Cell(tt.Rows.Count, 4).Range.Text = s.CostMonth.ToString(); total += s.CostMonth; } ttOS.Rows.Add(); ttOS.Cell(tt.Rows.Count, 1).Range.Text = "Итого"; ttOS.Cell(tt.Rows.Count, 4).Range.Text = total.ToString(); //rash san Wd.Table ttSAN = FindTable(WordDoc, WordDoc.Bookmarks["tab9"]); total = 0; foreach (var s in ad.RashMaterials) { ttSAN.Rows.Add(); ttSAN.Cell(tt.Rows.Count, 1).Range.Text = s.Name; ttSAN.Cell(tt.Rows.Count, 2).Range.Text = s.Quant.ToString(); ttSAN.Cell(tt.Rows.Count, 3).Range.Text = s.Price.ToString(); ttSAN.Cell(tt.Rows.Count, 4).Range.Text = s.CostMonth.ToString(); total += s.CostMonth; } ttSAN.Rows.Add(); ttSAN.Cell(tt.Rows.Count, 1).Range.Text = "Итого в месяц"; ttSAN.Cell(tt.Rows.Count, 4).Range.Text = total.ToString(); StringBuilder sb = new StringBuilder(); foreach (var c in ad.Contacts) { if (c.IsSelected) { sb.AppendLine(c.Dolj); sb.AppendLine(c.Name); sb.AppendLine(c.Tel); sb.AppendLine(c.MobTel); sb.AppendLine(c.Email); sb.AppendLine(); } } ReplaceAll(WordDoc, "[Contacts]", sb.ToString()); WordDoc.TablesOfContents[1].Update(); foreach (Wd.Range docRange in WordDoc.Words) { docRange.HighlightColorIndex = Wd.WdColorIndex.wdNoHighlight; } } catch (Exception ee) { MessageBox.Show(ee.Message); } finally { WordDoc.Save(); WordApp.Documents.Close(); WordApp.Quit(Wd.WdSaveOptions.wdDoNotSaveChanges); string convertedXpsDoc = string.Concat(System.IO.Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps"); XpsDocument xpsDocument = ConvertWordToXps(fn, convertedXpsDoc); if (xpsDocument != null) { documentViewer.Document = xpsDocument.GetFixedDocumentSequence(); } pw.Stop(); } // doc.Content.Find.Execute("[ND]", ReplaceWith: Doc.No); // SaveW(app, doc, TemplateFilePath); }
/// <summary> /// Window has been activated /// </summary> /// <param name="sender">sender</param> /// <param name="e">event details</param> private void Window_Activated(object sender, EventArgs e) { if (!_firstActivated) { return; } _firstActivated = false; try { ReportDocument reportDocument = new ReportDocument(); StreamReader reader = new StreamReader(new FileStream(@"Templates\DynamicReport.xaml", FileMode.Open, FileAccess.Read)); reportDocument.XamlData = reader.ReadToEnd(); reportDocument.XamlImagePath = Path.Combine(Environment.CurrentDirectory, @"Templates\"); reader.Close(); DataTable tableHeader = null; DataTable tableData = null; object[] obj = null; ReportData data = new ReportData(); // REPORT 1 DATA tableHeader = new DataTable("Header"); tableData = new DataTable("Data"); tableHeader.Columns.Add(); tableHeader.Rows.Add(new object[] { "Service" }); tableHeader.Rows.Add(new object[] { "Amount" }); tableHeader.Rows.Add(new object[] { "Price" }); tableData.Columns.Add(); tableData.Columns.Add(); tableData.Columns.Add(); obj = new object[3]; for (int i = 0; i < 15; i++) { obj[0] = String.Format("Service oferted. Nº{0}", i); obj[1] = i * 2; obj[2] = String.Format("{0} €", i); tableData.Rows.Add(obj); } data.DataTables.Add(tableData); data.DataTables.Add(tableHeader); // REPORT 2 DATA tableHeader = new DataTable("Header2"); tableData = new DataTable("Data2"); tableHeader.Columns.Add(); tableHeader.Rows.Add(new object[] { "Service" }); tableHeader.Rows.Add(new object[] { "Amount" }); tableData.Columns.Add(); tableData.Columns.Add(); obj = new object[2]; for (int i = 0; i < 15; i++) { obj[0] = String.Format("Service offered. Nº{0}", i); obj[1] = i; tableData.Rows.Add(obj); } data.DataTables.Add(tableData); data.DataTables.Add(tableHeader); XpsDocument xps = reportDocument.CreateXpsDocument(data); documentViewer.Document = xps.GetFixedDocumentSequence(); } catch (Exception ex) { // show exception MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop); } }
}// end:OnOpen() // --------------------------- OpenDocument --------------------------- /// <summary> /// Loads and displays a given XPS document file.</summary> /// <param name="filename"> /// The path and filename of the XPS document /// to load and display.</param> /// <returns> /// true if the document loads successfully; otherwise false.</returns> public bool OpenDocument(string filename) { // Save the document path and filename. _xpsDocumentPath = filename; // Extract the document filename without the path. _xpsDocumentName = filename.Remove(0, filename.LastIndexOf('\\')+1); _packageUri = new Uri(filename, UriKind.Absolute); try { _xpsDocument = new XpsDocument(filename, FileAccess.Read); } catch (System.IO.FileFormatException) { string msg = filename + "\n\nThe specified file " + "in not a valid unprotected XPS document.\n\n" + "The file is possibly encrypted with rights management. " + "Please see the RightsManagedPackageViewer\nsample that " + "shows how to access and view a rights managed XPS document."; MessageBox.Show(msg, "Invalid File Format", MessageBoxButton.OK, MessageBoxImage.Error); return false; } // Get the document's PackageStore into which // new user annotations will be added and saved. _xpsPackage = PackageStore.GetPackage(_packageUri); if ((_xpsPackage == null) || (_xpsDocument == null)) { MessageBox.Show("Unable to get Package from file."); return false; } // Get the FixedDocumentSequence from the open document. FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence(); if (fds == null) { string msg = filename + "\n\nThe document package within the specified " + "file does not contain a FixedDocumentSequence."; MessageBox.Show(msg, "Package Error"); return false; } // Load the FixedDocumentSequence to the DocumentViewer control. docViewer.Document = fds; // Enable document menu controls. menuFileClose.IsEnabled = true; menuFilePrint.IsEnabled = true; menuFileRights.IsEnabled = true; menuViewIncreaseZoom.IsEnabled = true; menuViewDecreaseZoom.IsEnabled = true; // Give the DocumentViewer focus. docViewer.Focus(); WriteStatus("Opened '" + _xpsDocumentName + "'"); WritePrompt("Click 'File | Rights...' to select an " + "eXtensible Rights Markup (XrML) permissions file."); return true; }// end:OpenDocument()
public void DocViewerLoaded(DocumentViewer documentViewer) { try { ReportDocument reportDocument = new ReportDocument(); reportDocument.ImageProcessing += reportDocument_ImageProcessing; reportDocument.ImageError += reportDocument_ImageError; StreamReader reader = new StreamReader(new FileStream(@"Templates\Prescription.xaml", FileMode.Open, FileAccess.Read)); reportDocument.XamlData = reader.ReadToEnd(); reportDocument.XamlImagePath = Path.Combine(Environment.CurrentDirectory, @"Templates\"); reader.Close(); ReportData data = new ReportData(); //Clinic info if (_clinic != null) { data.ReportDocumentValues.Add("ClinicName", _clinic.Name.ToUpper()); data.ReportDocumentValues.Add("ClinicAddress", _clinic.Address); data.ReportDocumentValues.Add("ClinicPhone", _clinic.Phone); } //Patient info data.ReportDocumentValues.Add("PatientName", _patient.Name.ToUpper()); data.ReportDocumentValues.Add("BirthDay", "Ngày sinh: " + _patient.Birthday); data.ReportDocumentValues.Add("Address", _patient.Address); data.ReportDocumentValues.Add("Sex", "Giới tính: " + _patient.Sex); data.ReportDocumentValues.Add("Diagnose", _session.Diagnose); //Prescription DataTable table = new DataTable("Prescription"); table.Columns.Add("Count", typeof(int)); table.Columns.Add("BrandName", typeof(string)); table.Columns.Add("Quantity"); table.Columns.Add("Type", typeof(string)); table.Columns.Add("DrugNote", typeof(string)); var drugs = _esClinicContext.Drugs.Include("Product").ToList().Where(d => d.SessionId == _session.SessionId); int count = 0; foreach (var drug in drugs) { count++; table.Rows.Add(count, drug.Product.BrandName, drug.Quantity, drug.Product.Type, drug.Note); } data.DataTables.Add(table); //Note data.ReportDocumentValues.Add("Note", _session.Note); data.ReportDocumentValues.Add("ReExamDate", string.Format("{0:dd/MM/yyyy}", _session.ReExamDate)); string tmp = "Ngày " + string.Format("{0:dd}", _session.Date) + " tháng " + string.Format("{0:MM}", _session.Date) + " năm " + String.Format("{0:yyyy}", _session.Date); data.ReportDocumentValues.Add("Date", tmp); data.ReportDocumentValues.Add("DoctorName", _session.DoctorName); XpsDocument xps = reportDocument.CreateXpsDocument(data); documentViewer.Document = xps.GetFixedDocumentSequence(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { IsBusyHidden = true; NotifyOfPropertyChange(() => IsBusyHidden); } }
}// end:GetContentFolder() // --------------------------- OpenDocument --------------------------- /// <summary> /// Loads, displays, and enables user annotations /// a given XPS document file.</summary> /// <param name="filename"> /// The path and filename of the XPS document /// to load, display, and annotate.</param> /// <returns> /// true if the document loads successfully; otherwise false.</returns> public bool OpenDocument(string filename) { // Load an XPS document into a DocumentViewer // and enable user Annotations. _xpsDocumentPath = filename; _packageUri = new Uri(filename, UriKind.Absolute); try { _xpsDocument = new XpsDocument(filename, FileAccess.ReadWrite); } catch (System.UnauthorizedAccessException) { string msg = filename + "\n\nThe specified file is Read-Only which " + "prevents storing user annotations."; MessageBox.Show(msg, "Read-Only file", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } // Get the document's PackageStore into which // new user annotations will be added and saved. _xpsPackage = PackageStore.GetPackage(_packageUri); if ((_xpsPackage == null) || (_xpsDocument == null)) { MessageBox.Show("Unable to get Package from file."); return(false); } // Get the FixedDocumentSequence from the open document. FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence(); if (fds == null) { string msg = filename + "\n\nThe document package within the specified " + "file does not contain a FixedDocumentSequence."; MessageBox.Show(msg, "Package Error"); return(false); } // Load the FixedDocumentSequence to the DocumentViewer control. docViewer.Document = fds; // Enable document menu controls. menuFileClose.IsEnabled = true; menuFilePrint.IsEnabled = true; menuViewAnnotations.IsEnabled = true; menuViewIncreaseZoom.IsEnabled = true; menuViewDecreaseZoom.IsEnabled = true; // Enable user annotations on the document. Uri fixedDocumentSeqUri = GetFixedDocumentSequenceUri(); _annotHelper.SetSource(_packageUri, fixedDocumentSeqUri); if (menuViewAnnotations.IsChecked) { _annotHelper.StartAnnotations(); } // Give the DocumentViewer focus. docViewer.Focus(); return(true); }// end:OpenDocument()
private static void ExtractImage(string xpsPath, string imagePath) { if (!File.Exists(xpsPath)) { return; } //xpsPath = @"D:\hsr\Semesterarbeit\svn\code\trunk\ProjectFlip\Resources\Xps\pn_063_d_sensor_linearantrieb_web.xps"; var xpsDoc = new XpsDocument(xpsPath, FileAccess.Read); try { xpsDoc.GetFixedDocumentSequence(); var docSeq = xpsDoc.GetFixedDocumentSequence(); xpsDoc.Close(); if (docSeq == null) { xpsDoc.Close(); return; } var docPage = docSeq.DocumentPaginator.GetPage(0); var renderTarget = new RenderTargetBitmap( (int)docPage.Size.Width, (int)docPage.Size.Height, 96, 96, // WPF (Avalon) units are 96dpi based PixelFormats.Default); // crop image from 340x309 - 583x552 renderTarget.Render(docPage.Visual); var encoder = new BmpBitmapEncoder(); // Choose type here ie: JpegBitmapEncoder, etc encoder.Frames.Add(BitmapFrame.Create(renderTarget)); var pageOutStream = new FileStream(imagePath + ".tmp", FileMode.Create, FileAccess.Write); encoder.Save(pageOutStream); pageOutStream.Close(); var v = Image.FromFile(imagePath + ".tmp"); var bmpImage = new Bitmap(v); var bmpCrop = bmpImage.Clone(new Rectangle(340, 309, 243, 243), bmpImage.PixelFormat); bmpCrop.Save(imagePath); v.Dispose(); File.Delete(imagePath + ".tmp"); bmpImage.Dispose(); bmpCrop.Dispose(); } finally { // Memory Leak .NET FrameworkBug!? See http://stackoverflow.com/questions/218681/opening-xps-document-in-net-causes-a-memory-leak // Workaround: // Executes: ContextLayoutManager.From(Dispatcher.CurrentDispatcher).UpdateLayout(); xpsDoc.Close(); var presentationCoreAssembly = Assembly.GetAssembly(typeof(UIElement)); var contextLayoutManagerType = presentationCoreAssembly.GetType("System.Windows.ContextLayoutManager"); var contextLayoutManager = contextLayoutManagerType.InvokeMember("From", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new[] { Dispatcher.CurrentDispatcher }); contextLayoutManagerType.InvokeMember("UpdateLayout", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, contextLayoutManager, null); GC.Collect(); // End of workaround } //Rectangle rect = new Rectangle(340, 309, 100, 100); //CroppedBitmap x = new CroppedBitmap(encoder.Frames[0].pix, rect); //Rectangle rect = new Rectangle(340, 309, 100, 100); //Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat); /*Uri uri = new Uri(string.Format("memorystream://{0}", xpsPath)); * FixedDocumentSequence seq; * * using (Package pack = Package.Open(xpsPath, FileMode.Open, FileAccess.Read, FileShare.Read)) * using (StorePackage(uri, pack)) * using (XpsDocument xps = new XpsDocument(pack, CompressionOption.Normal, uri.ToString())) * { * seq = xps.GetFixedDocumentSequence(); * }*/ /* * DocumentPaginator paginator = seq.DocumentPaginator; * // I only want the first page for this example * Visual visual = paginator.GetPage(0).Visual; * */ /* * var doc = new XpsDocument(xpsPath, FileAccess.Read); * if (doc.FixedDocumentSequenceReader == null) return; * //if (!Filepath.EndsWith("pn_013_d_digitalsignal_web.xps")) return DefaultLogo(); * * //var visual = doc.GetFixedDocumentSequence().DocumentPaginator.GetPage(0).Visual; * var visual = doc.GetFixedDocumentSequence().DocumentPaginator.GetPage(0).Visual; * var fe = (FrameworkElement) visual; * * var bmp = new RenderTargetBitmap((int)fe.ActualWidth, * (int)fe.ActualHeight, 96d, 96d, PixelFormats.Default); * bmp.Render(fe);*/ /*if (doc.FixedDocumentSequenceReader != null) * { * var list = new List<IXpsFixedDocumentReader>(doc.FixedDocumentSequenceReader.FixedDocuments); * foreach (var xpsFixedDocumentReader in list) * { * SaveImage(xpsPath, imagePath); * } * }*/ /*Uri uri = new Uri(string.Format("memorystream://{0}", xpsPath)); * FixedDocumentSequence seq; * * using (Package pack = Package.Open(xpsPath)) * using (var xps = new XpsDocument(pack, CompressionOption.Normal, uri.ToString())) * { * seq = xps.GetFixedDocumentSequence(); * } * * FrameworkElement fe = (FrameworkElement)seq.DocumentPaginator.GetPage(0).Visual; * * RenderTargetBitmap bmp = new RenderTargetBitmap((int)fe.ActualWidth, * (int)fe.ActualHeight, 96d, 96d, PixelFormats.Default); * bmp.Render(fe); * * PngBitmapEncoder png = new PngBitmapEncoder(); * png.Frames.Add(BitmapFrame.Create(bmp)); * * using (Stream stream = File.Create(imagePath)) * { * png.Save(stream); * }*/ }
private void button_Click(object sender, RoutedEventArgs e) { n++; Microsoft.Office.Interop.Word.Application schedule = new Microsoft.Office.Interop.Word.Application(); schedule.Visible = false; object missing = System.Reflection.Missing.Value; Document document = schedule.Documents.Add(ref missing, ref missing, ref missing, ref missing); try { List <string> days_of_week = new List <string>() { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.Name = "Gill Sans MT"; headerRange.Font.Size = 20; headerRange.Text = "My Schedule"; } for (int i = 0; i < days_of_week.Count; i++) { Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); para1.Range.Text += days_of_week[i] + Environment.NewLine; List <Lesson> day = new List <Lesson>(); for (int j = 0; j < Subject.result.Count; j++) { if (Subject.result[j].Day.Contains(days_of_week[i]) == true) { day.Add(Subject.result[j]); } } Microsoft.Office.Interop.Word.Table schedule_table = document.Tables.Add(para1.Range, day.Count + 1, 4, ref missing, ref missing); schedule_table.Borders.Enable = 1; schedule_table.Rows[1].Cells[1].Range.Text = "Name of the class"; schedule_table.Rows[1].Cells[2].Range.Text = "Time"; schedule_table.Rows[1].Cells[3].Range.Text = "Teacher"; schedule_table.Rows[1].Cells[4].Range.Text = "Address"; for (int a = 0; a < day.Count; a++) { for (int j = 0; j < day.Count - a - 1; j++) { DateTime dtstartj1 = new DateTime(2000, 10, 1, day[j].time_startHH, day[j].time_startMM, 0); DateTime dtstartj2 = new DateTime(2000, 10, 1, day[j + 1].time_startHH, day[j + 1].time_startMM, 0); if (dtstartj1 > dtstartj2) { Lesson temp = day[j]; day[j] = day[j + 1]; day[j + 1] = temp; } } } for (int j = 0; j < day.Count; j++) { schedule_table.Rows[j + 2].Cells[1].Range.Text = day[j].Name; schedule_table.Rows[j + 2].Cells[2].Range.Text = day[j].TimeStart + " - " + day[j].TimeEnd; schedule_table.Rows[j + 2].Cells[3].Range.Text = day[j].Teacher; schedule_table.Rows[j + 2].Cells[4].Range.Text = day[j].Address; } } object filename = Settings.schedule_save_folder_name + "\\schedule" + n + ".docx"; object filename1 = Settings.schedule_save_folder_name + "\\schedule" + n + ".xps"; document.SaveAs2(ref filename); document.SaveAs2(ref filename1, WdSaveFormat.wdFormatXPS); document.Close(ref missing, ref missing, ref missing); document = null; schedule.Quit(ref missing, ref missing, ref missing); schedule = null; XpsDocument doc = new XpsDocument(Settings.schedule_save_folder_name + "\\schedule" + n + ".xps", FileAccess.Read); documentViewer.Document = doc.GetFixedDocumentSequence(); } catch { document.Close(ref missing, ref missing, ref missing); document = null; schedule.Quit(ref missing, ref missing, ref missing); schedule = null; } }
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); } } }
private bool ConvertWordDocToXPSDoc(string wordDocName) { // Create a WordApplication and add Document to it Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application(); wordApplication.Documents.Add(wordDocName); Document doc = wordApplication.ActiveDocument; // You must make sure you have Microsoft.Office.Interop.Word.Dll version 12. // Version 11 or previous versions do not have WdSaveFormat.wdFormatXPS option try { string xpsDocName = @"http://www.jjgjt.com/download/1.xps"; doc.SaveAs(xpsDocName, WdSaveFormat.wdFormatXPS); wordApplication.Quit(); //XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read); XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read); documentViewer1.Document = xpsDoc.GetFixedDocumentSequence(); return true; } catch (Exception exp) { string str = exp.Message; return false; } }