// Test public static string ExtractText(string path) { XpsDocument _xpsDocument = new XpsDocument(path, System.IO.FileAccess.Read); IXpsFixedDocumentSequenceReader fixedDocSeqReader = _xpsDocument.FixedDocumentSequenceReader; IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0]; IXpsFixedPageReader _page = _document.FixedPages[0]; StringBuilder _currentText = new StringBuilder(); System.Xml.XmlReader _pageContentReader = _page.XmlReader; if (_pageContentReader != null) { while (_pageContentReader.Read()) { if (_pageContentReader.Name == "Glyphs") { if (_pageContentReader.HasAttributes) { if (_pageContentReader.GetAttribute("UnicodeString") != null) { _currentText. Append(_pageContentReader. GetAttribute("UnicodeString") + "\n"); } } } } } return(_currentText.ToString()); }
// -------------------- IterateSignatureDefinitions -------------------- /// <summary> /// Interates through the SignatureDefinition contained in a given /// XPS document displaying and updating the signature properties /// through a user dialog.</summary> /// <param name="signatureDialog"> /// The user dialog to use in displaying and /// updating the signature information.</param> /// <param name="xpsDocument"> /// The XPS document containing the signature information.</param> public void IterateSignatureDefinitions( SignatureDialog signatureDialog, XpsDocument xpsDocument) { IXpsFixedDocumentSequenceReader docSeq = xpsDocument.FixedDocumentSequenceReader; // For every FixedDocument in the XPS document. foreach (IXpsFixedDocumentReader doc in docSeq.FixedDocuments) { // For every SignatureDefinition in each FixedDocument. foreach (XpsSignatureDefinition signature in doc.SignatureDefinitions) { SignatureDisplayItem item = signatureDialog.AddSignatureItem(signature); // Signatures are bound to signature definitions by GUID. // If the SignatureDefintion SpotId is the same as the // SignatureId, the signature is signing that definition. // For every signature in the XPS document. foreach (XpsDigitalSignature sig in xpsDocument.Signatures) { if (sig.Id != null && sig.Id == signature.SpotId) { X509Certificate2 cert = sig.SignerCertificate as X509Certificate2; item.Signer = cert.GetNameInfo(X509NameType.SimpleName, false); item.IsSigned = true; } } // end:foreach (XpsDigitalSignature } // end:foreach (XpsSignatureDefinition } // end:foreach (IXpsFixedDocumentReader } // end:IterateSignatureDefinitions()
private void SignatureDefinitionCommandHandler(object sender, RoutedEventArgs e) { SignatureDefinition sigDefDialog = new SignatureDefinition(); if (sigDefDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { XpsSignatureDefinition signatureDefinition = new XpsSignatureDefinition(); signatureDefinition.RequestedSigner = sigDefDialog.RequestedSigner.Text; signatureDefinition.Intent = sigDefDialog.Intent.Text; signatureDefinition.SigningLocale = sigDefDialog.SigningLocale.Text; try { signatureDefinition.SignBy = DateTime.Parse(sigDefDialog.SignBy.Text); } catch (FormatException) { } signatureDefinition.SpotId = Guid.NewGuid(); IXpsFixedDocumentSequenceReader docSeq = _xpsDocument.FixedDocumentSequenceReader; //_xpsDocument is type System.Windows.Xps.Packaging.XpsDocument IXpsFixedDocumentReader doc = docSeq.FixedDocuments[0]; doc.AddSignatureDefinition(signatureDefinition); doc.CommitSignatureDefinition(); InitializeSignatureDisplay(); } }
public string extracttext() { IXpsFixedDocumentSequenceReader fixedDocSeqReader = newxpsdocument.FixedDocumentSequenceReader; IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0]; // IXpsFixedPageReader _page = _document.FixedPages[documentViewerElement.MasterPageNumber]; string _fullPageText = ""; for (int pagenumber = 0; pagenumber < _document.FixedPages.Count(); pagenumber++) { IXpsFixedPageReader _page = _document.FixedPages[pagenumber]; StringBuilder _currentText = new StringBuilder(); System.Xml.XmlReader _pageContentReader = _page.XmlReader; if (_pageContentReader != null) { while (_pageContentReader.Read()) { if (_pageContentReader.Name == "Glyphs") { if (_pageContentReader.HasAttributes) { if (_pageContentReader.GetAttribute("UnicodeString") != null) { _currentText. Append(_pageContentReader. GetAttribute("UnicodeString")); } } } } } _fullPageText = _fullPageText + _currentText.ToString(); } return(_fullPageText); }
public static bool IsXps(string filename) { try { XpsDocument x = new XpsDocument(filename, FileAccess.Read); IXpsFixedDocumentSequenceReader fdsr = x.FixedDocumentSequenceReader; // Needed to actually try to find the FixedDocumentSequence Uri uri = fdsr.Uri; return(true); } catch (Exception) { } return(false); }
} // end:IterateSignatureDefinitions() // ------------------------- IterateSignatures ------------------------ /// <summary> /// Interates through signatures that are not associated with /// a SignatureDefinition.</summary> /// <param name="signatureDialog"> /// The user dialog to use in displaying and /// updating the signature information.</param> /// <param name="xpsDocument"> /// The XPS document containing the signature information.</param> public void IterateSignatures( SignatureDialog signatureDialog, XpsDocument xpsDocument) { bool found = false; IXpsFixedDocumentSequenceReader docSeq = xpsDocument.FixedDocumentSequenceReader; // For every signature in the XPS document. foreach (XpsDigitalSignature sig in xpsDocument.Signatures) { found = false; // For every FixedDocument in the XPS document. foreach (IXpsFixedDocumentReader doc in docSeq.FixedDocuments) { // For every SignatureDefinition in each FixedDocument. foreach (XpsSignatureDefinition signature in doc.SignatureDefinitions) { if (sig.Id != null && sig.Id == signature.SpotId) { found = true; break; } }//end:foreach (XpsSignatureDefinition if (found) { break; } }// end:foreach (IXpsFixedDocument if (!found) { SignatureDisplayItem item = signatureDialog.AddSignatureItem(null); X509Certificate2 cert = sig.SignerCertificate as X509Certificate2; item.Signer = cert.GetNameInfo(X509NameType.SimpleName, false); item.IsSigned = true; } } // end:foreach (XpsDigitalSignature } // end:IterateSignatures()
}// end:Create() //</SnippetCreateAndWriteToXpsDocument> //<SnippetIterateXpsPackageParts> // --------------------- IterateXpsPackageParts() --------------------- /// <summary> /// Iterates through the parts contained in a given XpsDocument /// package initializing a tree view control with the name of each /// part contained within the package.</summary> /// <param name="xpsDocument"> /// The XPS document to extract the part names from.</param> /// <param name="treeView"> /// The TreeView control to insert the part names into.</param> /// <param name="fileName"> /// The XPS document filename.</param> public void IterateXpsPackageParts( XpsDocument xpsDocument, TreeView treeView, string fileName) { // Set up the Tree View treeView.Items.Clear(); treeView.Visibility = Visibility.Visible; TreeViewItem packageNode = new TreeViewItem(); packageNode.ToolTip = fileName; packageNode.Header = System.IO.Path.GetFileName(fileName); treeView.Items.Add(packageNode); // Start with a DoucmentSequence. IXpsFixedDocumentSequenceReader docSeq = xpsDocument.FixedDocumentSequenceReader; TreeViewItem docSeqNode = AddUriToTreeView(packageNode, docSeq.Uri); // For every FixedDocument within the DocumentSequence. foreach (IXpsFixedDocumentReader docReader in docSeq.FixedDocuments) { TreeViewItem docNode = AddUriToTreeView(docSeqNode, docReader.Uri); // For every FixedPage within the FixedDocument. foreach (IXpsFixedPageReader page in docReader.FixedPages) { TreeViewItem pageNode = AddUriToTreeView(docNode, docReader.Uri); // For every Image on the page. foreach (XpsImage image in page.Images) { AddUriToTreeView(pageNode, image.Uri); } // For every Font on the page. foreach (XpsFont font in page.Fonts) { AddUriToTreeView(pageNode, font.Uri); } } } }// end:IterateXpsPackageParts()
}// end:OnAddStructure() // ----------------------- AddDocumentStructure ----------------------- /// <summary> /// Writes a structured XPS document given an unstructured document /// and a file list of XAML document structure elements to add.</summary> /// <param name="xpsUnstructuredFile"> /// The path and filename of the unstructured XPS document.</param> /// <param name="xamlStructureFile"> /// A file list of XAML document structures to add.</param> /// <param name="xpsTargetFile"> /// The path and filename for the new structured /// XPS document to write.</param> /// <remarks> /// If xpsTargetFile exists, it is first deleted and /// then a new structured XPS document written.</remarks> private void AddDocumentStructure( string xpsUnstructuredFile, // source unstructured document string[] xamlStructureFile, // structure definition resources string xpsTargetFile) // target structured XPS document { // Close the current document if one is open. CloseDocument(); ShowStatus("\nCreating new structured XPS\n " + "document '" + Filename(xpsTargetFile) + "'."); // If the new target XPS file exists, prompt to confirm ok to replace. if (File.Exists(xpsTargetFile)) { MessageBoxResult result = MessageBox.Show("'" + xpsTargetFile + "' already exists.\nDo you want to delete and replace it?", "Ok to replace '" + Filename(xpsTargetFile) + "'?", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result != MessageBoxResult.Yes) { return; } ShowStatus(" Deleting old '" + Filename(xpsTargetFile) + "'."); File.Delete(xpsTargetFile); } ShowStatus(" Copying '" + Filename(xpsUnstructuredFile) + "'\n to '" + Filename(xpsTargetFile) + "'."); File.Copy(xpsUnstructuredFile, xpsTargetFile); ShowStatus(" Opening '" + Filename(xpsTargetFile) + "'\n (currently without structure)."); XpsDocument xpsDocument = null; try { xpsDocument = new XpsDocument(xpsTargetFile, FileAccess.ReadWrite); } catch (System.IO.FileFormatException) { string msg = xpsUnstructuredFile + "\n\nThe specified file " + "does not appear to be a valid XPS document."; MessageBox.Show(msg, "Invalid File Format", MessageBoxButton.OK, MessageBoxImage.Error); ShowStatus(" Invalid XPS document format."); return; } ShowStatus(" Getting FixedDocumentSequenceReader."); IXpsFixedDocumentSequenceReader fixedDocSeqReader = xpsDocument.FixedDocumentSequenceReader; ShowStatus(" Getting FixedDocumentReaders."); ICollection <IXpsFixedDocumentReader> fixedDocuments = fixedDocSeqReader.FixedDocuments; ShowStatus(" Getting FixedPageReaders."); IEnumerator <IXpsFixedDocumentReader> enumerator = fixedDocuments.GetEnumerator(); enumerator.MoveNext(); ICollection <IXpsFixedPageReader> fixedPages = enumerator.Current.FixedPages; // Add a document structure to each fixed page. int i = 0; foreach (IXpsFixedPageReader fixedPageReader in fixedPages) { XpsResource pageStructure; ShowStatus(" Adding page structure resource:\n '" + Filename(_fixedPageStructures[i]) + "'"); try { // Add a new StoryFragment to hold the page structure. pageStructure = fixedPageReader.AddStoryFragment(); } catch (System.InvalidOperationException) { MessageBox.Show(xpsUnstructuredFile + "\n\nDocument structure cannot be added.\n\n" + Filename(xpsUnstructuredFile) + " might already " + "contain an existing document structure.", "Cannot Add Document Structure", MessageBoxButton.OK, MessageBoxImage.Error); break; } // Copy the page structure to the new StoryFragment. WriteResource(pageStructure, _fixedPageStructures[i++]); } ShowStatus(" Saving and closing the new document.\n"); xpsDocument.Close(); // Open the new structured document. OpenDocument(xpsTargetFile); ShowDescription(_descriptionString[4] + _descriptionString[5]); ShowPrompt(_descriptionString[5]); }// end:AddDocumentStructure
public bool CreateNewXPSFromSource(string sourceXpsPath, string destinationXpsPath, ReplaceCallBackType cb) { this.m_CallBack = cb; bool blnResult = false; try { // Delete the old file generated by our code. if (File.Exists(destinationXpsPath)) { File.Delete(destinationXpsPath); } // Creating the output XPS file. XpsDocument document = new XpsDocument(destinationXpsPath, FileAccess.ReadWrite, System.IO.Packaging.CompressionOption.NotCompressed); IXpsFixedDocumentSequenceWriter docSeqWriter = document.AddFixedDocumentSequence(); // Loading the source xps files to list to read them for edit. List <string> sourceFiles = new List <string>(); sourceFiles.Add(sourceXpsPath); // Looping each source files. foreach (string sourceFile in sourceFiles) { XpsDocument docToRead = new XpsDocument(sourceFile, FileAccess.ReadWrite); IXpsFixedDocumentSequenceReader docSequenceToRead = docToRead.FixedDocumentSequenceReader; foreach (IXpsFixedDocumentReader fixedDocumentReader in docSequenceToRead.FixedDocuments) { IXpsFixedDocumentWriter fixedDocumentWriter = docSeqWriter.AddFixedDocument(); AddStructure(fixedDocumentReader, fixedDocumentWriter); foreach (IXpsFixedPageReader fixedPageReader in fixedDocumentReader.FixedPages) { IXpsFixedPageWriter pageWriter = fixedDocumentWriter.AddFixedPage(); AddImages(fixedPageReader, pageWriter); AddFonts(fixedPageReader, pageWriter); AddContent(fixedPageReader, pageWriter); // Commmit all changes. pageWriter.Commit(); } fixedDocumentWriter.Commit(); } // Close the current source before openeing next one. docToRead.Close(); } docSeqWriter.Commit(); // Close newly created XPS document. document.Close(); blnResult = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } return(blnResult); }
string[] pages = null; // 用于存放目录文档各节点OutlineTarget值,页码信息 // 读取导航目录 private void ReadDoc(XpsDocument xpsDoc) { IXpsFixedDocumentSequenceReader docSeq = xpsDoc.FixedDocumentSequenceReader; IXpsFixedDocumentReader docReader = docSeq.FixedDocuments[0]; XpsStructure xpsStructure = docReader.DocumentStructure; Stream stream = xpsStructure.GetStream(); XmlDocument doc = new XmlDocument(); doc.Load(stream); //获取节点列表 XmlNodeList nodeList = doc.ChildNodes.Item(0).FirstChild.FirstChild.ChildNodes; if (nodeList.Count <= 0)//判断是否存在目录节点 { //tvTree.Visibility = System.Windows.Visibility.Hidden; tvTree.Items.Add(new TreeViewItem { Header = "没有导航目录" }); return; } tvTree.Visibility = System.Windows.Visibility.Visible; array = new int[nodeList.Count]; array1 = new string[nodeList.Count]; arrayName = new string[nodeList.Count]; pages = new string[nodeList.Count]; for (int i = 0; i < nodeList.Count; i++) { array[i] = Convert.ToInt32(nodeList[i].Attributes["OutlineLevel"].Value); array1[i] = nodeList[i].Attributes["OutlineLevel"].Value.ToString(); arrayName[i] = nodeList[i].Attributes["Description"].Value.ToString(); pages[i] = nodeList[i].Attributes["OutlineTarget"].Value.ToString(); } for (int i = 0; i < array.Length - 1; i++) { //对array进行转换组装成可读的树形结构,通过ASCII值进行增加、转换 array1[0] = "A"; if (array[i + 1] - array[i] == 1) { array1[i + 1] = array1[i] + 'A'; } if (array[i + 1] == array[i]) { char s = Convert.ToChar(array1[i].Substring((array1[i].Length - 1), 1)); array1[i + 1] = array1[i].Substring(0, array1[i].Length - 1) + (char)(s + 1); } if (array[i + 1] < array[i]) { int m = array[i + 1]; char s = Convert.ToChar(array1[i].Substring(0, m).Substring(m - 1, 1)); array1[i + 1] = array1[i].Substring(0, m - 1) + (char)(s + 1); } } //添加一个节点作为根节点 TreeViewItem parent = new TreeViewItem(); TreeViewItem parent1 = null; parent.Header = "目录导航"; Boolean flag = false; for (int i = 0; i < array.Length; i++) { if (array[i] == 1) { flag = true; } if (flag) //如果找到实际根节点,加载树 { parent1 = new TreeViewItem(); parent1.Header = arrayName[i]; parent1.Tag = array1[i]; parent.Items.Add(parent1); parent.IsExpanded = true; parent1.IsExpanded = true; FillTree(parent1, array1, arrayName); flag = false; } } tvTree.Items.Clear(); tvTree.Items.Add(parent); }
public bool Read(string filePath, string outputFolder, List <byte[]> imageBytes, List <string> imageNames, ContractParameters settings, ProgressDelegate progress) { if (LogHelper.CanDebug()) { LogHelper.Begin("XPSImageReader.Read"); } try { XpsDocument xpsDocument = null; // read the document xpsDocument = new XpsDocument(filePath, FileAccess.Read, CompressionOption.NotCompressed); // IXpsFixedDocumentSequenceReader fixedDocSeqReader = xpsDocument.FixedDocumentSequenceReader; ICollection <IXpsFixedDocumentReader> fixedDocuments = fixedDocSeqReader.FixedDocuments; IEnumerator <IXpsFixedDocumentReader> enumerator = fixedDocuments.GetEnumerator(); enumerator.MoveNext(); ICollection <IXpsFixedPageReader> fixedPages = enumerator.Current.FixedPages; string imageFileName = Path.GetFileNameWithoutExtension(filePath); int i = 0; foreach (IXpsFixedPageReader fixedPageReader in fixedPages) { try { ICollection <XpsImage> list = fixedPageReader.Images; if (list.Count == 1) { XpsImage img = list.First(); if (img != null) { using (Stream xpsThumbStream = img.GetStream()) { byte[] buf = new byte[xpsThumbStream.Length]; xpsThumbStream.Read(buf, 0, buf.Length); imageBytes.Add(buf); imageNames.Add(imageFileName + "_" + i + ".jpg"); } } } i++; } catch (System.InvalidOperationException) { } } xpsDocument.Close(); string msg = CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageExtracted", "{0} images extracted..."); progress(string.Format(msg, imageBytes.Count)); } catch (Exception err) { LogHelper.Manage("XPSImageReader.Read", err); settings.Result = false; return(false); } finally { LogHelper.End("XPSImageReader.Read"); } return(true); }
public ParsedData parseData(string filename) { /* * NAME (last, first) CHAR DOE, JOHN * DOB NUM MM/DD/YYYY * MRN CHAR NNNNNNN * StudyID NUM AlphaNumeric * SEX CHAR M/F * RACE CHAR WHITE, BLACK, ASIAN, NATIVE AMERICAN, PACIFIC ISLANDER, BIRACIAL, etc * ETHNICITY CHAR HISPANIC, NOT HISPANIC, MIDDLE EASTERN * ADMISSION DATE NUM MM/DD/YYYY * DISCHARGE DATE NUM MM/DD/YYYY * HOSPITAL LOCATION NUM SR AFLAC IP, EG 3-E (AFLAC), EG AFLAC BMT, SR PEDIATRIC ICU, EG PEDIATRIC ICU * PRIMARY ONC DIAGNOSIS CHAR SPECIFIC DISEASE * DATE OF PRIMARY ONC DIAGNOSIS NUM MM/DD/YYYY * SECONDARY ONC DIAGNOSIS CHAR SPECIFIC DISEASE * DATE OF SECONDARY ONC DIAGNOSIS NUM MM/DD/YYYY * RELAPSE CHAR Y/N * DATE OF RELAPSE NUM MM/DD/YYYY * BMT CHAR Y/N * BMT DATE NUM MM/DD/YYYY * BMT TYPE CHAR ALLO/AUTO * LINE INSERTION DATE NUM MM/DD/YYYY * LINE REMOVAL DATE NUM MM/DD/YYYY * LINE TYPE CHAR DLCVL, PORT, DLPORT, PICC * HAS SECONDARY LINE CHAR Y/N * SECONDARY LINE TYPE CHAR DLCVL, PORT, DLPORT, PICC * BLOOD CULTURE ORDERED CHAR Y/N * POSITIVE BLOOD CULTURE CHAR Y/N * ORGANISM PRESENT IN BLOOD CULTURE CHAR GENUS SPECIES * DATE OF POS BLOOD CULTURE NUM MM/DD/YYYY * CLABSI CHAR Y/N * TOTAL NUMBER CLABSI DURING TIME INTERVAL NUM 0-N * WBC COUNT AT POS BCX DX NUM 0-NNN,NNN * ANC AT POS BCX DX NUM 0-NNN,NNN * LINE ENTRIES IN INTERVAL NUM 0-N * LINE ENTRIES LAST 24 HRS NUM 0-N * NUMBER MOUTH CARE IN INTERVAL NUM 0-N * NUMBER MOUTH CARE 72 HRS NUM 0-N * MOUTHCARE TYPE CHAR BRUSH, RINSE * RINSE AGENT CHAR BIOTENE, PERIDEX * NUMBER CHG BATHS IN INTERVAL NUM 0-N * CHG BATHS 72 HRS BEFORE POSITIVE BCX NUM 0-N * PREOP CHG BATH CHAR Y/N * ROUTINE BATH CHAR Y/N * OTHER EXTERNAL LINE/DRAIN PRESENT CHAR GT, GJT, CT, JPDRAIN, WOUNDVAC, FOLEY, NEPHROSTOMY, TRACH * LAST DRESSING CHANGE DATE NUM MM/DD/YYYY * DATES OF DRESSING CHANGES NUM MM/DD/YYYY * FREQUENCY DRESSING CHANGE (DAYS) NUM 0-NN * TOTAL DRESSING CHANGES IN INTERVAL NUM 0-N * LAST TUBING CHANGE DATE NUM MM/DD/YYYY * FREQUENCY TUBING CHANGE (DAYS) NUM 0-NN * LAST CAP CHANGE DATE NUM MM/DD/YYYY * FREQUENCY CAP CHANGE (DAYS) NUM 0-NN * TOTAL CAP CHANGES NUM 0-N * HIGH TOUCH SURFACE CLEAN PROTOCOL CHAR Y/N * DAILY LINEN CHANGE CHAR Y/N */ XpsDocument _xpsDocument = new XpsDocument(filename, System.IO.FileAccess.Read); IXpsFixedDocumentSequenceReader fixedDocSeqReader = _xpsDocument.FixedDocumentSequenceReader; IXpsFixedDocumentReader _document = fixedDocSeqReader.FixedDocuments[0]; IXpsFixedPageReader _page = _document.FixedPages[0]; StringBuilder _currentText = new StringBuilder(); System.Xml.XmlReader _pageContentReader = _page.XmlReader; if (_pageContentReader != null) { while (_pageContentReader.Read()) { if (_pageContentReader.Name == "Glyphs") { if (_pageContentReader.HasAttributes) { if (_pageContentReader.GetAttribute("UnicodeString") != null) { _currentText.Append(" "); _currentText. Append(_pageContentReader. GetAttribute("UnicodeString")); } } } } } string _fullPageText = _currentText.ToString(); // MessageBox.Show(_fullPageText); // return new ParsedData() { Name = filename }; return(fakeparse(filename)); }
private bool CreateNewXPSFromSource() { bool blnResult = false; try { // Delete the old file generated by our code. if (File.Exists(destinationXpsPath)) { File.Delete(destinationXpsPath); } // Creating the output XPS file. XpsDocument document = new XpsDocument(destinationXpsPath, FileAccess.ReadWrite, System.IO.Packaging.CompressionOption.Maximum); IXpsFixedDocumentSequenceWriter docSeqWriter = document.AddFixedDocumentSequence(); // Loading the source xps files to list to read them for edit. List <string> sourceFiles = new List <string>(); sourceFiles.Add(sourceXPS); // Looping each source files. foreach (string sourceFile in sourceFiles) { XpsDocument docToRead = new XpsDocument(sourceFile, FileAccess.ReadWrite); IXpsFixedDocumentSequenceReader docSequenceToRead = docToRead.FixedDocumentSequenceReader; foreach (IXpsFixedDocumentReader fixedDocumentReader in docSequenceToRead.FixedDocuments) { IXpsFixedDocumentWriter fixedDocumentWriter = docSeqWriter.AddFixedDocument(); AddStructure(fixedDocumentReader, fixedDocumentWriter); foreach (IXpsFixedPageReader fixedPageReader in fixedDocumentReader.FixedPages) { IXpsFixedPageWriter pageWriter = fixedDocumentWriter.AddFixedPage(); AddImages(fixedPageReader, pageWriter); AddFonts(fixedPageReader, pageWriter); AddContent(fixedPageReader, pageWriter); // Commmit all changes. pageWriter.Commit(); } fixedDocumentWriter.Commit(); } // Close the current source before openeing next one. docToRead.Close(); } docSeqWriter.Commit(); // Show the modified content in a DocumentViewer. dvModifiedXPS.Document = document.GetFixedDocumentSequence(); ModifiedGrid.Visibility = System.Windows.Visibility.Visible; // Close newly created XPS document. document.Close(); blnResult = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } return(blnResult); }
public FlowDocument Convert(string filename) { FlowDocument fdoc = new FlowDocument(); Package pkg = Package.Open(filename, FileMode.Open, FileAccess.Read); string pack = "pack://temp.xps"; PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument _doc = new XpsDocument(pkg, CompressionOption.Fast, pack); /*foreach (DocumentReference dr in _doc.GetFixedDocumentSequence().References) * { * foreach (PageContent pc in dr.GetDocument(false).Pages) * { * FixedPage fp = pc.GetPageRoot(false); * BlockUIContainer cont = new BlockUIContainer(); * cont.Child = fp; * fdoc.Blocks.Add(cont); * } * } * * viewer.Document = fdoc; * * this.Content = viewer; * return;*/ IXpsFixedDocumentSequenceReader fixedDocSeqReader = _doc.FixedDocumentSequenceReader; Dictionary <string, string> fontList = new Dictionary <string, string>(); foreach (IXpsFixedDocumentReader docReader in fixedDocSeqReader.FixedDocuments) { foreach (IXpsFixedPageReader fixedPageReader in docReader.FixedPages) { while (fixedPageReader.XmlReader.Read()) { string page = fixedPageReader.XmlReader.ReadOuterXml(); string path = string.Empty; foreach (XpsFont font in fixedPageReader.Fonts) { string name = font.Uri.GetFileName(); path = string.Format(@"{0}\{1}", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), name); if (!fontList.ContainsKey(font.Uri.OriginalString)) { fontList.Add(font.Uri.OriginalString, path); font.SaveToDisk(path); } } foreach (XpsImage image in fixedPageReader.Images) { //here to get images } foreach (KeyValuePair <string, string> val in fontList) { page = page.ReplaceAttribute("FontUri", val.Key, val.Value); } FixedPage fp = XamlReader.Load(new MemoryStream(Encoding.Default.GetBytes(page))) as FixedPage; /*fp.Children.OfType<Glyphs>().ToList().ForEach(glyph => * { * Binding b = new Binding(); * b.Source = glyph; * b.Path = new PropertyPath(Glyphs.UnicodeStringProperty); * glyph.SetBinding(TextSearch.TextProperty, b); * });*/ BlockUIContainer cont = new BlockUIContainer(); cont.Child = fp; fdoc.Blocks.Add(cont); //string outp = XamlWriter.Save(fp); } } } return(fdoc); }
public static FlowDocument ConvertXPSDocumentToFlowDocument(Stream stream) { FlowDocument fdoc = new FlowDocument(); fdoc.FlowDirection = FlowDirection.LeftToRight; Package pkg = Package.Open(stream, FileMode.Open, FileAccess.Read); string pack = "pack://temp.xps"; Uri uri = new Uri(pack); PackageStore.AddPackage(uri, pkg); XpsDocument _doc = new XpsDocument(pkg, CompressionOption.Fast, pack); DocumentPaginator xpsPaginator = ((IDocumentPaginatorSource )_doc.GetFixedDocumentSequence()).DocumentPaginator; DocumentPage fixedpage = xpsPaginator.GetPage(0); fdoc.PageHeight = fixedpage.Size.Height; fdoc.PageWidth = fixedpage.Size.Width; fdoc.ColumnGap = 0; fdoc.ColumnWidth = fixedpage.Size.Width; fdoc.PagePadding = new Thickness(0, 0, 0, 0); DocumentPaginator flowPainator = ((IDocumentPaginatorSource )fdoc).DocumentPaginator; flowPainator.PageSize = fixedpage.Size; IXpsFixedDocumentSequenceReader fixedDocSeqReader = _doc.FixedDocumentSequenceReader; Dictionary <string, string> imageList = new Dictionary <string, string>(); Dictionary <string, string> fontList = new Dictionary <string, string>(); foreach (IXpsFixedDocumentReader docReader in fixedDocSeqReader.FixedDocuments) { foreach (IXpsFixedPageReader fixedPageReader in docReader.FixedPages) { while (fixedPageReader.XmlReader.Read()) { string page = fixedPageReader.XmlReader.ReadOuterXml(); foreach (XpsFont font in fixedPageReader.Fonts) { string name = GetFileName(font.Uri); string guid = new Guid(name.Split('.')[0]).ToString("N"); name = System.IO.Path.Combine(guid, System.IO.Path.GetFileNameWithoutExtension(name) + ".ttf"); string path = string.Format(@"{0}\{1}", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), name); if (!fontList.ContainsKey(font.Uri.OriginalString)) { SaveToDisk(font, path); fontList.Add(font.Uri.OriginalString, path); } } foreach (XpsImage image in fixedPageReader.Images) { //here to get images string name = Helper.GetFileName(image.Uri); string path = string.Format(@"{0}\{1}", System.IO.Path.GetTempPath(), name); if (!imageList.ContainsKey(image.Uri.OriginalString)) { imageList.Add(image.Uri.OriginalString, path); Helper.SaveToDisk(image, path); } } foreach (KeyValuePair <string, string> val in fontList) { page = Helper.ReplaceAttribute(page, "FontUri", val.Key, val.Value); } foreach (KeyValuePair <string, string> val in imageList) { page = Helper.ReplaceAttribute(page, "ImageSource", val.Key, val.Value); } FixedPage fp = XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(page))) as FixedPage; //FixedPage fp = XamlReader.Load(new MemoryStream(Encoding.Default.GetBytes(page ))) as FixedPage; fp.Children.OfType <Glyphs>().ToList().ForEach(glyph => { Binding b = new Binding(); b.Source = glyph; b.Path = new PropertyPath(Glyphs.UnicodeStringProperty); glyph.SetBinding(TextSearch.TextProperty, b); }); BlockUIContainer cont = new BlockUIContainer(); cont.Child = fp; ((Block)cont).Margin = new Thickness(0); ((Block)cont).Padding = new Thickness(0); fdoc.Blocks.Add(cont); } } } pkg.Close(); PackageStore.RemovePackage(uri); return(fdoc); }