Reputation: 11740
I am printing a document using print preview and every-time user click to print the data a dialogue asking for printer settings gets prompted which is of course not good. So, in order to remove that print dialogue box I need to store the print dialogue settings some where on the hard disk.
Code
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
if (pdi.ShowDialog() == DialogResult.OK)
{
doc.PrinterSettings = pdi.PrinterSettings;
pd.Print();
}
else
{
MessageBox.Show("Print Cancelled");
}
Problem
how to store print dialog setting in some format and retrieve and store it in the object?
P.S: settings should be saved for the next time when the application is restarted.
Upvotes: 1
Views: 5745
Reputation: 125197
Create a setting key in Setting file of your project and choose System.drawing.Printing.PrinterSettings type for it and name it for example PrinterSettins. Then you can save your printer settings in this property or read from this property simply.
Also you can create some setting keys for individual properties of PrinterSettings
like PrinterName
save them.
Save:
if(printDialog1.ShowDialog()==DialogResult.OK)
{
Properties.Settings.Default.PrinterSettings = printDialog1.PrinterSettings;
//Properties.Settings.PrinterName = printDialog1.PrinterSettings.PrinterName;
Properties.Settings.Default.Save();
}
Read:
printDocument1.PrinterSettings = Properties.Settings.Default.PrinterSettings;
//printDocument1.PrinterSettings.PrinterName = Properties.Settings.Default.PrinterName;
Note:
Since PrinterSettings
class is serializable, another solution is to convert it to a base64 string and save it in a string and restore it from string. So you can create a string setting key PrinterSettings
and save PrinterSettings
in it or restore from it:
Save:
Properties.Settings.Default.PrinterSettings=SettingToString( printDialog1.PrinterSettings);
Properties.Settings.Default.Save();
Read:
printDocument1.PrinterSettings = SettingFromString(Properties.Settings.Default.PrinterSettings);
Helper Methods:
private string SettingToString(PrinterSettings settings)
{
if (settings == null)
return null;
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, settings);
return Convert.ToBase64String(ms.ToArray());
}
}
private PrinterSettings SettingFromString(string base64)
{
try
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream(Convert.FromBase64String(base64)))
{
return (PrinterSettings)bf.Deserialize(ms);
}
}
catch (Exception)
{
return new PrinterSettings();
}
}
Upvotes: 3