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.
Related
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
I'm trying to create a WPF which can preview documents(word,pdf,png,jpg) located on my HDD. I've tried using printPreviewControl but I cant get it working.
Code:
public Form1()
{
InitializeComponent();
initComponents();
}
public void initComponents()
{
try
{
string fname = "C:\\Users\\Gebruiker\\Desktop\\PDF en DOC\\test.pdf";
streamToPrint = new StreamReader(fname, Encoding.UTF8);
try
{
PrintDocument pd = new PrintDocument();
pd = new PrintDocument();
pd.DocumentName = fname;
//Get responsive width and height.
System.Drawing.Rectangle workingRectangle = Screen.PrimaryScreen.WorkingArea;
int height = workingRectangle.Height / 100 * 85;
int width = workingRectangle.Width / 100 * 75;
//Settings printPreviewControl
printPreviewControl1.ClientSize = new System.Drawing.Size(width, height);
printPreviewControl1.Location = new System.Drawing.Point(0, 0);
printPreviewControl1.Document = pd;
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
*It says its generating the preview, but stays empty, watch image below:
If you guys have any other solution, I'm open to try.
Thanks
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!
My printer is connected via Serial Port (COM3, 9600), and now I want to print some text on it. I have tried all codes that I was found on net, mostly named for epson printers, but none of them didn't worked for me.
Simply I want to send message to printer on Button_click event.
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!serialPort.IsOpen)
serialPort.Open();
serialPort.Write(Message());
}
Simple test message would be (and that's where I need help):
private String Message() {
char[] init = new char[] { (char)0x1b, '#' };
String msg = "";
foreach (char c in init)
msg += c;
msg+="Hello World";
return msg;
}
I also have user manual for printer, with pseudo command:
LPRINT “0123456789012345678901”;
LPRINT CHR$ (&HA);
LPRINT CHR$ (&H9) + “AAA”;
LPRINT CHR$ (&H9) + “BBB”;
LPRINT CHR$ (&HA);
LPRINT CHR$ (&H1B) + “D”;
LPRINT CHR$ (3) + CHR$ (7) + CHR$ (14) + CHR$ (0);
LPRINT CHR$ (&H9) + “AAA”;
LPRINT CHR$ (&H9) + “BBB”;
LPRINT CHR$ (&H9) + “CCC” + CHR$ (&HA);
How this would be converted to C# and does something missing in this pseudo command? I need help here to properly define my Message() method and to print text.
I was found workaround for my problem. Datecs have windows drivers for this type of printer, so that printer acts as regular printer. No messing with com ports and it's params, just send regular formated string for printing. Here is methodt for printing String
public void PrintText(StringBuilder s, String PrinterName)
{
PrintDocument p = new PrintDocument();
p.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(s.ToString(), new Font("Times New Roman", 11), new SolidBrush(System.Drawing.Color.Black), new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));
};
try
{
p.PrinterSettings.PrinterName = PrinterName;
p.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
For this method is needed to add references:
System.Drawing
And to add using statment on top
using System.Drawing;
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.