Ignored Paper Size in PrintDialog/XPS Document Writer - c#

I am trying to print with WPF's PrintDialog class (namespace System.Windows.Controls in PresentationFramework.dll, v4.0.30319). This is the code that I use:
private void PrintMe()
{
var dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
dlg.PrintVisual(new System.Windows.Shapes.Rectangle
{
Width = 100,
Height = 100,
Fill = System.Windows.Media.Brushes.Red
}, "test");
}
}
The problem is no matter what Paper Size I select for "Microsoft XPS Document Writer", the generated XPS, always, has the width and height of "Letter" paper type:
This is the XAML code I can find inside XPS package:
<FixedPage ... Width="816" Height="1056">

Changing the paper size in the print dialog only affects the PrintTicket, not the FixedPage content. The PrintVisual method produces Letter size pages, so in order to have a different page size you need to use the PrintDocument method, like so:
private void PrintMe()
{
var dlg = new PrintDialog();
FixedPage fp = new FixedPage();
fp.Height = 100;
fp.Width = 100;
fp.Children.Add(new System.Windows.Shapes.Rectangle
{
Width = 100,
Height = 100,
Fill = System.Windows.Media.Brushes.Red
});
PageContent pc = new PageContent();
pc.Child = fp;
FixedDocument fd = new FixedDocument();
fd.Pages.Add(pc);
DocumentReference dr = new DocumentReference();
dr.SetDocument(fd);
FixedDocumentSequence fds = new FixedDocumentSequence();
fds.References.Add(dr);
if (dlg.ShowDialog() == true)
{
dlg.PrintDocument(fds.DocumentPaginator, "test");
}
}

Related

How to set text alignment in dynamically created FixedDocument

I am creating a report through FixedDocument and I am doing it in the code behind to dynamically add data to the report.
I started using FixedDocument today and got stuck in aligning texts. It does not seem to center align. Here's my code:
using System.Windows.Documents;
....
public void GenerateReport()
{
FixedDocument document = new FixedDocument();
PageContent content = new PageContent();
FixedPage page = new FixedPage();
page.Width = document.DocumentPaginator.PageSize.Width;
page.Height = document.DocumentPaginator.PageSize.Height;
page.Background = System.Windows.Media.Brushes.AliceBlue;
//header first line
System.Windows.Controls.Canvas canvas = new System.Windows.Controls.Canvas();
canvas.Width = document.DocumentPaginator.PageSize.Width;
FixedPage.SetTop(canvas, 15);
FixedPage.SetLeft(canvas, 15);
System.Windows.Controls.TextBlock block = new System.Windows.Controls.TextBlock();
block.FontSize = 11;
block.FontWeight = FontWeights.Bold;
block.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
block.Text = "This is the first line";
block.HorizontalAlignment = HorizontalAlignment.Center;
canvas.Children.Add(block);
page.Children.Add(canvas);
//header second line
System.Windows.Controls.TextBlock block2 = new System.Windows.Controls.TextBlock(); block.FontSize = 11;
block2.FontWeight = FontWeights.Bold;
block2.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
block2.Text = "Daily Report";
var canvas2 = new System.Windows.Controls.Canvas();
canvas2.Children.Add(block2);
FixedPage.SetTop(canvas2, 30);
FixedPage.SetTop(canvas2, 30);
FixedPage.SetLeft(canvas2, 15);
FixedPage.SetRight(canvas2, 15);
canvas2.Width = document.DocumentPaginator.PageSize.Width;
page.Children.Add(canvas2);
((IAddChild)content).AddChild(page);
document.Pages.Add(content);
}
How will I do the alignment right?
https://learn.microsoft.com/en-us/dotnet/api/system.windows.documents.flowdocument?view=net-5.0#properties
I'm not sure if you can do this with FixedDocument. This is available in Flowdocument though with the TextAlignmentProperty.

How to print .docx silently with c#

I want to print a .docx file silently and being able to choose the tray of the printer.
At first I tried to print the .docx with the Microsoft.Office.Interop.Word but word is opening...
After I converted the .docx file to an image and printed it with ProcessStartInfo but it shows a printing window to the user.
ProcessStartInfo info = new ProcessStartInfo(imageFilePath);
info.Verb = "Print";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(info);
I tried another method it print the image silently BUT the image is blured and not scaled correctly.
PrinterSettings settings = new PrinterSettings();
string defaultPrinter = settings.PrinterName;
FileInfo fileInfo = new FileInfo(imageFilePath);
PrintDocument pd = new PrintDocument();
pd.DocumentName = fileInfo.Name;
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(imageFilePath);
PrintPageEventArgs arguments = args;
System.Drawing.Rectangle m = new System.Drawing.Rectangle()
{
Y = 0,
X = 0,
Location = new System.Drawing.Point(0, 0),
Height = args.MarginBounds.Height,
Size = args.MarginBounds.Size,
Width = args.MarginBounds.Width
};
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height)
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
args.Graphics.DrawImage(i, m);
};
pd.Print();
So is it possible to print a .docx silently and being able to choose the tray of the printer ?
Did anyone face the same issue. Any help in this regard. Thanks in advance.
I did something very similar to this myself but I never looked up the documentation if you could choose the tray. I believe these are set on the print server itself (if you are using one) and would be able to reference those if your application has the access rights.
string PrinterName = #"\\Server\nameOfThePrinter";
ProcessStartInfo printProcessInfo = new ProcessStartInfo()
{
Verb = "PrintTo",
CreateNoWindow = true,
FileName = pdfFileName,
Arguments = "\"" + PrinterName + "\"",
WindowStyle = ProcessWindowStyle.Hidden
};
Process printProcess = new Process();
printProcess.StartInfo = printProcessInfo;
printProcess.Start();
printProcess.WaitForInputIdle();
printProcess.WaitForExit(10000);
if (printProcess.HasExited)
{
}else
{
printProcess.Kill();
}
return true;
Also, you may want to investigate this article here https://www.codeproject.com/Tips/598424/How-to-Silently-Print-PDFs-using-Adobe-Reader-and
Cheers!
I found a solution I couldn't print a .docx silently so I converted it as a .png image before.
Link to convert .docx to .png
Here is the code to print the image :
PrinterSettings settings = new PrinterSettings();
string PrinterName = settings.PrinterName;
//set paper size
PaperSize oPS = new PaperSize
{
RawKind = (int)PaperKind.A4
};
//choose the tray here
PaperSource oPSource = new PaperSource
{
RawKind = (int)PaperSourceKind.Upper
};
PrintDocument printDoc = new PrintDocument
{
PrinterSettings = settings,
};
//set printer name here it's the default printer
printDoc.PrinterSettings.PrinterName = PrinterName;
printDoc.DefaultPageSettings.PaperSize = oPS;
printDoc.DefaultPageSettings.PaperSource = oPSource;
printDoc.PrintPage += new PrintPageEventHandler((sender, args) =>
{
System.Drawing.Image img = System.Drawing.Image.FromFile(imageFilePath);
int printHeight = (int)printDoc.DefaultPageSettings.PrintableArea.Height;
int printWidth = (int)printDoc.DefaultPageSettings.PrintableArea.Width;
int leftMargin = 0;
int rightMargin = 0;
args.Graphics.DrawImage(img, new System.Drawing.Rectangle(leftMargin, rightMargin, printWidth, printHeight));
});
printDoc.Print();
printDoc.Dispose();

Spire.PDF prints pdf only in grayscale

I am using the free version of Spire.PDF to print a local pdf file but the print is in grayscale even though the pdf file is in color. Here is my code
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(fileName);
doc.ColorSpace = PdfColorSpace.RGB;
PrintDialog dialogPrint = new PrintDialog();
dialogPrint.AllowPrintToFile = true;
dialogPrint.AllowSomePages = true;
dialogPrint.PrinterSettings.MinimumPage = 1;
dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
dialogPrint.PrinterSettings.FromPage = 1;
dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;
if (dialogPrint.ShowDialog() == DialogResult.OK)
{
//Set the pagenumber which you choose as the start page to print
doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
//Set the pagenumber which you choose as the final page to print
doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
//Set the name of the printer which is to print the PDF
doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;
PrintDocument printDoc = doc.PrintDocument;
printDoc.DefaultPageSettings.Color = true;
dialogPrint.Document = printDoc;
printDoc.Print();
}
I have checked dialogPrint.PrinterSettings.SupportsColor returns true

WPF: The font will not change on a printed FlowDocument

I am trying to print the contents of a rich-text box. I do that in the following way:
Obtain a TextRange from the FlowDocument.
Create a new FlowDocument with a smaller font using the TextRange.
Send this new FlowDocument to the printer.
My problem, is that the font doesn't seem to change. I would like it to go down to size 8. Instead, it remains at a fixed size. Here is my code:
private void button_Print_Click(object sender, RoutedEventArgs e)
{
IDocumentPaginatorSource ps = null;
FlowDocument fd = new FlowDocument();
PrintDialog pd = new PrintDialog();
Paragraph pg = new Paragraph();
Style style = new Style(typeof(Paragraph));
Run r = null;
string text = string.Empty;
// get the text
text = new TextRange(
this.richTextBox_Info.Document.ContentStart,
this.richTextBox_Info.Document.ContentEnd).Text;
// configure the style of the flow document
style.Setters.Add(new Setter(Block.MarginProperty, new Thickness(0)));
fd.Resources.Add(typeof(Paragraph), style);
// style the paragraph
pg.LineHeight = 0;
pg.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
pg.FontFamily = new FontFamily("Courier New");
pg.TextAlignment = TextAlignment.Left;
pg.FontSize = 8;
// create the paragraph
r = new Run(text);
r.FontFamily = new FontFamily("Courier New");
r.FontSize = 8;
pg.Inlines.Add(r);
// add the paragraph to the document
fd.Blocks.Add(pg);
ps = fd;
// format the page
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;
// print the document
if (pd.ShowDialog().Value == true)
{
pd.PrintDocument(ps.DocumentPaginator, "Information Box");
}
}
I would like to add that, changing the font works just fine for the flow-document when it is inside of the rich-text box. However, when I am doing it programmatically (as shown above) I run into problems.
I try your code and found when I remove this line and then change the r.FontSize to 50, it seems work.
pg.LineHeight = 0;

WPF FlowDocument printing only to small area

I am printing plain text in WPF by using a FlowDocument, FlowDocumentPaginator and PrintDialog. My approach is based on this article and is implemented as follows:
var printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
var flowDocument = new FlowDocument();
var paragraph = new Paragraph();
paragraph.FontFamily = new FontFamily("Courier New");
paragraph.FontSize = 10;
paragraph.Margin = new Thickness(0);
paragraph.Inlines.Add(new Run(this.textToPrint));
flowDocument.FontSize = 10;
flowDocument.Blocks.Add(paragraph);
var paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
printDialog.PrintDocument(paginator, "Chit");
}
This works good for printing stuff with narrow width. But when I try to print a long string, it all gets stuffed in a small area:
I checked dimensions in the print dialog's PrintTicket and in the paginator, and they seem to be okay:
So, what is causing this problem and how can I fix it?
This is some code I use
flowDocument.PagePadding = new Thickness(standardThickness);
flowDocument.ColumnGap = 0;
flowDocument.ColumnWidth = printDialog.PrintableAreaWidth;
You need to tell the flowdocument it is one column and tell the flowdocument the width of the printer.

Categories

Resources