Adobe Reader Parameters - c#

Im trying to save a pdf file as a new pdf but printting it (required), Im using Adobe Acrobat to do that cause it brings me the option to introduce parameters.
The thing is : I need to do it silently (Not a single Window can been saw). So I need to set a printer, a path to my file and an output destination.
As I said I need to "print it" as a new pdf so I'm using Microsoft Print to PDF to do that (I don't know if it is the better option).
Thank you so much!
string file = name;
string pathFile = "C:\\DfPrinter\\" + name;
ProcessStartInfo infoPrintPdf = new ProcessStartInfo();
string printerName = "Microsoft Print to PDF";
infoPrintPdf.FileName = "C:\\Program Files (x86)\\Adobe\\Acrobat Reader DC\\Reader\\AcroRd32.exe";
infoPrintPdf.Arguments = string.Format("/t" + " '" + pathFile + "'" +"' " +"'"+printerName+"'");
infoPrintPdf.CreateNoWindow = true;
infoPrintPdf.UseShellExecute = false;
infoPrintPdf.WindowStyle = ProcessWindowStyle.Hidden;
Process printPdf = new Process();
printPdf.StartInfo = infoPrintPdf;
printPdf.Start();
System.Threading.Thread.Sleep(10000);
if (!printPdf.CloseMainWindow())
printPdf.Kill(); printPdf.WaitForExit();

I don't think Acrobat Reader can print silently, but you could consider using the Win2PDF "printpdf" command line:
win2pdfd.exe printpdf "filename.pdf" Win2PDF "newfilename.pdf"
This prints the PDF silently to a new PDF specified by "newfilename" by using the Win2PDF printer.

Related

How to print PDF documents or other printable files in UWP? [duplicate]

Here's the basic premise:
My user clicks some gizmos and a PDF file is spit out to his desktop. Is there some way for me to send this file to the printer queue and have it print to the locally connected printer?
string filePath = "filepathisalreadysethere";
SendToPrinter(filePath); //Something like this?
He will do this process many times. For each student in a classroom he has to print a small report card. So I generate a PDF for each student, and I'd like to automate the printing process instead of having the user generated pdf, print, generate pdf, print, generate pdf, print.
Any suggestions on how to approach this? I'm running on Windows XP with Windows Forms .NET 4.
I've found this StackOverflow question where the accepted answer suggests:
Once you have created your files, you
can print them via a command line (you
can using the Command class found in
the System.Diagnostics namespace for
that)
How would I accomplish this?
Adding a new answer to this as the question of printing PDF's in .net has been around for a long time and most of the answers pre-date the Google Pdfium library, which now has a .net wrapper. For me I was researching this problem myself and kept coming up blank, trying to do hacky solutions like spawning Acrobat or other PDF readers, or running into commercial libraries that are expensive and have not very compatible licensing terms. But the Google Pdfium library and the PdfiumViewer .net wrapper are Open Source so are a great solution for a lot of developers, myself included. PdfiumViewer is licensed under the Apache 2.0 license.
You can get the NuGet package here:
https://www.nuget.org/packages/PdfiumViewer/
and you can find the source code here:
https://github.com/pvginkel/PdfiumViewer
Here is some simple code that will silently print any number of copies of a PDF file from it's filename. You can load PDF's from a stream also (which is how we normally do it), and you can easily figure that out looking at the code or examples. There is also a WinForm PDF file view so you can also render the PDF files into a view or do print preview on them. For us I simply needed a way to silently print the PDF file to a specific printer on demand.
public bool PrintPDF(
string printer,
string paperName,
string filename,
int copies)
{
try {
// Create the printer settings for our printer
var printerSettings = new PrinterSettings {
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings) {
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes) {
if (paperSize.PaperName == paperName) {
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfDocument.Load(filename)) {
using (var printDocument = document.CreatePrintDocument()) {
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
} catch {
return false;
}
}
You can tell Acrobat Reader to print the file using (as someone's already mentioned here) the 'print' verb. You will need to close Acrobat Reader programmatically after that, too:
private void SendToPrinter()
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = #"c:\output.pdf";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(3000);
if (false == p.CloseMainWindow())
p.Kill();
}
This opens Acrobat Reader and tells it to send the PDF to the default printer, and then shuts down Acrobat after three seconds.
If you are willing to ship other products with your application then you could use GhostScript (free), or a command-line PDF printer such as http://www.commandlinepdf.com/ (commercial).
Note: the sample code opens the PDF in the application current registered to print PDFs, which is the Adobe Acrobat Reader on most people's machines. However, it is possible that they use a different PDF viewer such as Foxit (http://www.foxitsoftware.com/pdf/reader/). The sample code should still work, though.
I know the tag says Windows Forms... but, if anyone is interested in a WPF application method, System.Printing works like a charm.
var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(file, 0, file.Length);
}
Just remember to include System.Printing reference, if it's not already included.
Now, this method does not play well with ASP.NET or Windows Service. It should not be used with Windows Forms, as it has System.Drawing.Printing. I don't have a single issue with my PDF printing using the above code.
I should mention, however, that if your printer does not support Direct Print for PDF file format, you're out of luck with this method.
The following code snippet is an adaptation of Kendall Bennett's code for printing pdf files using the PdfiumViewer library. The main difference is that a Stream is used rather than a file.
public bool PrintPDF(
string printer,
string paperName,
int copies, Stream stream)
{
try
{
// Create the printer settings for our printer
var printerSettings = new PrinterSettings
{
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == paperName)
{
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfiumViewer.PdfDocument.Load(stream))
{
using (var printDocument = document.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
}
catch (System.Exception e)
{
return false;
}
}
In my case I am generating the PDF file using a library called PdfSharp and then saving the document to a Stream like so:
PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
pdf.AddPage();
MemoryStream stream = new MemoryStream();
pdf.Save(stream);
MemoryStream stream2 = new MemoryStream(stream.ToArray());
One thing that I want to point out that might be helpful to other developers is that I had to install the 32 bit version of the Pdfium native DLL in order for the printing to work even though I am running Windows 10 64 bit. I installed the following two NuGet packages using the NuGet package manager in Visual Studio:
PdfiumViewer
PdfiumViewer.Native.x86.v8-xfa
The easy way:
var pi=new ProcessStartInfo("C:\file.docx");
pi.UseShellExecute = true;
pi.Verb = "print";
var process = System.Diagnostics.Process.Start(pi);
This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.
private void SendToPrinter()
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = #"c:\output.pdf";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
long ticks = -1;
while (ticks != p.TotalProcessorTime.Ticks)
{
ticks = p.TotalProcessorTime.Ticks;
Thread.Sleep(1000);
}
if (false == p.CloseMainWindow())
p.Kill();
}
System.Diagnostics.Process.Start can be used to print a document. Set UseShellExecute to True and set the Verb to "print".
You can try with GhostScript like in this post:
How to print PDF on default network printer using GhostScript (gswin32c.exe) shell command
I know Edwin answered it above but his only prints one document. I use this code to print all files from a given directory.
public void PrintAllFiles()
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.Verb = "print";
System.Diagnostics.Process p = new System.Diagnostics.Process();
//Load Files in Selected Folder
string[] allFiles = System.IO.Directory.GetFiles(Directory);
foreach (string file in allFiles)
{
info.FileName = #file;
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo = info;
p.Start();
}
//p.Kill(); Can Create A Kill Statement Here... but I found I don't need one
MessageBox.Show("Print Complete");
}
It essentually cycles through each file in the given directory variable Directory - > for me it was #"C:\Users\Owner\Documents\SalesVaultTesting\" and prints off those files to your default printer.
this is a late answer, but you could also use the File.Copy method of the System.IO namespace top send a file to the printer:
System.IO.File.Copy(filename, printerName);
This works fine
You can use the DevExpress PdfDocumentProcessor.Print(PdfPrinterSettings) Method.
public void Print(string pdfFilePath)
{
if (!File.Exists(pdfFilePath))
throw new FileNotFoundException("No such file exists!", pdfFilePath);
// Create a Pdf Document Processor instance and load a PDF into it.
PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
documentProcessor.LoadDocument(pdfFilePath);
if (documentProcessor != null)
{
PrinterSettings settings = new PrinterSettings();
//var paperSizes = settings.PaperSizes.Cast<PaperSize>().ToList();
//PaperSize sizeCustom = paperSizes.FirstOrDefault<PaperSize>(size => size.Kind == PaperKind.Custom); // finding paper size
settings.DefaultPageSettings.PaperSize = new PaperSize("Label", 400, 600);
// Print pdf
documentProcessor.Print(settings);
}
}
public static void PrintFileToDefaultPrinter(string FilePath)
{
try
{
var file = File.ReadAllBytes(FilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(file, 0, file.Length);
}
}
catch (Exception)
{
throw;
}
}

Printing html file from windows application is not working when we set default browser as chrome (other than IE)

I have to print html file when user clicks on print button and it is working fine (prompts print dialog) when I set default browser as IE.
If I change default browser to chrome or firefox other than IE, the code does not prompting print dialog instead it just opens html file in the browser. Can you please let me know what configuration I have missed in the below code?
string TempFile = #"D:\test.html";
ProcessStartInfo Params = new ProcessStartInfo();
Params.FileName = "iexplore.exe";
Params.Arguments = TempFile;
Params.UseShellExecute = false;
Params.Verb = "print";
Params.WindowStyle = ProcessWindowStyle.Hidden;
Params.CreateNoWindow = true;
Process.Start(Params);
Finally I got the solution for this issue. The below code works like a charm!!
using (Process exeProcess = new Process())
{
string TempFile = #"D:\test.html";
exeProcess.StartInfo.FileName = "rundll32";
exeProcess.StartInfo.Arguments = #"system32\mshtml.dll,PrintHTML """ + TempFile + #"""";
exeProcess.StartInfo.UseShellExecute = true;
exeProcess.Start();
}

C# - Printing files regardles of type to printer

currently I am working with application that should silently print files regardless of their type to specific printer.
I have method to print:
public static void SendToPrinter(string filePath, string fileName, string printerName)
{
ProcessStartInfo info = new ProcessStartInfo(filePath);
info.Arguments = "\"" + printerName + "\"";
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
info.Verb = "PrintTo";
Process.Start(info);
}
and this works almost perfect.
I do not know how to force the printer to leave the original image size.
Currently the image is scaled to the page size.
Have you met someone with a similar problem?
Shell only sends print command to printer. There is no printer settings available. Instead try to use Print document. It has various printer settings.

How to save a PDF using Graphics.DrawString in C#?

I have the Graphics.DrawString method for Print Preview.
Now I would like to use the same code to save it as a PDF. I have a Form, I have created a printprewiew and I would like to save as it is in printPrview to pdf.
Is it posible to do this?
I have a solution this may help you, but it requires to download and install "CutePDF Writer". CutePDF Writer is free software. You can download it from there official website.
PrintDialog pDia = New PrintDialog()
PrinterSettings ps = New PrinterSettings()
pDia.Document = PrintDocument1
pDia.Document.DocumentName = "Your File Name"
ps.PrinterName = item.ToString()
ps.PrintToFile = False
//Create folder inside Bin folder to save PDFs
String strReportBackupPath = "C:\\"
String strFilePath = strReportBackupPath & "\\" & pDia.Document.DocumentName & ".pdf"
//To avoid the replace dialog of cutePDF - To save new file if have same name
ps.PrintFileName = strFilePath
PrintDocument1.PrinterSettings = ps
PrintDocument1.Print()
but it will show you save as dialog to save the file to pdf.

Using Acrobat Plugin to print multiple PDF's (axAcroPDF1)

I've got a windows app where I want to send to printer a list of PDF's in a listbox.
Stepping through the code below, I can see that *axAcroPDF1.LoadFile(s) is loading each file in my application, but Acrobat only seems to print the last item in the lbPDFList listbox to the printer (eg. if there is 4 PDF's to print, it will always only print the last PDF)?
int iListCounter = lbPDFList.Items.Count;
for (int i=0; i < iListCounter; i++)
{
String s = null;
lbPDFList.SetSelected(i,true);
s = lbPDFList.SelectedItem.ToString();
axAcroPDF1.LoadFile(s);
axAcroPDF1.Show();
axAcroPDF1.printAllFit(true);
}
Is this a threading issue?
The answer was simple! Ignore the axAcroPDF object and just print using the windows print function (use the code below inside a loop to print each PDF):
// start a new cmd process
Process objP = new Process();
objP.StartInfo.FileName = strFilePath;
objP.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //Hide the window.
//!! Since the file name involves a nonexecutable file(.pdf file), including a verb to specify what action to take on the file.
//The action in our case is to "Print" a file in a selected printer.
//!! Print the document in the printer selected in the PrintDialog !!//
objP.StartInfo.Verb = "printto";
objP.StartInfo.Arguments = "/p /h \"" + strFilePath + "\" \"" + pd.PrinterSettings.PrinterName + " \"";//pd.PrinterSettings.PrinterName;
objP.StartInfo.CreateNoWindow = true; //!! Don't create a Window.
objP.Start(); //!! Start the process !!//
objP.CloseMainWindow();

Categories

Resources