Sending Colored Text to richedit20w - c#

I'm trying to send colored text "RTF" to a richedit20w
Here is mycode:
public static void SendColoredMSG(string Text, string title)
{
RichTextBox richtext = new RichTextBox();
richtext.SelectAll();
richtext.Font = new Font(richtext.SelectionFont.FontFamily, 12, FontStyle.Bold);
richtext.SelectionColor = System.Drawing.Color.Green;
IntPtr hRich = GetRichHandle(title, true);
//here if i replace richtext.rtf with richtext.text it sends the text fine but without color.
SendMessage(hRich, WM_SETTEXT, 0, new StringBuilder(richtext.Rtf));
SendMessage(hRich, WM_KEYDOWN, 13, 0);
}
Problem is if I called this method with:
SendColoredMSG("test","some Title");
it would type:
{\rtf1\fbidis\ansi\ansicpg1256\deff0\deflang3073{\fonttbl{\f0\fnil\fcharset0 Tahoma;}}
{\colortbl ;\red0\green128\blue0;}
\viewkind4\uc1\pard\ltrpar\cf1\b\f0\fs24 test\cf0\par
}
I'm not sure why this is happening and what I should do about it to make it work.

Related

Symbol font is rasterized when printing from .NET application

I am creating a Postscript file from C# by printing to a Postscript printer set up to print to a file. I'm using the .NET PrintDocument class and Graphics.DrawString to render the text.
If I use a symbol or pictograph font such as Symbol or WingDings, the text is rasterized in the Postscript file. If I use e.g. Arial, then the text is not rasterized. My aim is to produce a Postscript file from my application where text using a symbol font is not rasterized.
If I print the same text using symbol font from e.g. notepad the text is not rasterized, so it doesn't at first glance appear to be a printer driver limitation.
What am I doing wrong/different that's causing the rasterization?
The printer's font substitution table is set to not substitute the font.
Symbol font is available on the printers I have tried.
Choosing another Postscript printer driver makes no difference.
Using the TextRenderer.DrawText produces the same result.
Printing using the Symbol font from other applications (Notepad, Word, etc) does not result in rasterized output.
#region Usings
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
#endregion
public class PrintingExample
{
private string _fontName;
private string _printerName;
private string _textToPrint;
//private bool endPrintFired = false;
// private bool keepGoing = true;
private Font printFont;
public PrintingExample(string fontName, string printerName, string textToPrint)
{
_fontName = fontName;
_printerName = printerName;
_textToPrint = textToPrint;
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
const float fontSize = 14.0f;
var fFamily = new FontFamily(_fontName);
printFont = new Font(fFamily, fontSize, FontStyle.Regular, GraphicsUnit.Point);
var leftMargin = ev.MarginBounds.Left;
var topMargin = ev.MarginBounds.Top;
ev.Graphics.DrawString(_textToPrint, printFont, Brushes.Black, new Point(leftMargin, topMargin), new StringFormat());
// Only printing one page
ev.HasMorePages = false;
}
// Print the file.
public void Printing()
{
try
{
var outputFile = string.Empty;
try
{
outputFile = Path.Combine(#"c:\temp\print\", Path.GetRandomFileName() + ".ps");
var pd = new PrintDocument {PrinterSettings = {
PrinterName = _printerName,
PrintToFile = true,
PrintFileName = outputFile}
};
pd.PrintPage += pd_PrintPage;
PrintController pc = new StandardPrintController();
PrintController printController = new PrintControllerWithStatusDialog(pc);
pd.PrintController = printController;
// Print the document.
pd.Print();
}
finally
{
// For debugging, loads in default associated application
if (File.Exists(outputFile))
Process.Start(outputFile);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// This is the main entry point for the application.
public static void Main(string[] args)
{
const string fontName = "Symbol";
const string printerName = "<Choose an installed Postscript printer here>";
const string textToPrint = "1234567890\r\nabcdefghijklmnopqrstuvwxyz";
var p = new PrintingExample(fontName, printerName, textToPrint);
p.Printing();
}
}
This turned out to be a bug in Windows 2012R2, 10, Server 2016, and Server 2019 (server 2008R2 was unaffected, which led us to open an MS case). Only some fonts were affected. It was resolved in the March 2021 OS updates for Windows 10, Server 2016 and Server 2019

Printing to a thermal printer with ASP.NET C# WebForms (4.5)

I have a requirement for a project at work to print to a thermal printer (specifically a Citizen CT-S651) that is attached to the computer via USB from ASP.NET C# Webforms. So far, I have tried a few things and did a lot of research. The main three things I have tried was using QZ Tray (formerly known as JZebra, found here https://qz.io/), however the non-free version costs too much right now, and the free version is too annoying in its popups to be of much use right now. I also tried to generate a PDF using MigraDoc (http://www.pdfsharp.net/), but when I try to print to the printer, it uses far too much paper before it even prints "Hello World" code for that shown below:
private void print()
{
Document document = CreateDocument();
document.UseCmykColor = true;
const bool unicode = false;
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
//pdfRenderer.Save("C:/Users/jamesl/Documents/Visual Studio 2013/Projects/TestCheckScanner/TestCheckScanner/TestDocument.pdf");
MemoryStream stream = new MemoryStream();
pdfRenderer.PdfDocument.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();
}
private Document CreateDocument()
{
Document document = new Document();
MigraDoc.DocumentObjectModel.Unit width, height;
width = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(80);
height = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(50);
Section section = document.AddSection();
section.PageSetup.PageHeight = height;
section.PageSetup.PageWidth = width;
section.PageSetup.PageHeight = height;
section.PageSetup.PageWidth = width;
section.PageSetup.LeftMargin = 0;
section.PageSetup.RightMargin = 0;
section.PageSetup.TopMargin = 0;
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black; //Same as System.Drawing.Color
paragraph.AddFormattedText("Hello, World!");
return document;
}
Since that hasn't worked very well, I have gotten it to print a little bit using PrintDocument, however, the main problems I have with this way are twofold: 1. Formatting it print a proper receipt is going to be very tedious although if it is ends up being the best way with my current constraints I am all for it. 2. This method only works if I print from Visual Studio, when I try it on the test web app I have set up on a server, I get an error of "Settings to access printer 'CITIZEN CT-S651' are not valid." Here is my code for that:
private void print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.PrinterSettings.PrinterName = "CITIZEN CT-S651";
pd.Print();
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.End();
}
}
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Test Print", new System.Drawing.Font("Arial", 12), new SolidBrush(Color.Black), 60, 0);
e.Graphics.DrawString("Test Again", new System.Drawing.Font("Arial", 12), new SolidBrush(Color.Black), 60, 20);
}
Any help you can give on this matter would be awesome!

How to Thumb Preview in Picture Box From Thumb Impression Device

I am trying to preview an image in picture box from Thumb Impression device. I am doing this successfully on button click which shows an image of my thumb on button click. But my requirement is, when i keep my thumb it should immediately shows my thumb without button click. Following is the code which i am using in button click. Please anyone guide.
private void GetMinDataBtn_Click(object sender, EventArgs e)
{
SGFingerPrintManager manager = new SGFingerPrintManager();
int deviceInfo = manager.Init(SGFPMDeviceName.DEV_AUTO);
deviceInfo = manager.OpenDevice(0);
try
{
this.m_TestMin.Initialize();
SGFPMDeviceInfoParam pInfo = new SGFPMDeviceInfoParam();
deviceInfo = manager.GetDeviceInfo(pInfo);
byte[] buffer = new byte[pInfo.ImageWidth * pInfo.ImageHeight]; //Here sometime it fails to load image through device. And sometimes it continously works without an issue.
deviceInfo = manager.GetImageEx(buffer, 0x1388, (int)this.FDxPicBox.Handle, 50);
if (manager.CreateTemplate(buffer, this.m_TestMin) == 0)
{
this.FdxToFIRBtn.Enabled = true;
this.VerifyBtn.Enabled = true;
this.StatusBar.Text = "Get Minutiae Data Success";
deviceInfo = manager.CloseDevice();
}
}
catch (Exception ex)
{
deviceInfo = manager.CloseDevice();
MessageBox.Show(ex.ToString());
this.StatusBar.Text = "Thumb data failed to get";
}
}

custom font prints random characters

I have the following code to print something:
class Print
{
public static void print(string titel, string text, short i, Color color) {
PrintDocument doc = new PrintDocument();
doc.PrintController = new StandardPrintController();
doc.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(titel, new Font("Microsoft Sans Serif", 20), new SolidBrush(color), new PointF(30, 40));
PrivateFontCollection pfc = new PrivateFontCollection();
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".Barc.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata, 0, (int)fontStream.Length);
fontStream.Close();
unsafe
{
fixed (byte * pFontData = fontdata)
{
pfc.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length);
}
}
e1.Graphics.DrawString("*" + text + "*", new Font(pfc.Families[0], 20), new SolidBrush(Color.Black), new PointF(30, 120));
};
doc.PrinterSettings.Copies = i;
try
{
fd.BeginInvoke(doc, null, null);
}
catch (Exception ex)
{
MessageBox.Show("error while printing: " + ex.ToString());
}
}
private delegate void FunctionDelegate(PrintDocument doc);
private static FunctionDelegate fd = new FunctionDelegate(doprint);
private static void doprint(PrintDocument doc)
{
doc.Print();
}
}
When I print something from my computer using (for example) Print.print("A1439213616", "A1439213616", 1, Color.Black) it will work correctly, using the barcode font to print the second line.
But when i copied my program onto another pc, it still printed the first line correctly, but the second line printed, in the default font instead of the custom font, #3) , +1*) +. ) . #. (the only pattern I've been able to spot so far is that the * are getting replaced with # everytime) Whats going wrong here? I am using .NET framework 3.5.
update: without changing anything, now 50% of the time it suddenly does print it correctly and 50% of the time its still the same as before.

Pull Up Print Dialog In Notepad

What I'm trying to do is create a Windows Journal (.jrn) file from a .txt. This conversion can be done by printing to a virtual "Journal Note Writer" printer. I've been struggling with a few different methods of getting this to work for a while now, so I've decided to try to simplify things (I hope).
What I Currently Have
Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
FileName = fileToOpen, // My .txt file I'd like to convert to a .jrn
CreateNoWindow = true,
Arguments = "-print-dialog -exit-on-print"
};
p.Start();
This opens the file in Notepad, but does not open the print dialog. I'd like for the print dialog to open and ideally to be able to specify some default options in the print dialog.
Another thing I've tried is this (found in another SO question):
Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
CreateNoWindow = true,
Verb = "print",
FileName = fileToOpen
};
p.Start( );
The problem with this is that it just automatically prints the file to the default printer (a physical one) without giving me the option to change it.
What I'm Looking For
At this point I'm just looking for any way to print a .txt to "Windows Note Writer." I've tried doing the printing without going through an external application, and had some trouble with that as well. I haven't been able to find any other references to converting to a .jrn file, so I'm open to ANY ideas.
To get Journal Note Writer as printer you would have to add it into the printer preferences -> Add Printer (I wonder whether it could be done programmatically).
Anyways you can always get a print of a plain .txt file as described here at MSDN.
After struggling with this issue for a while, I decided to go back to trying the handle the printing directly through the application without going through Notepad. The issue I was having before when I tried this was that changing the paper size would break the resulting .jrn file (the printout would be blank). It turns out that changing some paper size settings was necessary to print on a non-native paper size.
Below is the final code in case anybody else struggles with this issue. Thanks for everybody's help.
private void btnOpenAsJRN_Click(object sender, EventArgs e) {
string fileToOpen = this.localDownloadPath + "\\" + this.filenameToDownload;
//Create a StreamReader object
reader = new StreamReader(fileToOpen);
//Create a Verdana font with size 10
lucida10Font = new Font("Lucida Console", 10);
//Create a PrintDocument object
PrintDocument pd = new PrintDocument();
PaperSize paperSize = new PaperSize("Custom", 400, 1097);
paperSize.RawKind = (int)PaperKind.Custom;
pd.DefaultPageSettings.PaperSize = paperSize;
pd.DefaultPageSettings.Margins = new Margins(20, 20, 30, 30);
pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["journalNotePrinter"];
pd.DocumentName = this.filenameToDownload;
//Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
//Call Print Method
try {
pd.Print();
}
finally {
//Close the reader
if (reader != null) {
reader.Close();
}
this.savedJnt = fileToOpen.Replace("txt", "jnt");
System.Threading.Thread.Sleep(1000);
if (File.Exists(this.savedJnt)) {
lblJntSaved.Visible = true;
lblJntSaved.ForeColor = Color.Green;
lblJntSaved.Text = "File successfully located.";
// If the file can be found, show all of the buttons for completing
// the final steps.
lblFinalStep.Visible = true;
btnMoveToSmoketown.Visible = true;
btnEmail.Visible = true;
txbEmailAddress.Visible = true;
}
else {
lblJntSaved.Visible = true;
lblJntSaved.ForeColor = Color.Red;
lblJntSaved.Text = "File could not be located. Please check your .jnt location.";
}
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs) {
//Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
//Read margins from PrintPageEventArgs
float leftMargin = ppeArgs.MarginBounds.Left;
float topMargin = ppeArgs.MarginBounds.Top;
string line = null;
//Calculate the lines per page on the basis of the height of the page and the height of the font
linesPerPage = ppeArgs.MarginBounds.Height /
lucida10Font.GetHeight(g);
//Now read lines one by one, using StreamReader
while (count < linesPerPage &&
((line = reader.ReadLine()) != null)) {
//Calculate the starting position
yPos = topMargin + (count *
lucida10Font.GetHeight(g));
//Draw text
g.DrawString(line, lucida10Font, Brushes.Black,
leftMargin, yPos, new StringFormat());
//Move to next line
count++;
}
//If PrintPageEventArgs has more pages to print
if (line != null) {
ppeArgs.HasMorePages = true;
}
else {
ppeArgs.HasMorePages = false;
}
}

Categories

Resources