Are there any FlowDocument diff viewers for WPF? - wpf

We have 2 flowdocuments that we'd like to compare similar to when using a diff viewer (winmerge, beyond compare, etc). Has anybody done this or know how to get the text out of a flowdocument to do a compare?

Here's a way to save it as raw xaml (text file) from the code-behind file, assuming that the flowdocument (not viewer) itself is named "myFlowDoc", if only the viewer is named, use the property .Document of the viewer to get it. And a stream to a stream myStream (FileStream, MemoryStream, etc doesn't matter).
// Create a TextRange around the entire document.
TextRange documentTextRange = new TextRange(myFlowDoc.ContentStart, myFlowDoc.ContentEnd);
// Save it. Note that it will not respect current stream position;
// it'll assume that it gets the entire stream.
documentTextRange.Save(myStream, DataFormats.Xaml);

I just forged together a basic WPF diff viewer. Shouldn't be too hard to adapt it to write a side by side Flowdocument diff view.
Find more information here: http://www.eqqon.com/index.php/GitSharp#GitSharp.Demo
-- henon

Related

WPF Visual to XPS document method creates only one page

I have a WPF Window that I want to save to an XPS file (or really, any type of file that would store the window image). This window contains a lengthy DataGrid. So far I am able to write to an XPS file, but the resulting document contains only one page, so most of the DataGrid rows are missing. How can I get the XPSDocumentWriter to use as many pages as necessary?
Here is what I've got so far (I've turned off the grid scroll bar and autosized the window to make sure it is full-sized before writing to XPS file):
Dim visual = CType(Me.Content, Media.Visual)
Me.LogGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden
Me.SizeToContent = Windows.SizeToContent.WidthAndHeight
Dim xd As New System.Windows.Xps.Packaging.XpsDocument(file, IO.FileAccess.ReadWrite)
Dim xw = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(xd)
xw.Write(visual)
xd.Close()
I think Will's comment is probably the right answer.

Print FlowDocument centered on page

In my WPF application I want to print a custom generated FlowDocument but I have big problems getting the pages on the center of the paper. Every page is aligned to the upper left corner. Even so close the printer can not reach it. Small parts of the document are missing. On the lower and right side there is plenty of empty space so the document can easiely fit on the paper. If it would be centered!
Is the any way to set borders/margin/or offset for the PrintTicket or the Paginator?
I did not find anything that would work.
This is what I do:
// selectedDocument is a FlowDocument
private const double PAGE_HEIGHT = 728;
private const double PAGE_WIDTH = 1024;
var paginator
= ((IDocumentPaginatorSource)this .selectedDocument).DocumentPaginator;
paginator.PageSize = new Size(PAGE_WIDTH, PAGE_HEIGHT);
printDialog.PrintTicket.PageOrientation
= System.Printing.PageOrientation.Landscape;
printDialog.PrintDocument(paginator, "Report");
I also tried different page sizes but it makes no difference.
If I save my FlowDocument as XpsDocument via XpsSerializationManager the created file looks perfect. Borders and margins are all as they should be. In a later step I use this file to create a pdf file. If I then print the pdf-File it looks fine on paper too.

Fastest way to convert RTF to FlowDocument

What is the fastest way to convert a RTF to FlowDocument? I store RTF as plain string and then reload it back, I am using following method,
FlowDocument document = new FlowDocument();
document.SetValue(FlowDocument.TextAlignmentProperty, TextAlignment.Left);
TextRange content = new TextRange(document.ContentStart, document.ContentEnd);
if (content.CanLoad(DataFormats.Rtf) && string.IsNullOrEmpty(rtf) == false)
{
// If so then load it with RTF
byte[] valueArray = Encoding.ASCII.GetBytes(rtf);
using (MemoryStream stream = new MemoryStream(valueArray))
{
content.Load(stream, DataFormats.Rtf);
}
}
But this method is very slow. I need to load many RTFs (around 1000). What can be the trick to make the process fast? Is there any other way around to load a Flowdocument?
You really need to define what you actually need. TextBlock is not weak at all.
It has things to offer ;).
Colours(Background/Foreground + you can color specific part of TextBlock even)
Alignments(you can align TextBlocks as you want, and perhaps even part of them?! Not sure about the last one.
It has TextDecorations, which means it supports bold/italic/underline/strikethrough etc.
Fonts(yeah it supports custom fonts and whatever font you want)
But fair enough. I think you should store FlowDocument XAML instead of actual RTF. This way there will be no conversion and it should be multiple times faster. (See DataFormats.xaml)
Hello Vibhore the TextBlock element should be used when limited text support is required, Label can be used when minimal text support is required.
The FlowDocument element is a container for re-flowable documents that support rich presentation of content, and therefore, has a greater performance impact than using the TextBlock or Label controls.

Output control in Bitmap

I want to implement previews/thumbnails in my project, therefor i need the graphical output of a control as bitmap. I have a third party control which loads documents and displays them. Is it possible to fetch the output of an control and store it in a bitmap object without adding it to the UI? And If how?
Edit: I probably should said that before, but i don't know if that's important. The ThirdParty Control is an OCX(ActiveX control).
in a Form do:
Bitmap myBitmap = new Bitmap(button1.Width, button1.Height);
// button1.Draw..., not 'this.Draw...'!
button1.DrawToBitmap(myBitmap, button1.DisplayRectangle);
myBitmap.Save(#"C:\test.bmp");

What's the point of XPS?

When I read books about WPF, I saw the authors mention XPS like it was something important. Windows also includes its XPS viewer, and I've seen that listed as a "feature" of Windows.
But why? What's the point? Who the heck uses it? It's my understanding that XPS is, basically, like PDF, xhtml, or ePub (which is just xhtml)...or even Word's docx format. Many of the features are the same among those formats.
It doesn't seem to have any major benefits compared to any of those other formats. It seems to me that xhtml would be so much more useful than XPS as a way to save and load FlowDocuments from the RichTextBox. I've looked at multiple blogs about converting between the two. Most or all of the rich text on the internet is (x)html. Beyond that, I don't think anyone uses it just to publish their docs; PDF is preferred. It seems like XPS is just some random format that MS made and decided to push. I generally love MS, but they do have a habit of that kind of thing. Couldn't MS have made an api using xhtml instead? That would have been more useful in a lot of situations, I'd think.
So, is there a point to using XPS, particularly in comparison to one of the other formats I mentioned (or any I haven't)? Have you ever used XPS in your programs or otherwise?
As U62 already stated, WPF comes with a DocumentViewer control which enables you to view XPS documents. The DocumentViewer also has some useful fonctions like Print, Zoom, FitToPage etc... So you don't need to implement that or use a third party tool.
What I just finished an hour ago using XPS and the DocumentViewer was some kind of "Adress label print preview". Allow the user to select some contacts from a list of contacts, click "Print Preview". This opens a new XAML Window which contains a DocumentViewer control and a ListBox with the choice of different Labels (e.g. 1 sheet with 12 labels [2 columns, 6 rows], 1 sheet with a single label whose width and height can be user defined).
Based on the users selection, I generate an XPS Document in the layout the user selected with the adresses of the selected contacts. If e.g. the user selected 4 contacts and wishes to print them on "SingleLabelSheet"'s, I generate 1 XPS document with 4 pages, each page containing 1 Adress. Then I display the XPS in the DocumentViewer and the user can print the labels on our Label Printer.
Once I understood how the XPS API worked (at least the Basics), it was a matter of 2 hours to get this up and running.
So, basically, I see XPS as an easy to use API to display FixedDocuments which are to be generated on the fly. But I wouldn't personnally go about saving them to my HDD or somehow modify them or whatever you generally do with documents.
The only actual advantage I can think of is that you have a control for viewing XPS documents in WPF applications. The other formats you mention mean you would have to bring in a 3rd party renderer (or write one yourself if you have a year to spare).
btw. I don't know much about ePub, but XPS isn't directly comparable with XHTML, it's more like PDF in that it's designed to have a fixed layout.
XPS to WPF is like WMF to Win32/WinForms, it's a persistent format that let you store and print native WPF graphics.
XPS is used to print from WPF (even when you print directly from the application without saving, the internal printing system is built on XPS) so what should MS do:
Create a new file format that exactly fit with what they are trying to do
Build a 100% perfect translator from WPF to a format they don't control like PDF (and hope Adobe doesn't break all WPF applications out there with the next release of Acrobat Reader).
What would you do?
Saving XPS files is just a nice bonus.
Look, I may be a pessimist on XPS as a report generation solution, but I gave it a go and found the initial documentation to be hard to understand, with less real world samples out there than what I would have liked. When I put it into a real world business application I found it to be frustrating, particularly in LOB apps that require tables that span over multiple pages.
Things may have changed since then but as soon as I started looking at tables that spanned over several pages and I wanted column headers to go to the top, etc. I found that the API required me to do what I would call excessive workarounds with unnecessary complexity.
So, things may have changed since then (about 8 months ago), but I went from XPS to using ITextSharp and that has been a lot less painful.
So the only advantage I would say, like everyone else, is the built in viewer in WPF - but other than that I feel the API may need to "mature" a bit more before I will attempt something again in it.
Actually I found a really nice reason to use XPS. I wanted to print from multiple sources, merge documents and specify duplex and stapled. Finally it should be printed as one document with duplex and stapled. I was having a difficult time doing so but found that by printing to XPS (saved to disc) I could accomplish my goal with minimum fuss. I haven't found any other method that is so easy and straightforward.
Dim PrintServer As New SysPrint.PrintServer("\\" & My.Computer.Name)
Dim PrintQ As New SysPrint.PrintQueue(PrintServer, "Ricoh Main")
Dim Jobs As SysPrint.PrintJobInfoCollection = PrintQ.GetPrintJobInfoCollection
Dim able As SysPrint.PrintCapabilities = PrintQ.GetPrintCapabilities()
Dim CurrentTicket As SysPrint.PrintTicket = PrintQ.CurrentJobSettings.CurrentPrintTicket
If able.StaplingCapability IsNot Nothing AndAlso able.StaplingCapability.Count > 0 Then
If able.StaplingCapability.Contains(Printing.Stapling.StapleTopLeft) Then
CurrentTicket.Stapling = Printing.Stapling.StapleTopLeft
End If
Else
Debug.Print("no stapling capability")
End If
CurrentTicket.Duplexing = Printing.Duplexing.TwoSidedLongEdge
Dim fiName As String = "S:\Temp\PS\XPS\Test.xps"
Dim TestJob As SysPrint.PrintSystemJobInfo _
= PrintQ.AddJob("Test job", fiName, False)
XPS (code named "metro") was clearly designed as the Microsoft alternative to PDF and PostScript in Windows Vista. See this old article here: Microsoft Readies New Document Printing Specification
There are different approches when inventing document formats:
Some are made for quick view on screen (say low def) like HTML, doc.
Some other are (or can be) very respectuous of printing contrains (say quality based) like PDF, XPS.
So XPS whiches to be as good as PDF, plus it is formated in XML, so "maybe" it is more standard than the stream approch in PDF.
The black spot of XPS is maybe the management of special colors (Pantone, paper effects).

Resources