I am currently opening the PrintDialog where user can select printer setting and do the printing.
At the moment I am using below code
var files = Directory.GetFiles(sourceFolder);
foreach (var file in files)
{
var pdoc = new PrintDocument();
var pdi = new PrintDialog
{
Document = pdoc
};
if (pdi.ShowDialog() == DialogResult.OK)
{
pdoc.DocumentName = file;
pdoc.Print();
}
}
Is there a way to send all the files to the printer by using PrintDialog once. So the user can select the folder and set one print setting for all the documents inside the folder and then do the printing?
Try this sample code:
var files = Directory.GetFiles(sourceFolder);
if (files.Length != 0)
{
using (var pdoc = new PrintDocument())
using (var pdi = new PrintDialog { Document = pdoc, UseEXDialog = true })
{
if (pdi.ShowDialog() == DialogResult.OK)
{
pdoc.PrinterSettings = pdi.PrinterSettings;
// ************************************
// Pay attention to the following line:
pdoc.PrintPage += pd_PrintPage;
// ************************************
foreach (var file in files)
{
pdoc.DocumentName = file;
pdoc.Print();
}
}
}
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
string file = ((PrintDocument)sender).DocumentName; // Current file name
// Do printing of the Document
...
}
Related
I'm using Visual Studio with Selenium to build an application that goes to a web page and finds if the contents of an array are on the page. I'm running into an issue with searching the page for the array contents.. Right now it finds nothing, so it clicks to go to the next page when it shouldn't.
The array comes from a CSV file I'm loading in and it needs to search the page for a match of any of the records from the CSV file and stops.
Here is what I have so far:
OpenFileDialog ofd = new OpenFileDialog();
private double timeOut;
private void bttnImportBrowse_Click(object sender, EventArgs e)
{
ofd.Filter = "CSV|*.csv";
var fileInputs = new List<string>();
if (ofd.ShowDialog() == DialogResult.OK)
{
String chosenFile = ofd.FileName;
String safeFileName = ofd.SafeFileName;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(chosenFile))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
fileInputs.Add(line);
//Console.Write(string.Join(" ", fileInputs));
var driver = new ChromeDriver(#"C:\Users\andre_000\Documents\Visual Studio 2015\Projects\MyProject\");
driver.Navigate().GoToUrl("MySite");
var WebDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.XPath("/html/body/a[2]"))));
while (1==1) {
try
{
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
break;
}
catch (NoSuchElementException n)
{
var nextBttn = driver.FindElementByXPath("/html/body/a[2]");
nextBttn.Click();
}
}
}
}
}
catch (Exception entry)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(entry.Message);
}
}
}
Sorry i would have left a comment but am not allowed to yet. Do you have the CSV file?
I believe you are trying to find the Link text incorrectly.
Currently calling ToString() on the list
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
should probably be
var result = driver.FindElement(By.LinkText(line));
I am developing an application which is work as print agent without getting user interaction. In there, I have to consider about below conditions.
Download file shouldn't be access for user.
file sould be deleted after print it.
The download document could be either Image/PDF or word.docx
First downloaded file should be print first.
So far I able to complete as follow.
- watcher method created to catch up new download file.
public void catchDocuments()
{
if (!string.IsNullOrEmpty(Program.docDirectory))
{
file_watcher = new FileSystemWatcher();
file_watcher.Path = Program.docDirectory;
file_watcher.EnableRaisingEvents = true;
file_watcher.Created += new FileSystemEventHandler(OnChanged);
}
}
when new file came, it will fire Onchange event and print document.
string extension = Path.GetExtension(args.FullPath);
if (extension.Equals(#".png") || extension.Equals(#".jpeg") || extension.Equals(#".jpg"))
{
docCtrl.imageToByteArray(nFile);
docCtrl.printImage();
}
else if (extension.Equals(#".pdf"))
{
docCtrl.PrintPDF(nFile);
}
But My problem is, When another files download before complete print process of downloaded file, Application will not work properly.
I used print option as follow.
//For Image printing
public void printImage()
{
System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
pdi.PrinterSettings.PrinterName;
pd.Print();
}
//For PDF Printing
public void PrintPDF(string path)
{
PrintDialog pdf = new PrintDialog();
Process p = new Process();
pdf.AllowSelection = true;
pdf.AllowSomePages = true;
p.EnableRaisingEvents = true; //Important line of code
p.StartInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
Verb = "print",
FileName = path,
};
p.Start();
p.WaitForExit();
p.Close();
}
how could I overcome this issue. I'll be really appreciate your good thoughts.
Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}
I have a ListBox which I put some files, if the file is not AVI I automatically converts it but I want when the files converting message will write on a label that the files are now converted to another format, what happens to me now is only when the program has finished converting them its update the label and not in the process
after all the fixes:
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
btnPlay.IsEnabled = false;
Stream checkStream = null;
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.Title = "Please Select Source File";
if ((bool)openFileDialog.ShowDialog())
{
if ((checkStream = openFileDialog.OpenFile()) != null)
{
foreach (string file in openFileDialog.FileNames)
{
try
{
FileInfo fileInfo = new FileInfo(file);
listBoxFiles.Items.Add(file);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
for (int i = 0; i < listBoxFiles.Items.Count; i++)
{
string path = (string)listBoxFiles.Items[i];
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Extension != ".AVI")
{
listToRemove.Add(path);
}
}
(new System.Threading.Thread(ProcessAviFiles)).Start();
foreach (string file in listToRemove) //remove all non .AVI files from listbox
{
listBoxFiles.Items.Remove(file);
}
}
}
else
{
}
if (listBoxFiles.Items.Count != 0)
{
btnClear.IsEnabled = true;
btnPlay.IsEnabled = true;
}
listToRemove.RemoveRange(0, listToRemove.Count);
}
function:
public void ProcessAviFiles()
{
if (listToRemove.Count == 0)
{
return;
}
lblStatus2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => { lblStatus2.Content = "Convert file to .AVI..."; }));
foreach (String file in listToRemove)
{
FileInfo fileInfo = new FileInfo(file);
editpcap = new EditCap(fileInfo);
String newFileName = editpcap._newFileName;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
{
listBoxFiles.Items.Add(editpcap._newFileName);
}));
}
lblStatus2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(
() =>
{
lblStatus2.Content = "Select adapter and packet file, Click play button to start.";
btnClear.IsEnabled = true;
}));
}
The label is not updating because the main UI thread is busy doing other things.
Looking to your code, it seems that you are running the AVI file conversion business inside your main UI thread. You should run this time consuming task in a separate thread to make sure your UI stays responsive.
Below is a fix to your problem, replace your foreach (String file in listToRemove){} by:
Action aviConversion = new Action(() => {
if(listToRemove.Count == 0) return; // nothing to do
lblStatus2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() => { lblStatus2.Content = "Convert file to .AVI...";});
);
foreach (String file in listToRemove){
FileInfo fileInfo = new FileInfo(file);
editpcap = new (classes who convert the files)(fileInfo);
String newFileName = editpcap._newFileName;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() => {
listBoxFiles.Items.Add(newFileName);
}));
}
lblStatus2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() => { lblStatus2.Content = "AVI file conversion finished...";});
});
// Run this action in a separate thread...
Task.Factory.StartNew(action, "beta");
EDIT Using Thread instead of Task (OP can't use Task)
private void ProcessAviFiles(){
if(listToRemove.Count == 0) return; // nothing to do
lblStatus2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() => { lblStatus2.Content = "Convert file to .AVI...";});
);
foreach (String file in listToRemove){
FileInfo fileInfo = new FileInfo(file);
editpcap = new (classes who convert the files)(fileInfo);
String newFileName = editpcap._newFileName;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() => {
listBoxFiles.Items.Add(newFileName);
}));
}
lblStatus2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(() => { lblStatus2.Content = "AVI file conversion finished...";});
}
replace your foreach (String file in listToRemove){} by:
(new System.Threading.Thread(ProcessAviFiles)).Start();
Use BackgroundWorker for the main task and dispatcher for UI updates.
backgroundWorker1.DoWork += worker_DoWork;
backgroundWorker1.RunWorkerCompleted += worker_RunWorkerCompleted;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.ProgressChanged +=new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
In my main Form I have a method called SavePDFDocument():
private void SavePDFDocument()
{
PDFWrapper pdfWrapper = new PDFWrapper();
pdfWrapper.CreatePDF(horizontalPictureScroller1.GetPictures(), "pdfDocument.pdf");
}
As you can see, right now I'm manually typing in a name for the file. I'd like to ask the user to choose where to save it and what name to give it.
This is the CreatePDF() method I'm using above:
public void CreatePDF(List<System.Drawing.Image> images, string filename)
{
if (images.Count >= 1)
{
Document document = new Document(PageSize.LETTER);
try
{
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
// step 3: we open the document
document.Open();
foreach (var image in images)
{
iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
if (pic.Height > pic.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / pic.Height;
pic.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 540 / pic.Width;
pic.ScalePercent(percentage * 100);
}
pic.Border = iTextSharp.text.Rectangle.BOX;
pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
pic.BorderWidth = 3f;
document.Add(pic);
document.NewPage();
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// step 5: we close the document
document.Close();
}
}
Any suggestions?
Did you take a look at SaveFileDialog?
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
I believe this page describes what you are looking for:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // 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;
}
A useful link: How to: Save Files Using the SaveFileDialog Component