i am trying to to generate a XPS Document from a WPF Control. Printing works so far, but i cannot find a way to create the XPS in landscape mode.
My code to create the XPS file, mostly taken from another SO page
public FixedDocument ReturnFixedDoc()
{
FixedDocument fixedDoc = new FixedDocument();
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
var ctrl = new controlToPrint();
//Create first page of document
fixedPage.Children.Add(ctrl);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
//Create any other required pages here
return fixedDoc;
}
public void SaveCurrentDocument()
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "MyReport"; // Default file name
dlg.DefaultExt = ".xps"; // Default file extension
dlg.Filter = "XPS Documents (.xps)|*.xps"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
FixedDocument doc = ReturnFixedDoc();
XpsDocument xpsd = new XpsDocument(filename, FileAccess.Write);
System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
xw.Write(doc);
xpsd.Close();
}
}
Any help is appreciated.
Try setting the size of your FixedPage in ReturnFixedDoc:
// hard coded for A4
fixedPage.Width = 11.69 * 96;
fixedPage.Height = 8.27 * 96;
The numbers are in the form (inches) x (dots per inch). 96 is the DPI of WPF. I have used the dimensions of an A4 page.
Related
So I am trying to convert a standard A4 PDF file into a .txt file using Spire.Pdf NuGet Package, and whenever I do it there is a lot of whitespace at the start of each line where the margins of the document go I presume. I managed to solve the issue using the TrimStart() method but I want to be able to do remove the margins using Spire.Pdf itself.
I have played around with setting a PdfTextExtractOptions ExtractArea RectangleF but for some reason it cuts the bottom of the text and I lose rows.
My code is:
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"path");
var content = new List<string>();
RectangleF rectangle = new RectangleF(45, 0, 0, 0);
PdfTextExtractOptions options = new() { IsExtractAllText = true, IsShowHiddenText = true, ExtractArea = rectangle };
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor textExtractor = new(page);
//extract text from a specific rectangular area here - defualt A4 margin sizes?
string extractedText = textExtractor.ExtractText(options);
content.Add(extractedText);
}
FileStream fs = new FileStream(#"outputFile.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string txtBefore = (string.Join("\n", content));
sw.Write(txtBefore);
Thanks in advance
You can try the code below to extract text from PDF, it will not generate extra white spaces at the start of each line in the result .txt file. I already tested it.
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"test.pdf");
PdfTextExtractOptions options = new PdfTextExtractOptions();
options.IsSimpleExtraction = true;
StringBuilder sb = new StringBuilder();
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor extractor = new PdfTextExtractor(page);
sb.AppendLine(extractor.ExtractText(options));
}
File.WriteAllText("Extract.txt", sb.ToString());
I'm using DocumentViewer in a WPF XAML project. I create a fixed document with the following code. The page looks fine in the viewer. When I print it, it prints in landscape view, but the top 1-2 cm is cut off! I tried it without the scale transform on the dockpanel but that had no effect.
private void PrintReport()
{
PrintDialog pd = new PrintDialog();
pd.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
pd.PrintTicket = pd.PrintQueue.DefaultPrintTicket;
pd.PrintTicket.PageOrientation = PageOrientation.Landscape;
pd.PrintDocument(docViewer.Document.DocumentPaginator, "DaySheet");
}
public void BuildReport(DockPanel dpPrint)
{
try
{
// init
ScaleTransform st = new ScaleTransform(0.5, 0.5, 0, 0);
dpPrint.RenderTransform = st;
Size pgSize = new Size(96 * 11.69, 96 * 8.27);
FixedDocument fd = new FixedDocument();
// add page content
FixedPage fp = new FixedPage();
fp.Width = pgSize.Width;
fp.Height = pgSize.Height;
fp.Children.Add(dpPrint);
// set page content
PageContent pc = new PageContent();
pc.Child = fp;
fd.Pages.Add(pc);
// set up fresh XpsDocument
var uri = new Uri("pack://daysheet_report.xps");
PackageStore.RemovePackage(uri);
var stream = new MemoryStream();
var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);
PackageStore.AddPackage(uri, package);
var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);
// write FixedDocument to the XpsDocument
var docWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
docWriter.Write(fd);
// display XpsDocument in DocumentViewer
docViewer.Document = xpsDoc.GetFixedDocumentSequence();
docViewer.Document.DocumentPaginator.PageSize = pgSize;
}
catch (Exception ex)
{
gFunc.ProcessError(ex);
}
}
I tried playing around with printer drivers but it seemed to make no difference. The printer driver I have installed is the correct one for my laser printer and the right version for Windows 10 64-bit. When I print from Word, Excel, PDF its all fine, but from my WPF app it crops the top part of the page content.
As is so often the case, I got around the problem with a hack. I just changed the page content to use a StackPanel and I placed a blank TextBlock as the first child to push the other content down.
I`m trying to print some mark sheets. I created a WPF window and print whole window in this way:
PrintDialog pd = new System.Windows.Controls.PrintDialog();
if (pd.ShowDialog() == true)
{
pd.PrintVisual(this.Content as Visual, "Report");
}
Then I want to add more mark sheet in on document: insert each student marks in that window, add it to a page.
And then print a single file in this way:
PrintDialog pd = new System.Windows.Controls.PrintDialog();
FixedDocument document = new FixedDocument();
document.DocumentPaginator.PageSize = new System.Windows.Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight);
FixedPage page1 = new FixedPage();
page1.Width = document.DocumentPaginator.PageSize.Width;
page1.Height = document.DocumentPaginator.PageSize.Height;
page1.Children.Add(this);
PageContent page1Content = new PageContent();
((IAddChild)page1Content).AddChild(page1);
document.Pages.Add(page1Content);
FixedPage page2 = new FixedPage();
page2.Width = document.DocumentPaginator.PageSize.Width;
page2.Height = document.DocumentPaginator.PageSize.Height;
page2.Children.Add(this);
PageContent page2Content = new PageContent();
((IAddChild)page2Content).AddChild(page2);
document.Pages.Add(page2Content);
if (pd.ShowDialog() == true)
{
pd.PrintDocument(document.DocumentPaginator, "My first document");
}
But the problem is when I add Window (this) to pages as element:
page1.Children.Add(this);
I have Window must be the root of the tree.Cannot add Window as a child of Visual. Source=< Cannot evaluate the exception source> error.
I want to create a PNG from a view. I am using this code:
//I instance the user control
ucFormToPrintView miViewToPrint = new ucFormToPrintView();
miViewToPrint.DataContext = ((ucFormToPrintView)CCForm).DataContext;
//I use a RenderTargetBitmap to render the user control
System.Windows.Media.Imaging.RenderTargetBitmap rtb = new System.Windows.Media.Imaging.RenderTargetBitmap(794, 1122, 72, 72, System.Windows.Media.PixelFormats.Pbgra32);
rtb.Render(miViewToPrint);
//I use an encoder to create the png
System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));
//I use a dialog to select the path where to save the png file
Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
saveFileDialog.FilterIndex = 1;
if (saveFileDialog.ShowDialog() == true)
{
using (System.IO.Stream stream = saveFileDialog.OpenFile())
{
encoder.Save(stream);
stream.Close();
System.Diagnostics.Process.Start(saveFileDialog.FileName);
}
}
The result is an empty png.
How can I create a png file from a user control?
Thank so much.
The UserControl has to be laid out at least once to be visible. You can achieve that by calling its Measure and Arrange methods.
var miViewToPrint = new ucFormToPrintView();
miViewToPrint.DataContext = ((ucFormToPrintView)CCForm).DataContext;
// layout, i.e. measure and arrange
miViewToPrint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
miViewToPrint.Arrange(new Rect(miViewToPrint.DesiredSize));
...
if (saveFileDialog.ShowDialog() == true)
{
using (var stream = saveFileDialog.OpenFile())
{
encoder.Save(stream);
}
System.Diagnostics.Process.Start(saveFileDialog.FileName);
}
Just wondering if there is a way to set the print document orientation on a Print Dialog that is using a flow document.
e.g.
var document = userControl.Content as FlowDocument;
var printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
var paginator = ((IDocumentPaginatorSource) document).DocumentPaginator;
paginator.PageSize = new Size(userControl.Width, userControl.Height);
//Set Orientation Landscape .....
printDialog.PrintDocument(paginator, PrintDescription);
}
Use:
printDialog.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;
You need to add a reference to ReachFramework.dll and System.Printing.dll each.