How to print .docx silently with c# - 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();

Related

How to print all pages in CSV file to 1 pdf file when user selects "Microsoft print to pdf"

What: I have a program which prints an RDLC report page using a CSV file when using a printer.
Issue: When the user prints to pdf, it saves each page 1 by 1 which is not efficent when there are 1000 pages to print.
Intent: When user selects specifically microsoft print to pdf, all files will print to 1 single pdf file. However other printers will print as usual.
Current situation: When printing to microsoft print to pdf, it prints to 1 file at a time, so 1000 records = 1000 files.
Below is the source code for the printer class and main class where the printer class is called
LocalReportExtensioncs.cs file
this file runs for every page so if there is 1000 pages to print, it will run 1000 times.
public static void PrintToPrinter(this LocalReport report)
{
var pageSettings = new PageSettings();
pageSettings.Color = false;
pageSettings.PaperSize = report.GetDefaultPageSettings().PaperSize;
pageSettings.Landscape = report.GetDefaultPageSettings().IsLandscape;
pageSettings.Margins = report.GetDefaultPageSettings().Margins;
pageSettings.Landscape = true;
Print(report, pageSettings);
}
public static void Print(this LocalReport report, PageSettings pageSettings)
{
string deviceInfo =
$#"<DeviceInfo>
<OutputFormat>EMF</OutputFormat>
<PageWidth>{pageSettings.PaperSize.Width * 100}in</PageWidth>
<PageHeight>{pageSettings.PaperSize.Height * 100}in</PageHeight>
<MarginTop>{pageSettings.Margins.Top * 100}in</MarginTop>
<MarginLeft>{pageSettings.Margins.Left * 100}in</MarginLeft>
<MarginRight>{pageSettings.Margins.Right * 100}in</MarginRight>
<MarginBottom>{pageSettings.Margins.Bottom * 100}in</MarginBottom>
</DeviceInfo>";
Warning[] warnings;
var streams = new List<Stream>();
var currentPageIndex = 0;
report.Render("Image", deviceInfo,
(name, fileNameExtension, encoding, mimeType, willSeek) =>
{
var stream = new MemoryStream();
streams.Add(stream);
return stream;
}, out warnings);
foreach (Stream stream in streams)
stream.Position = 0;
if (streams.Equals(null) || streams.Count == 0)
throw new Exception("Error: no stream to print.");
var printDocument = new PrintDocument();
printDocument.DocumentName = "default";
var printerController = new StandardPrintController();
printDocument.PrintController = printerController;
printDocument.DefaultPageSettings.Color = false;
printDocument.DefaultPageSettings = pageSettings;
DialogResult result = DialogResult.Retry;
while (!printDocument.PrinterSettings.IsValid)
{
result = MessageBox.Show("Error, Default printer hasnt been selected", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
if (result == DialogResult.Cancel)
{
Environment.Exit(0);
}
}
printDocument.PrintPage += (sender, e) =>
{
Metafile pageImage = new Metafile(streams[currentPageIndex]);
Rectangle adjustedRect = new Rectangle(
e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
e.PageBounds.Width,
e.PageBounds.Height);
e.Graphics.FillRectangle(Brushes.White, adjustedRect);
e.Graphics.DrawImage(pageImage, adjustedRect);
currentPageIndex++;
e.HasMorePages = (currentPageIndex < streams.Count);
e.Graphics.DrawRectangle(Pens.Red, adjustedRect);
};
printDocument.EndPrint += (Sender, e) =>
{
if (streams != null)
{
foreach (Stream stream in streams)
stream.Close();
streams = null;
}
};
printDocument.PrinterSettings.PrinterName = Properties.Settings.Default.PrinterName;
printDocument.Print();
}
}
In main.cs file where the RDLC report data is inserted,
localReport = AddToLocalReport(localReport);
localReport.ReportPath = Application.StartupPath + "\\RDLCreport.rdlc";
for (int i = 1; i < printCounter + 1; i++)
{
if (Properties.Settings.Default.canPrint == true)
{
localReport.PrintToPrinter();
}
}

Can't print jpg with Aspose.Pdf

I want to load in a JPEG file and print it with Aspose.Pdf in C# (.net Framework 4.8). The code I currently have is:
public void PrintImage(string fileToPrint, string printerName, string jobName)
{
System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileToPrint);
int h = srcImage.Height;
int w = srcImage.Width;
var doc = new Document();
var page = doc.Pages.Add();
var image = new Image();
image.File = (fileToPrint);
page.PageInfo.Height = (h);
page.PageInfo.Width = (w);
page.PageInfo.Margin.Bottom = (0);
page.PageInfo.Margin.Top = (0);
page.PageInfo.Margin.Right = (0);
page.PageInfo.Margin.Left = (0);
page.Paragraphs.Add(image);
var viewer = new PdfViewer(doc);
PrintUsingViewer(viewer, printerName, jobName);
}
private static void PrintUsingViewer(PdfViewer viewer, string printerName, string jobName)
{
viewer.AutoResize = true; // Print the file with adjusted size
viewer.AutoRotate = true; // Print the file with adjusted rotation
viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
var ps = new System.Drawing.Printing.PrinterSettings();
var pgs = new System.Drawing.Printing.PageSettings();
ps.PrinterName = printerName;
viewer.PrinterJobName = jobName;
viewer.PrintDocumentWithSettings(pgs, ps);
viewer.Close();
}
When I save the document instead of printing and look at it, it seems fine (the image is added). However, when trying to print the image it is not printed and the page is just blank..
I would like to print without first saving the document as a PDF and then trying to print that saved PDF. Does anyone see what I am doing wrong?
The solution was adding this line of code
doc.ProcessParagraphs();
right after this line:
page.Paragraphs.Add(image);
So the code now becomes
public void PrintImage(string fileToPrint, string printerName, string jobName)
{
System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileToPrint);
int h = srcImage.Height;
int w = srcImage.Width;
var doc = new Document();
var page = doc.Pages.Add();
var image = new Image();
image.File = (fileToPrint);
page.PageInfo.Height = (h);
page.PageInfo.Width = (w);
page.PageInfo.Margin.Bottom = (0);
page.PageInfo.Margin.Top = (0);
page.PageInfo.Margin.Right = (0);
page.PageInfo.Margin.Left = (0);
page.Paragraphs.Add(image);
doc.ProcessParagraphs();
var viewer = new PdfViewer(doc);
PrintUsingViewer(viewer, printerName, jobName);
}
private static void PrintUsingViewer(PdfViewer viewer, string printerName, string jobName)
{
viewer.AutoResize = true; // Print the file with adjusted size
viewer.AutoRotate = true; // Print the file with adjusted rotation
viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
var ps = new System.Drawing.Printing.PrinterSettings();
var pgs = new System.Drawing.Printing.PageSettings();
ps.PrinterName = printerName;
viewer.PrinterJobName = jobName;
viewer.PrintDocumentWithSettings(pgs, ps);
viewer.Close();
}
Now the image is printed correctly!

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

process always prints document by default printer

I have a problem with selecting printer to print my document.
My code is :
var filename = #"C:\Users\I\Desktop\test.doc";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings =new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
Process objP = new Process();
objP.StartInfo.FileName = filename;
objP.StartInfo.WindowStyle =
ProcessWindowStyle.Hidden; //Hide the window.
objP.StartInfo.Verb ="print";
objP.StartInfo.Arguments ="/p /h \"" + filename + "\" \"" + pd.PrinterSettings.PrinterName + "\"";
objP.StartInfo.CreateNoWindow = false;
//true;//!! Don't create a Window.
objP.Start();
//!! Start the process !!//
objP.CloseMainWindow();
}
and whatever I choose, process always will use default printer, no matter what value of pd.PrinterSettings.PrinterName is.
What's wrong with my code?
You probably want to use "PrintTo" instead of "print" for the verb. You already set objP.FileName to the filename so there's no need to get complicated in the arguments. Pass the printer name alone there.
var filename = #"C:\Users\I\Desktop\test.doc";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings =new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
Process objP = new Process();
objP.StartInfo.FileName = filename;
objP.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //Hide the window.
objP.StartInfo.Verb ="PrintTo";
objP.StartInfo.Arguments = pd.PrinterSettings.PrinterName;
objP.StartInfo.CreateNoWindow = false;
//true;//!! Don't create a Window.
objP.Start();
//!! Start the process !!//
objP.CloseMainWindow();
}
Try changing pd.PrinterSettings =new PrinterSettings(); to read something like this:
pd.PrinterSettings =new System.Drawing.Printing.PrinterSettings;
By default when you create an instance of printer settings it returns the default printer name just an fyi... you can then try something like this
//sudu code
foreach(string strPrinter in PrinterSettings.InstalledPrinters)
{
// or unless you know the name of the printer then skip this and assign it to the code above
}

Ignored Paper Size in PrintDialog/XPS Document Writer

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");
}
}

Categories

Resources