Automatically Word-Wrapping Text To A Print Page? - c#

I have some code that prints a string, but if the string is say: "Blah blah blah"... and there are no line breaks, the text occupies a single line. I would like to be able to shape the string so it word wraps to the dimensions of the paper.
private void PrintIt(){
PrintDocument document = new PrintDocument();
document.PrintPage += (sender, e) => Document_PrintText(e, inputString);
document.Print();
}
static private void Document_PrintText(PrintPageEventArgs e, string inputString) {
e.Graphics.DrawString(inputString, new Font("Courier New", 12), Brushes.Black, 0, 0);
}
I suppose I could figure out the length of a character, and wrap the text manually, but if there is a built in way to do this, I'd rather do that. Thanks!

Yes there is the DrawString has ability to word wrap the Text automatically. You can use MeasureString method to check wheather the Specified string can completely Drawn on the Page or Not and how much space will be required.
There is also a TextRenderer Class specially for this purpose.
Here is an Example:
Graphics gf = e.Graphics;
SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa",
new Font(new FontFamily("Arial"), 10F), 60);
gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa",
new Font(new FontFamily("Arial"), 10F), Brushes.Black,
new RectangleF(new PointF(4.0F,4.0F),sf),
StringFormat.GenericTypographic);
Here i have specified maximum of 60 Pixels as width then measure string will give me Size that will be required to Draw this string. Now if you already have a Size then you can compare with returned Size to see if it will be Drawn properly or Truncated

I found this : How to: Print a Multi-Page Text File in Windows Forms
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
}

Dude im suffering with printing in HTML, total nightmare. I would say that in my opinion you should try use something else to print out the text etc pass parameters to reporting services and popup a PDF which the user can print off.
Or potentially you might need to count out the number of characters and explicitly specify a line break!

Related

Receipt printing in roll paper

I searched for a lot in google and did not find what i actually wanted. I got following code, which will print the variable name. I got a Epson Dot Matrix Printer and Roll Paper (Endless continuous paper).
My problem is that, after printing name paper feeds up to size of A4. I don`t want the paper feed. This application is intended to do print receipts which will have unlimited data which need to be printed flawless ( with out page break).
Can you, the smart folk out there to point me in the correct direction with these codes?
edited this code and changed scenario .. please move down further
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Font Heading2 = new Font("Times New Roman", 13);
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Near;
sf.Alignment = StringAlignment.Center;
//e.HasMorePages = false;
PaperSize pkCustomSize1 = new PaperSize("First custom size", 100, 200);
pd.DefaultPageSettings.PaperSize = pkCustomSize1;
e.Graphics.DrawString(name.ToString(), Heading1, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width / 2), e.MarginBounds.Top, sf);
}
Edit 1:- #Adriano Repetti suggested this is a duplicate with Form feed in c# printing. What i learned from the above question is that he want to add the form feed. But i want to remove the form feed.
Edit 2:- I got an another hint by googling that setting the page Height equal to line height will make stop feeding which sounds promising. I am trying to figure that out too.
Edit 3:- #Adriano Repetti suggested me with Raw Printing (Directly printing binary data) with KB link. I googled around about it, and found out its c# better equivalent paste bin or pastie.org (provided because it is a handy one) . At first it sounded good and it worked nicely stopping form feeding. But eventually i struck some ice berg.
On my code i had to align some printing quotes to center or align to left`. for which i got only option of using space and tabs. But there will be no guaranty that it will be well formatted as we can not certain about built in fonts with printer.( Refer:SO Question by #syncis )
And secondly, i will have to move my application to unicode(local language support) capable one, at least with in a month or so. In that scenario, raw printing wont help and i will have to go through theses faces again. SO, For avoiding that its better for me to stay with Graphics DrawString. And for this i changed my code as.
//---------
// start button click
//---------
PrintDocument pdoc = new PrintDocument();
pdoc.DefaultPageSettings.PaperSize.Height = 300;
pdoc.Print();
//---------
// end button click
//---------
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Font Heading2 = new Font("Times New Roman", 13);
// changed following statement to met with new **unicode** criteria
//e.Graphics.DrawString(name.ToString(), Heading1, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width / 2), e.MarginBounds.Top, sf);
TextRenderer.DrawText(e.Graphics, "My name in local language is വിനീത്", Heading2, new Point(0, 0), Color.Black);
}
With current problems, i am redefining the Question extending tag to unicode as.
How can print with TextRenderer.DrawText with unicode support without form feeding ? I think setting paper height to line height will solve my problem. If so how or suggest me a better way to stop paper feeding. It really eats a lot of my valuable time...
EDIT 4: Today I found out a very interesting thing about my printer. I cant even set custom paper size manually (Not by coding.. I mean control panel->printers and faxes ->Epson LX-300+ ->properties -> printing preference-> paper/quality -> advanced -> paper size -> BOOOOOM not showing my custom paper size). I am using Epson LX-300+ printer. Do guys think it wont support custom paper sizes? is that causing me problems?
I found the solution by my self ( sorry for my english ) As Hans Passant says ( PrintDocument is page based. end of story ) You must use ( e.HasMorePages = true; )
float cordenadaX;
float cordenadaY;
int totalPages;
int paginaAtual;
int indiceItem;
List<string> items;
public void ImprimeDanfeNFCe()
{
totalPages = 1;
paginaAtual = 1;
indiceItem = 0;
cordenadaX = 0;
cordenadaY = 0;
items = new List<string>();
items.Add("Item1");
items.Add("Item2");
items.Add("Item3");
(............)
PrintDocument recordDoc = new PrintDocument();
recordDoc.DocumentName = "xMarket danfe";
recordDoc.PrintPage += new PrintPageEventHandler(imprimeDanfeReceipt);
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "My printer";
recordDoc.PrinterSettings = ps;
recordDoc.Print();
recordDoc.Dispose();
}
void imprimeDanfeReceipt(PrintPageEventArgs e)
{
float pageHeight = e.MarginBounds.Height;
string text = "";
if (paginaAtual == 1)
{
text = "Cupom header";
e.Graphics.DrawString(text, drawFontDanfeTitulo, drawBrush, new
RectangleF(cordenadaX, cordenadaY, width, height),
drawFormatCenter);
cordenadaY += e.Graphics.MeasureString(text, drawFontDanfeTitulo).Height;
}
for (int i = indiceItem; i < items.Count; i++)
{
int indice = i + 1;
//items[i] Is very important to not print same items again while print next page
e.Graphics.DrawString(items[i], drawFontDanfeItems, drawBrush,
new RectangleF(cordenadaX, cordenadaY, width, height), drawFormatLeft);
cordenadaY += e.Graphics.MeasureString(text, drawFontDanfeTitulo).Height;
indiceItem++;
//cordenadaY+100 is for the size of the footer
if (cordenadaY+100 >= pageHeight)
{
paginaAtual++;
e.HasMorePages = true;
return;
}
}
e.Graphics.DrawString("page footer", drawFontDanfeItems, drawBrush,
new RectangleF(cordenadaX, cordenadaY, width, height), drawFormatLeft);
cordenadaY += e.Graphics.MeasureString(text, drawFontDanfeTitulo).Height;
}

Add watermark below image but within print area in C#

I am trying to insert a text watermark underneath a TIFF image in my windows form and would definitely appreciate anyone's help. I have a print button that retrieves the image, scales it down, then based on my margins, places the image accordingly to print. I'd like to add an additional piece where just before the image prints, I add in a text watermark (in this case a date stamp) that is just below the image.
I've tried adjusting the margin but that just increases (or decreases depending on the number setting) the image scale but does not add the additional room I want to add the watermark. Below is code of what I have so far:
protected void PrintPage(object sender, PrintPageEventArgs e)
{
if (this.Image == null)
{
e.Cancel = true;
return;
}
//ADD TIME STAMP WATERMARK
string watermark = "DATE ISSUED: " + String.Format("{0:MM/dd/yyyy}", System.DateTime.Now.Date);
System.Drawing.Graphics gpr = Graphics.FromImage(Image);
System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);
Font font = new System.Drawing.Font("Arial", 55, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
SizeF size = e.Graphics.MeasureString(watermark, font);
float x = 0;
float y = Image.Height-size.Height;
RectangleF printArea = new RectangleF(x, y, size.Width, size.Height);
gpr.DrawString(watermark, font, brush, printArea);
e.Graphics.DrawImage(this.Image, e.MarginBounds);
}
The value of e.MarginBounds I have set in my App.config and include the following values: Left=70, Right=90, Top=190; Bottom=475. All the printouts are going to be printed portrait style on Letter 8 1/2 by 11 size paper.
I am able to display the watermark anywhere on top of the image, but I am hoping to place it underneath. When I adjust the y coordinate, and it so happens to be below the image, when I print, I assume that it is outside the print area and therefore, the watermark does not get printed on the page (it only shows the image).
I appreciate anyone's help in this as I have been racking my brain on this and have had no luck.
Aren't you printing your text beneath the image. I think you want to start printing at y=Image.Height + e.MarginBounds.Top, and x=e.MarginBounds.Left
That will print a your label left justified below the image in the margin.
Update: This works:
y=-size.Height + e.MarginBounds.Bottom;
x = e.MarginBounds.Left;
e.Graphics.DrawImage(Image, e.MarginBounds);
// note the change. Using e.graphics instead of gpr below
e.Graphics.DrawString(watermark, font, brush, printArea);

How to have text with bold and normal words for same label?

I need to have text for my label control which as both bold and normal character.
How can I do that? any idea or pointers??
Thanks.
EDIT:
It is Winform, and I am sorry but I have no idea, I am using TWO label for this but I want to use only one.
Is it possible.!!
I have done something like,
using (Graphics g = Graphics.FromImage(pictureBox1.Image))
{
Font drawFont = new Font("Arial", 12);
Font drawFontBold = new Font("Arial", 12, FontStyle.Bold);
SolidBrush drawBrush = new SolidBrush(Color.Black);
// find the width of single char using selected fonts
float CharWidth = g.MeasureString("Y", drawFont).Width;
// draw first part of string
g.DrawString("this is normal", drawFont, drawBrush, new RectangleF(350f, 250f, 647, 200));
// now get the total width of words drawn using above settings
float widthFirst = ("this is normal").Length() * CharWidth;
// the width of first part string to start of second part to avoid overlay
g.DrawString(" and this is bold text", drawFontBold, drawBrush, new RectangleF(350f + widthFirst, 250f, 647, 200));
}
Hope it helps..!!!
NOTE
You can use Label Paint event and Draw the way I have done for lable
I think answer can be relevant for you:
https://stackoverflow.com/a/2527744/3835956
Use a styled RichTextBox instead of a label, select the text and set it to bold.

PrintDocument always has margin

I am having a problem when using PrintDocument with margins.
No matter what I do there is always a margin around everything I print, this means that nothing is aligned where it needs to be.
Here is the code I am using to create the PrintDocument
public void Print()
{
PrintDocument printDocument = new PrintDocument();
printDocument.DefaultPageSettings.PaperSize = new PaperSize("A5",583,827);
printDocument.OriginAtMargins = true;
printDocument.DefaultPageSettings.Margins.Top = 0;
printDocument.DefaultPageSettings.Margins.Left = 0;
printDocument.DefaultPageSettings.Margins.Right = 0;
printDocument.DefaultPageSettings.Margins.Bottom = 0;
if (!string.IsNullOrWhiteSpace(PrinterName))
{
printDocument.PrinterSettings.PrinterName = PrinterName;
}
printDocument.PrintController = new StandardPrintController();
printDocument.PrintPage += On_PrintPage;
printDocument.Print();
}
The On_PrintPage method, has various calls to e.Graphics.Draw... methods.
How can I make it so that something I print at 0,0 will print in the very top left of the page. I know that if the printer cannot print that far to the edge of the page it will be blank, however it should do that rather than print 0,0 not in the top left of the page.
I'm really lost here
interestingly the print function is too late to set most of the properties and would only apply to subsequent pages
you need to use PrintDocument.QueryPageSettings event instead and set the properties there and I always set the page settings not just defaults. then drawing at 0,0 should be as close as you can get (printer + driver allows)
The OriginAtMargins property of the PrintDocument, when set to true, it will sets the origin of the provided Graphics object at the top-left corner of the margin. From the MSDN document Remarks section:
Calculating the area available to print requires knowing the physical
size of the paper, the margins for the page, and the location of the
Graphics object origin. When OriginAtMargins is true, the Graphics
object location takes into account the PageSettings.Margins property
value and the printable area of the page. When OriginAtMargins is
false, only the printable area of the page is used to determine the
location of the Graphics object origin, the PageSettings.Margins value
is ignored.
Set it to false, to change it to the top-left corner of the printable area. If you need it to be at the top-left corner of the page, you will need to transform the graphics object to mach that coordinate; there isn't really a way to get around this:
void PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
var printArea = e.PageSettings.PrintableArea;
e.Graphics.TranslateTransform(-printArea.X, -printArea.Y);
// Build up the page here.
}
If you want to print landscape pages as well, this becomes tricky, as none of the properties of PageSettings are affected by this setting. This requires to know the angle the page is rotated by—as PrintableArea isn't always centered on the page—which can be acquired with PageSettings.PrinterSettings.LandscapeAngle. The value can only be either 90 or 270, and the code would look like this:
void PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
var printArea = e.PageSettings.PrintableArea;
if (e.PageSettings.Landscape)
{
var pageSize = e.PageSettings.PageSize;
switch (e.PageSettings.PrinterSettings.LandscapeAngle)
{
case 90:
e.Graphics.TranslateTransform(
dx: -printArea.Y,
dy: -(pageSize.Width - (printArea.X + printArea.Width)));
break;
case 270:
e.Graphics.TranslateTransform(
dx: -(pageSize.Height - (printArea.Y + printArea.Height)),
dy: -printArea.X);
break;
}
}
else
{
e.Graphics.TranslateTransform(-printArea.X, -printArea.Y);
}
// Build up the page here.
}
If you later want to use another transformation on a portion of the page, do not forget to use var gs = e.Save() before transforming and e.Restore(gs) to restore that transformation, instead of calling e.ResetTransform(), as the later will reset the transformation you did in the beginning.

Printing graphics on multiple pages using System.Drawing.Printing, based on the used coordinates in C#

Using System.Drawing.Printing, I want to print a set of lines on print document.
But the problem is it prints every line on the very first page, what ever the coordinates are, also if I draw an image, It prints that on a single page no matter how big it is.
Following is what I have done for printing text on multiple pages:
protected void ThePrintDocument_PrintPage (object sender, System.Drawing.Printing.PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPosition = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
Font printFont = this.richTextBox1.Font;
SolidBrush myBrush = new SolidBrush(Color.Black);
// Work out the number of lines per page, using the MarginBounds.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
// Iterate over the string using the StringReader, printing each line.
while(count < linesPerPage && ((line=myReader.ReadLine()) != null))
{
// calculate the next line position based on
// the height of the font according to the printing device
yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics));
// draw the next line in the rich edit control
ev.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
}
// If there are more lines, print another page.
if(line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
myBrush.Dispose();
}
What I should do in order to print line on multiple pages, i.e the following code should print on two pages as the length of the line is 1400 and print doc length is 1100, so remaining 300 of the line should be printed on the next page
protected void ThePrintDocument_PrintPage (object sender, System.Drawing.Printing.PrintPageEventArgs ev)
{
Pen P1 = new Pen(Brushes.Violet, 5);
ev.Graphics.DrawLine(P1, new Point(0,0), new Point(500,1400));
}
This is not how printing works in .NET. It does not create a new page just because you print outside the coordinates of the current page. There are events and event arguments which .NET uses to ask from you how many pages your document will contain. It will then invoke the event for printing a page for every page.
See here for an example.
EDIT
Ok, replying to your comment, I can think of two possible solutions: The first solution would involve clipping: intersect your graphic objects with the page's rectangle and print only what's common to both of them. If there were parts outside the clipping region, take that part as the new graphic objects and clip again to print on new page. Repeat this until the remaining graphics fit the page rectangle. However, I can't think of a way of doing that easily.
My second idea is as follows:
Calculate how many pages you would need to print all graphic objects by dividing the bounding rectangle of the graphic objects by the height of the "visual rectangle" of one page (increase number of pages by one if there's a remainder in this division).
Loop the following until reaching the last page
Print all graphic objects to the current page
Decrease all y-coordinates by the "visual height" of a page (effectively moving the graphic objects upwards outside the "bounds of the paper")
While the overhead of printing the entire list of graphic objects for every page may be high, you're leaving the clipping part to the printer driver/the printer itself.

Categories

Resources