I want to print out a document using C#. I have two buttons. btnUpload uploads or selects a word file. btnPrinthave to send uploaded file to a printer. How can I do this? Now using:
private void btnUpload_Click(object sender, EventArgs e)
{
string fileName;
// Show the dialog and get result.
OpenFileDialog ofd = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
fileName = ofd.FileName;
var application = new Microsoft.Office.Interop.Word.Application();
//var document = application.Documents.Open(#"D:\ICT.docx");
var document = application.Documents.Open(#fileName);
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "fileName";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
//Call ShowDialog
if (printDlg.ShowDialog() == DialogResult.OK)
printDoc.Print();
}
you need to hadle PrintPage event
Try This:
String content="";
private void btnUpload_Click(object sender, EventArgs e)
{
string fileName;
// Show the dialog and get result.
OpenFileDialog ofd = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
fileName = ofd.FileName;
var application = new Microsoft.Office.Interop.Word.Application();
//var document = application.Documents.Open(#"D:\ICT.docx");
//read all text into content
content=System.IO.File.ReadAllText(fileName);
//var document = application.Documents.Open(#fileName);
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "fileName";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
//Call ShowDialog
if (printDlg.ShowDialog() == DialogResult.OK)
{
printDoc.PrintPage += new PrintPageEventHandler(pd_PrintPage);
printDoc.Print();
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.Graphics.DrawString(content,printFont , Brushes.Black,
ev.MarginBounds.Left, 0, new StringFormat());
}
Related
I am trying to save some selected file in a folder(images) inside my application
I am able to get the file using following code:
private void button1_Click(object sender, EventArgs e)
{
string imagelocation = "";
OpenFileDialog dialog = new OpenFileDialog();
if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
textBox2.Text = dialog.FileName;
}
}
For saving the file I got in textBox2, I tried following code. But with following code I have to also select the path where I want to save the file.
What If I want to (set my path permanently to 'images' folder as shown in pic) for saving?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
if(f.ShowDialog() == DialogResult.OK)
{
using(Stream s = File.Open(f.FileName, FileMode.CreateNew))
using(StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox2.Text);
}
}
}
2 Approaches to Solve this problem
First Approach: (Browser the File and click Save, to automatically save the selected file to Image Directory)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
using (Stream s = File.Open(imageDir+"\\"+Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
Second Approach: (Browser the File and Save Opens SaveDialog with Directory as Image Directory and File name as Previously selected File)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
SaveFileDialog f = new SaveFileDialog();
f.InitialDirectory = imageDir;
f.FileName = textBox1.Text;
if (f.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(imageDir + "\\" + Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}```
Does this code work for you?
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Select Picture";
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
dlg.Filter = "Common Picture Files|*.gif;*.png;*.bmp;|All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.FileName;
}
}
I am generation json which show something like this (var json): ["C:\Users\Admin\Desktop\222.mp3","C:\Users\Admin\Desktop\TGD.mp3"]
How can I parse it with "foreach"? I want to use everysingle link in my app.
private void Button_Click_7(object sender, RoutedEventArgs e)
{
// Eksport
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Json (*.json)|*.json";
if (saveFileDialog.ShowDialog() == true)
{
string strResultJson = JsonConvert.SerializeObject(MusicList);
File.WriteAllText(saveFileDialog.FileName, strResultJson);
MessageBox.Show("Twoja playlista zostaĆa zapisana!");
}
}
private void Button_Click_8(object sender, RoutedEventArgs e)
{
// Import
OpenFileDialog fileDialog = new OpenFileDialog
{
Multiselect = false,
DefaultExt = ".json"
};
bool? dialogOk = fileDialog.ShowDialog();
if (dialogOk == true)
{
string linkToPlaylist;
linkToPlaylist = fileDialog.FileName;
var json = new WebClient().DownloadString(linkToPlaylist);
// What's now?
MessageBox.Show(json.ToString());
}
}
I made a program with iTextSharp which allows the user to click on a button to choose a file and do the main function with the second button.
Now I want to make a button which will replace this function in the second button:
using (Stream dest = File.Create(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf"))
I want to make a third button which will get the chosen location by the user, not a given location which is not changeable.
The whole Code:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
byte[] bytes = File.ReadAllBytes(theFile);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12,
iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (Stream source = File.OpenRead(theFile))
using (Stream dest = File.Create(theCFile))
{
PdfReader reader = new PdfReader(source);
using (PdfStamper stamper = new PdfStamper(reader, dest))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT,
new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
private void button12_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.FolderBrowserDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) ;
}
Use the FolderBrowserDialog class to select a folder location.
You can combine the output folder and filename using Path.Combine(selectedFolder, filename) and place that in the using statement.
Code for saving the selected output folder:
private void button12_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.FolderBrowserDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedPath = FD.SelectedPath;
theCFile = Path.Combine(selectedPath, theFile)
}
}
I have a question about the opfiledialog function within c#. When i dont select a file with openfiledialog it put's a text automaticly in my textbox. That text will be "filedialog1". What can i do to fix this.
using System;
using System.Windows.Forms;
using System.IO;
namespace Flashloader
{
public partial class NewApplication : Form
{
private toepassinginifile _toepassinginifile;
private controllerinifile _controllerinifile;
//private controllerinifile _controlIniFile;
public NewApplication(toepassinginifile iniFile)
{
_controllerinifile = new controllerinifile();
_toepassinginifile = iniFile;
InitializeComponent();
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
public bool Run()
{
var result = ShowDialog();
return result == System.Windows.Forms.DialogResult.OK;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
}
private void button3_Click(object sender, EventArgs e)
{
Toepassing toepassing = new Toepassing();
toepassing.Name = nameBox.Text;
toepassing.Controller = (Flashloader.Controller)controllerComboBox.SelectedItem;
toepassing.TabTip = descBox.Text;
toepassing.Lastfile = openFileDialog1.FileName;
fileBox.Text = openFileDialog1.FileName;
if (nameBox.Text == "")
MessageBox.Show("You haven't assigned a Name");
else if (controllerComboBox.Text == "")
MessageBox.Show("You haven't assigned a Controller");
else if (descBox.Text == "")
MessageBox.Show("You haven't assigned a Desciption");
else if (fileBox.Text == "")
MessageBox.Show("You haven't assigned a Applicationfile");
_toepassinginifile.ToePassingen.Add(toepassing);
_toepassinginifile.Save(toepassing);
MessageBox.Show("Save Succesfull");
DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var newcontroller = new Newcontroller(_controllerinifile);
newcontroller.ShowDialog();
controllerComboBox.DataSource = null;
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
}
}
Thanks all for the help
private void button3_Click(object sender, EventArgs e)
{
toepassing.Lastfile = openFileDialog1.FileName;// Dont do this
fileBox.Text = openFileDialog1.FileName; //or this
Its unclear to me why you are holding onto an Open file dialog I would personally do the following
using(OpenFileDialog ofd = new OpenFileDialog())
{
if(ofd.ShowDialog() == DialogResult.OK)
{
classStringVariable = ofd.FileName;
fileBox.Text = ofd.FileName;
}
}
Then in button 3
toepassing.LastFile = classStringVariable ;
fileBox.Text = classStringVariable ;
When you use the Form Designer to add an OpenFileDialog control on you form, the designer assigns at the property FileName the value openFileDialog1.
I suppose you have set something as the initial value for the property FileName. Then in button_click3 you have no mean to check for the DialogResult and thus you get inconditionally this default back.
Fix it removing this default from the designer FileName property
Just add openFileDialog1.FileName= ""; before you show the dialog.
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
In your button3_Click event you're checking for an empty string file name anyways, so they would get the correct error message and they wouldn't have some weird arbitrary default name show up when they open the dialog.
Currently I am saving the contents of my rich textbox as so:
private void asRTFToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf|TXT Files|*.txt";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
telep.SaveFile(saveFile1.FileName, RichTextBoxStreamType.RichText);
}
}
And loading it as:
private void rTFToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.DefaultExt = "*.rtf";
openFile1.Filter = "RTF Files|*.rtf";
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
openFile1.FileName.Length > 0)
{
telep.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);
}
}
How can I save and load the background color of my rich textbox?
try using registery
`private void SaveSettings()
{
RegistryKey R = Registry.CurrentUser.CreateSubKey("RTF box");
R.SetValue("FontName", textBox1.Font.FontFamily.GetName(0));
R.SetValue("FontSize", Convert.ToString(textBox1.Font.Size));
R.SetValue("ForeCol", Convert.ToString(textBox1.ForeColor.ToArgb()));
R.SetValue("BackCol", Convert.ToString(textBox1.BackColor.ToArgb()));
R.SetValue("WordWrap", Convert.ToString(textBox1.WordWrap));
}`
instead of textbox use functions of rich text box