I have the following issue when trying to draw a string and then printing it to PDF by Amyuni Printer :
where I couldn't select the text when pressing (Ctrl+A) , I need this PDF file to use it into another PDF reader , and it seems that the reader , tries to read the selected area not the actual text area .
I'm using the following code to do this stuff :
Font printFont = new Font("Simplified Arabic Fixed", (float)11, FontStyle.Regular);
StreamReader Printfile;
using (StreamReader Printfile = new StreamReader(#"C:\20_2.txt", Encoding.Default))
{
try
{
PrintDocument docToPrint = new PrintDocument();
PaperSize ps = new PaperSize("A4", 827, 1169);
bool bolFirstPage = true;
docToPrint.DefaultPageSettings.PaperSize = ps;
docToPrint.DefaultPageSettings.Landscape = true;
docToPrint.DocumentName = "docName" + DateTime.Now.Ticks.ToString(); //Name that appears in the printer queue
string FirstLine = Printfile.ReadLine();
bool bIsArabic = true;
docToPrint.PrintPage += (s, ev) =>
{
float nFontHight = printFont.GetHeight(ev.Graphics);
bIsArabic = true;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 1008;
float topMargin = 120;
string line = null;
//Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics) + 2;
Image img = Image.FromFile(#"C:\image.bmp");
ev.Graphics.DrawImage(img, 6, 1, 1095, 728);
//***Image Reslution is Working good -->***
StringFormat format = new StringFormat()/*arabic*/;
line = Printfile.ReadLine();
format = new StringFormat(StringFormatFlags.DisplayFormatControl | StringFormatFlags.DirectionRightToLeft)/*arabic*/;
do
{
yPos = topMargin + ((count) * printFont.GetHeight(ev.Graphics) * (float)0.91);
line = " تجربة تجربة تجربة تجربة تجربة";
ev.Graphics.DrawString(line, printFont, Brushes.DeepPink, leftMargin, yPos, format);
count++;
} while ((line = Printfile.ReadLine()) != null && !line.Contains(''));// lines contains \0 as UniCode
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
};
docToPrint.Print();
}
catch (System.Exception f)
{
MessageBox.Show(f.Message);
}
}
}
when I'm using another font type like "Arial" I can select near to 90% of the text, but unfortunately I have to use only the font type "Simplified Arabic Fixed" , and I'm using windows server 2003.
one more thing , when i try to print directly Arabic text from notepad it's work fine.
Related
I have been searching for long time to print formatted text and images which are in panel(PanelContain) but I have not get yet to print formatted text and images.Please tell me which text box support early I had used Rich text box but it does not convert in bitmap so I was getting blank text box.
Please help me.It is very very important for my project.
This is my code:
private void PrintPanel()
{
System.Drawing.Printing.PrintDocument doc = new PrintDocument();
doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
doc.Print();
}
private void doc_PrintPage(object sender, PrintPageEventArgs e)
{
try
{
RichTxtRptBody.BorderStyle = BorderStyle.None;
Bitmap bmp = new Bitmap(PanelContain.Width,
PanelContain.Height);
float tgtWidthMM = 210; //A4 paper size
float tgtHeightMM = 297;
float tgtWidthInches = tgtWidthMM / 25.4f;
float tgtHeightInches = tgtHeightMM / 25.4f;
float srcWidthPx = bmp.Width;
float srcHeightPx = bmp.Height;
float dpiX = srcWidthPx / tgtWidthInches;
float dpiY = srcHeightPx / tgtHeightInches;
bmp.SetResolution(dpiX, dpiY);
PanelContain.DrawToBitmap(bmp, PanelContain.ClientRectangle);
e.Graphics.InterpolationMode =
InterpolationMode.HighQualityBicubic;
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
e.Graphics.DrawImage(bmp, 3, 1, tgtWidthMM, tgtHeightMM-24);
}
catch (Exception ex)
{
}
}
private void toolStripBtnPrint_Click(object sender, EventArgs e)
{
try
{
Img = null;
PrintDocument doc = new PrintDocument();
PrintDialog dlgSettings = new PrintDialog();
dlgSettings.Document = doc;
if (dlgSettings.ShowDialog() == DialogResult.OK)
{
PrintPanel();
}
}
catch (Exception ex)
{
}
}
I have also given a snapshot of my panel:
YOU can use webbrowsercontrol populate dynamically and then you can print easily as you want to print with full formatting option as html code can help you to give layout also.
You want to print a rich text box content with formatting
Try this :
Here eintragRichTextBox is a RichTextBox
private void druckenPictureBox_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
PrintDocument documentToPrint = new PrintDocument();
printDialog.Document = documentToPrint;
if (printDialog.ShowDialog() == DialogResult.OK)
{
StringReader reader = new StringReader(eintragRichTextBox.Text);
documentToPrint.PrintPage += new PrintPageEventHandler(DocumentToPrint_PrintPage);
documentToPrint.Print();
}
}
private void DocumentToPrint_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
StringReader reader = new StringReader(eintragRichTextBox.Text);
float LinesPerPage = 0;
float YPosition = 0;
int Count = 0;
float LeftMargin = e.MarginBounds.Left;
float TopMargin = e.MarginBounds.Top;
string Line = null;
Font PrintFont = this.eintragRichTextBox.Font;
SolidBrush PrintBrush = new SolidBrush(Color.Black);
LinesPerPage = e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);
while (Count < LinesPerPage && ((Line = reader.ReadLine()) != null))
{
YPosition = TopMargin + (Count * PrintFont.GetHeight(e.Graphics));
e.Graphics.DrawString(Line, PrintFont, PrintBrush, LeftMargin, YPosition, new StringFormat());
Count++;
}
if (Line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
PrintBrush.Dispose();
}
I Have written this code to formats textbox
for (int i = 0; i < datGrid.Rows.Count - 1; i++)
{
String data = String.Format(
"{0,-18} {1,-10} {2,-10} {3,-7} {4,-10} | {5,5} ",
datGrid.Rows[i].Cells[0].Value.ToString(),
datGrid.Rows[i].Cells[1].Value.ToString(),
datGrid.Rows[i].Cells[2].Value.ToString(),
datGrid.Rows[i].Cells[3].Value.ToString(),
datGrid.Rows[i].Cells[4].Value.ToString(),
datGrid.Rows[i].Cells[5].Value.ToString());
textBox1.Text += "\n" + data;
data = "";
}
textBox1.Text += "\n------------------------------------";
textBox1.Text += "\n" +
String.Format("{0,-1}{1,-10}{2,-2}{3,-10}{4,-2}{5,-1}",
"Total :" + " ", labelTotal.Text+" ",
"Paid :" + " ", labelPaid.Text + " ",
"Balance:" + " ", labelBalance.Text);
I Used followiing code to print
streamToPrint = new StringReader(textBox1.Text);
streamToPrint.InitializeLifetimeService();
try
{
printFont = new Font("Arial", 8);
dialog.Document = pd;
PaperSize paperSize = new PaperSize("My Envelope",410,420);
pd.DefaultPageSettings.PaperSize = paperSize;
// pd.DefaultPageSettings.Landscape = true;
pd.DefaultPageSettings.Margins = new Margins(5, 5,5, 10);
pd.PrintPage += new PrintPageEventHandler (this.pd_PrintPage);
if (dialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}
finally
{
streamToPrint.Close();
}
And to print text following code
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin - 3,
yPos - 5, new StringFormat(StringFormatFlags.LineLimit));
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
//ev.Graphics.DrawString(textBox1.Text,
// new Font("Arial", 20, FontStyle.Regular), Brushes.Black, 20,20);
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
But I want to print in tabular format that I have given. This code is not working.
Your printFont is a proportional font (Arial) and therefore will not work with your type of tabular formatting. You have two options:
Pick a fixed size font like Consolas. This will fix the problem without hassle.
Print those chunks you feed into your formatted string separately to their respective horizontal positions. This allows you to use any Font you like.
BTW: You write that you put the same text into a TextBox. It should have the same problems, but only the first option will work there without being a pain..!
Have been looking for this from past 2days couldn't sort out, finally im here.
Now starting with the Question,
How to Print a reciept on dot matrix printer and stop after printing one reciept with out continuing to prnt complete page with white spaces from C#, iam able to print using the below JScript code, but continues to print whole page even after reciept is completed.
function Print-content() {
var DocumentContainer = document.getElementById('div2');
var WindowObject = window.open('', "PanelDetails"
,"width=1000,height=550,top=100
,left=150,toolbars=no,scrollbars=yes
,status=no,resizable=no");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.open();
WindowObject.print();
}
But after printing half page, printer doesnt stop it proceeds and prints complete page with white spaces, well thats a usual problem seen on many sites but didn't come up with a solution, So have shifted to server side coding, using ITextSharp Dll.
Can some one please help me with complete solution for printing a reciept half Page and stop the printer after printing last line of the page, which is vertical half of the Letter Fanfold 8-1/2'' 11'' size.
for more clarity if required i will post C# code aswell, but in order not to mess i ignored the code
Thanks in advance
Here's my C# code
StringReader sr;
private void ExportDataListToPDF()
{
using (PrintDocument doc = new PrintDocument())
{
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.div2.RenderControl(hw);
sr = new StringReader(sw.ToString());
doc.DocumentName = "Hello";
doc.DefaultPageSettings.Landscape = false;
PaperSize psize = new PaperSize("MyCustomSize", 216, 279);
doc.DefaultPageSettings.PaperSize = psize;
doc.PrinterSettings.DefaultPageSettings.PaperSize = psize;
psize.RawKind = (int)PaperKind.Custom;
doc.PrinterSettings.DefaultPageSettings.PaperSize.Height = doc.PrinterSettings.DefaultPageSettings.PaperSize.Height / 2;
doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
doc.PrinterSettings.PrinterName = "EPSON LQ-1150II";
doc.PrintController = new StandardPrintController();
// doc.PrinterSettings.PrintFileName = sw.ToString();
doc.Print();
}
}
public void doc_PrintPage(object sender, PrintPageEventArgs ev)
{
System.Drawing.Font printFont = new System.Drawing.Font(FontFamily.GenericSerif, 12);
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = sr.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
I am trying to get the out put from SSRS export and send it direct to a Server side printer without calling a print Dialog
ReportingService.ReportExporter.Export("basicHttpEndpoint", new NetworkCredential("userNmae", "*********"), reportName, parameters.ToArray(), reportFormat, out output, out extension, out mimeType, out encoding, out warnings, out streamIds);
In this case the export type is an Image; I am trying to get the output (which is a Byte Array) and setting a Memory stream and then trying to print directly using PrintDocumen() as follows
Stream stream = new MemoryStream(output);
StreamReader streamToPrint = new StreamReader(stream);
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
pd.PrintController = new StandardPrintController();
pd.Print();
The pd_PrintPage is well documented onthe web and MSDN
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
I am not able to get the format of the data, it just prints the image data as characters. DO I need to convert the output data to another format?
Becasue you're telling the print command to brint the bytes as text instead of rendering the output. In order to render the stream to the printer you need a PDF print driver (e.g. Acrobat). Here are some options:
https://stackoverflow.com/questions/8338953/print-in-memory-pdf-without-saving-directly-without-a-printer-dialog-or-user-i
Printing a PDF in c# using a stream ... can it be done ?
I am making a program that can write in Bengali (a virtual keyboard) or in English. Everything was perfect until I started programming the printing. The user should be able to select any text and change the font and color. Because every character could be different, I need to print character by character. Here is my code:
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
PrintDialog print = new PrintDialog();
doc = new System.Drawing.Printing.PrintDocument();
print.Document = doc;
doc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDoc);
if (print.ShowDialog() == DialogResult.OK)
{
doc.Print();
}
}
private void printDoc(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
System.IO.StringReader reader = new System.IO.StringReader(richTextBox1.Text);
float linesPerPage = 0;
float yPosition = 0;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float rightMargin = e.MarginBounds.Right;
float topMargin = e.MarginBounds.Top;
string line = null;
Font printFont = this.richTextBox1.Font;
SolidBrush printBrush = new SolidBrush(Color.Black);
int charpos = 0;
int xPosition = (int)leftMargin;
linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
while (count < linesPerPage && ((line = reader.ReadLine()) != null))
{
xPosition = (int)leftMargin;
yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
count++;
for (int i = 0; i < line.Length; i++)
{
richTextBox1.Select(charpos, 1);
if ((xPosition + ((int)e.Graphics.MeasureString(richTextBox1.SelectedText, richTextBox1.SelectionFont).Width)) > rightMargin)
{
count++;
if (!(count < linesPerPage))
{
break;
}
xPosition = (int)leftMargin;
yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
}
printBrush = new SolidBrush(richTextBox1.SelectionColor);
e.Graphics.DrawString(richTextBox1.SelectedText, richTextBox1.SelectionFont, printBrush, new PointF(xPosition, yPosition));
xPosition += ((int)e.Graphics.MeasureString(richTextBox1.SelectedText, richTextBox1.SelectionFont).Width);
charpos++;
}
}
if (line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
printBrush.Dispose();
}
}
However, when I get a print preview, it shows a space between each of the the characters:
I think this is because e.Graphics.MeasureString() is not giving me the tightest bounding box possible, or it's not giving me the exact width of the character as specified by the font. I'm quite new to C# Anyone know of a way to get the exact width of a character? It's been stumping me for a long time.
According to this MSDN article:
The (Graphics Class) MeasureString method is designed for use with individual string and includes a small amount of extra space before and after the string to allow for overhanging glyphs
You can instead use TextRenderer.MeasureString() to get the precise font width.
GOT IT. Finally. You need to use e.Graphics.MeasureString() after all. Just another overload of it. Use this:
e.Graphics.MeasureString(richTextBox1.SelectedText, richTextBox1.SelectionFont, new PointF(xPosition, yPosition), StringFormat.GenericTypographic).Width;
To remove the space you need to pass StringFormat.GenericTypographic. Hope it helps. (you can use my code for printing text with different color and text if you replace e.Graphics.MeasureString(string, Font) with the above).