On 1 Form I have two buttons (one to print to PDF printer, second to normal printer). I print some bitmap image. However behaviour of the program is strange. Sometimes both buttons work as expected. Sometimes normal printer prints blank, while pdf prints proper, sometimes normal printer do not print anything while pdf printer prints some "code".
Below my code
private void printBtn_Click(object sender, EventArgs e)
{ ... BmpToPrint = new Bitmap(tmp_bmp);
tmp_bmp.Dispose();
string file = "sometext";
pdoc.PrinterSettings.PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer"];
pdoc.DocumentName = file;
pdoc.DefaultPageSettings.Landscape = false;
ppv.Document = pdoc; //printpreviewdialog ppv, printdocument pdoc
printDialog1.Document = pdoc;
if (printDialog1.PrinterSettings.IsValid) { pdoc.Print(); } }
private void printPdfBtn_Click(object sender, EventArgs e)
{... BmpToPrint = new Bitmap(tmp_bmp);
tmp_bmp.Dispose();
string file = "sometext" + ".pdf";
if (!Directory.Exists(directory)) { directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); }
pdoc.PrinterSettings.PrinterName = System.Configuration.ConfigurationManager.AppSettings["PdfPrinter"];
pdoc.PrinterSettings.PrintToFile = true;
pdoc.DocumentName = file;
pdoc.PrinterSettings.PrintFileName = Path.Combine(directory, file);
pdoc.DefaultPageSettings.Landscape = false;
ppv.Document = pdoc;
printDialog1.Document = pdoc;
if (printDialog1.PrinterSettings.IsValid) { pdoc.Print(); } }
private void pdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.Clear(Color.White);
Point PktWst = new Point(5, 0);
e.Graphics.DrawImage(BmpToPrint, PktWst);
e.HasMorePages = false;
}
sometimes in pdf instead of image appears this
Sometimes it works perfectly printing image both to pdf and printer while sometimes the same image as before is either not printed/blank printed/ or pdf has this artifacts instead.
Shall I reset some settings while using second printer or clean some data somehow?
Related
So I have a program which I want to create as a POS Program for restaurant (practicing). The main problem is I add everything product from my program and fill out the details that I want (Name, Address etc. for delivery purposes). For the first time everything goes pretty well and it prints out a nice looking receipt but after that. The printPage method get called for the amount of times which I used it before like a queue which remembers all of the past printings and at the end it is overlapping.
Here is the code for my Printer class. Which I call from my Form1.cs
//Printer.cs
public class Printer
{
public Printer(List<Stuff> _StuffList, OtherClass _OtherClass)
{
this._StuffList = _StuffList;
this._OtherClass = _OtherClass;
}
public void printPage(object sender, PrintPageEventArgs e)
{
Graphics graphics = e.Graphics;
//The other stuff below is just receipt drawing.
}
And Here is my Form1.cs
//Form1.cs
Printer printer;
private void btn_print_Click(object sender, EventArgs e)
{
OtherClass = new _OtherClass(data_from_textbox here));
printer = new Printer(StuffList, OtherClass);
printReceipt(printer);
StuffList.Clear();
listBox.Items.Clear();
OtherClass.Clear();
//reset TextBox & Labels
label.Text = "";
textBox.Text = "";
}
private static String FILE = Environment.CurrentDirectory + #"\FILE.txt";
private void printReceipt(Printer printer)
{
FileStream fs = new FileStream(FILE, FileMode.Open);
StreamReader sr = new StreamReader(fs);
stringToPrint = sr.ReadToEnd();
//printDocument.PrinterSettings.PrinterName = "EPSON TM-T20III Receipt";
printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";
printDocument.PrintPage += new PrintPageEventHandler(printer.printPage);
printDocument.Print();
sr.Close();
fs.Close();
}
I wrote(copied) a small code to select some image files and print it every five minutes.
When it prints, the image doesn't fit to the paper. It's smaller or bigger. So I want to fit the Images to an A4 Page Size.
I couldn't find any properties for that.
Is there a way to do that?
Here is my code:
private async void button1_Click(object btnSender, EventArgs e)
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
// Read the files
foreach (string file in openFileDialog1.FileNames)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "Print Document";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
printDoc.DefaultPageSettings.Landscape = true;
printDoc.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(file);
Point p = new Point(0, 0);
args.Graphics.DrawImage(i, p);
};
printDoc.Print();
await Task.Delay(300000);
}
Process.Start("shutdown.exe", "-s -t 00");
}
}
You do not need to define Point;
To fit image to a page just use args.Graphics.DrawImage(i, args.PageBounds);
instead of args.Graphics.DrawImage(i, p);
I want to print multiple images to a pdf file, but not using the regular print-dialogue, but the 'print pictures' dialogue (see image below). As a printer, I want to use the 'Microsoft print to PDF'-Printer, which comes with windows 10.
My current code looks like this:
string fileName = #"C:\Users\mt\Pictures\test\test.jpg";
var p = new Process();
p.StartInfo.FileName = fileName;
p.StartInfo.Verb = "Print";
p.Start();
So far so good, the right dialogue is showing. I tried it first with other methods, which didn't give me this one. I can now print one image to a pdf page, but how do I add other images? Additionally, in this solution, I can't see how to set the printing-settings, like size of the image, which should be as large as possible without cutting the image and changing to horizontal format.
Earlier, I had this code:
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.PrinterSettings.PrinterName = STR_PRINTER_NAME;
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(#"C:\Users\mt\Pictures\test\1.jpg");
Point loc = new Point(100, 100);
e.Graphics.DrawImage(img, loc);
img.Dispose();
}
which I changed for the 'Print Picture'-Dialog. In the end, the dialog itself doesn't matter, but the 'Print Picture'-Dialog got all settings I need. The only thing the user has to set, is the name for the pdf-file.
Solved the 'Multiple-Page' problem with the following code:
private void button1_Click(object sender, EventArgs e)
{
imgs.Add(img1);
imgs.Add(img2);
imgs.Add(img3);
imgs.Add(img4);
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
Point p = new Point(10, 10);
Image img = Image.FromFile(imgs.ElementAt(page));
graphic.DrawImage(img, p);
page++;
e.HasMorePages = page < imgs.Count;
img.Dispose();
}
Still couldn't figure out how to set maximum size
I built a windows form application that opens any text file (even pdf using iTextSharp Dll) and view its contents in a rich tex box, a search field where i can search for a certain pattern, all possible matches to be highlighted in "Gold" color. I created a save button.
how can i overwrite the text file (.doc) with the text highlighted
by retaining the text format?
how can i do the same step with pdf?
(since pdf will crash after overwriting the file)
The code:
private void open_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
tb.Clear();
label1.Text = openFileDialog1.FileName;
if (label1.Text.Contains(".pdf"))
{
// create a reader (constructor overloaded for path to local file or URL)
string location = openFileDialog1.FileName;
PdfReader reader = new PdfReader(location);
StringBuilder text = new StringBuilder();
for (int page = 1; page <= reader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
reader.Close();
}
tb.Text = text.ToString();
}
else
{
tb.Text = File.ReadAllText(label1.Text);
}
}
}
private void save_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, tb.Text);
}
}
private void search_Click(object sender, EventArgs e)
{
int index = 0;
while (index < tb.Text.LastIndexOf(sb.Text))
{
tb.Find(sb.Text,index,tb.TextLength,RichTextBoxFinds.None);
tb.SelectionBackColor = Color.Gold;
index = tb.Text.IndexOf(sb.Text, index) + 1;
}
}
Thanks in advance!
Can you please try using this to get text along with all rich text format codes?
string str = richTextBox.Rtf;
For more information and implementation guidelines with respect to this context, please refer
http://www.codeproject.com/Articles/12932/Saving-and-Restoring-RichTextBox-Formatted-Text-Al
I am working on Crystal Reports for Visual Studio 2005. I need to change the default printer, and the number of copies to 2 as compared to the default of 1.
I have succeeded to change the default printer using below code.
static int SetAsDefaultPrinter(string printerDevice)
{
int ret = 0;
try
{
string path = "win32_printer.DeviceId='" + printerDevice + "'";
using (ManagementObject printer = new ManagementObject(path))
{
ManagementBaseObject outParams =
printer.InvokeMethod("SetDefaultPrinter",
null, null);
ret = (int)(uint)outParams.Properties["ReturnValue"].Value;
}
}
}
How can I change the number of copies printed?
.Net Framework doesn't provide any mechanism to override the default print functionality. So I disabled the default print button, and added a button name Print.Code for the Event Handler follows below.
private void Print_Click(object sender, EventArgs e)
{
try
{
PrintDialog printDialog1 = new PrintDialog();
PrintDocument pd = new PrintDocument();
printDialog1.Document = pd;
printDialog1.ShowNetwork = true;
printDialog1.AllowSomePages = true;
printDialog1.AllowSelection = false;
printDialog1.AllowCurrentPage = false;
printDialog1.PrinterSettings.Copies = (short)this.CopiesToPrint;
printDialog1.PrinterSettings.PrinterName = this.PrinterToPrint;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
PrintReport(pd);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PrintReport(PrintDocument pd)
{
ReportDocument rDoc=(ReportDocument)crvReport.ReportSource;
// This line helps, in case user selects a different printer
// other than the default selected.
rDoc.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName;
// In place of Frompage and ToPage put 0,0 to print all pages,
// however in that case user wont be able to choose selection.
rDoc.PrintToPrinter(pd.PrinterSettings.Copies, false, pd.PrinterSettings.FromPage,
pd.PrinterSettings.ToPage);
}