I am using C# in WinForms and trying to print a receipt on a thermal printer. Printing the invoice on less items it is ok but when the items getting bigger it always breaks the paper on a specific height.
This is my code:
PrintDocument pdoc = null;
PrintDialog pd = new PrintDialog();
pdoc = new PrintDocument();
pdoc.PrinterSettings.PrinterName = Settings.GetPrintSettings(2);
pd.Document = pdoc;
pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);
int printCount = Convert.ToInt32(Settings.GetPrintSettings(1));
for (int i = 0; i < printCount; i++)
{
DateTime nowDate = Convert.ToDateTime(lblOrderDate.Text);
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo(); //Date Format
dateFormat.MonthDayPattern = "MMMM";
string strDate = nowDate.ToString("dd MM yyyy HH:mm", dateFormat);
try
{
PaperSize PaperRoll = new PaperSize("Paper Roll", 300, 800);
pdoc.DefaultPageSettings.PaperSize = PaperRoll;
pdoc.Print();
}
catch (Exception)
{
}
}
I tried to specify the height using the PaperSize but still it breaks always at specific height
Related
I am getting a few compile errors with my new Rectangle() - I have a windows form with a few text boxes for user input, and a button to print preview. When the button is pressed to print preview, I want the current windows form to display on the page. I am trying to code the values from the text boxes to display in the top left directly above an image that prints at the bottom half of the page. This is the syntax that I have, but I am getting multiple compile errors. What have I set-up incorrectly? I feel like writing text form a win form to a print document should be fairly straightforward, but I am failing!
private void btnPreview_Click(object sender, EventArgs e)
{
PrintPreviewDialog PrintPreviewDlg = new PrintPreviewDialog();
PrintPreviewDlg.ClientSize = new System.Drawing.Size(400, 300);
PrintPreviewDlg.Location = new System.Drawing.Point(29, 29);
PrintPreviewDlg.Name = "PrintPreviewDlg";
PrintPreviewDlg.MinimumSize = new System.Drawing.Size(375, 250);
PrintPreviewDlg.WindowState = FormWindowState.Maximized;
PrintPreviewDlg.UseAntiAlias = true;
dynamic printData = CreatePrintDocument();
printData.DefaultPageSettings.Landscape = true;
PrintPreviewDlg.Document = printData;
PrintPreviewDlg.ShowDialog();
}
printData CreatePrintDocument()
{
printData document = new printData();
document.SetParentCtrl(this);
document.PrintData.txtAssignmentName = MainInstance.txtAssignmentName.Text;
document.PrintData.txtAssignmentNumber = MainInstance.txtAssignmentNumber.Text;
document.PrintData.txtPreparedBy = MainInstance.txtPreparedBy.Text;
document.PrintData.txtAssignmentSection = MainInstance.txtAssignmentSection.Text;
document.PrintData.DocumentName = "Testing Print Functionality";
return document;
}
class printData : PrintDocument
{
Size m_SubHeaderTextFieldSize;
int m_NormalRowHeight = 0;
class DataToPrintData
{
public string txtAssignmentName, txtAssignmentNumber, txtPreparedBy, txtAssignmentSection;
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
//More print specs here
int LeftSubHeadingWidth = 200;
m_SubHeaderTextFieldSize = new Size(LeftSubHeadingWidth, m_NormalRowHeight);
string printData = "Project Name: " + projectNumberTitle + System.Environment.NewLine +
"Prepared By: " + txtPreparedBy + System.Environment.NewLine +
"Assignment Section: " + txtAssignmentSection + System.Environment.NewLine;
e.Graphics.DrawString(e, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0,0, m_SubHeaderTextFieldSize, StringAlignment.Near);
}
}
Try this code:
var format = new StringFormat {Alignment = StringAlignment.Near};
e.Graphics.DrawString(
printData,
new Font("Times New Roman", 12),
new SolidBrush(Color.Black),
new RectangleF(new PointF(0, 0), m_SubHeaderTextFieldSize),
format);
new RectangleF(0,0, m_SubHeaderTextFieldSize, StringAlignment.Near) it looks like you are providing wrong parameters to RectangleF's constructor. There are 2 overloads - first accepts a PointF and a size you can call it like this:
new RectangleF(new PointF(0f,0f), m_SubHeaderTextFieldSize)
other one 4 points, call it like this:
new RectangleF(0f,0f, m_SubHeaderTextFieldSize.Width, m_SubHeaderTextFieldSize.Height)
any way it looks like StringAlignment.Near relates to e.Graphics.DrawString function ...
I am trying to create word document with few text boxes (more will be added later) on specific location (x and y) on same page using Spire.doc. But this code is generating two pages. Any help with this?
If the a any other way it is not necessary to use Spire.
Please keep in minde thet i am novice to programing, thanks.
string TEMPprocitano;
private void button1_Click(object sender, EventArgs e)
{
citanjeReda();
}
public void citanjeReda()
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
int brojRedova=File.ReadLines(openFileDialog1.FileName).Count();
StreamReader sr = new StreamReader(openFileDialog1.FileName);
for (int i = 0; i <= brojRedova; i++)
{
TEMPprocitano = sr.ReadLine();
f1(); f3();
}
sr.Close();
}
}
public void f1() //doc_pers_no 11
{
try
{
StringBuilder F1 = new StringBuilder(TEMPprocitano);
F1.Remove(0, 22);
F1.Remove(11, 698);
MessageBox.Show(F1.ToString());
//Create a Word document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
//Append a Textbox to paragraph
Spire.Doc.Fields.TextBox tb = paragraph.AppendTextBox(170, 20);
//Set the position of Textbox
tb.Format.HorizontalOrigin = HorizontalOrigin.Page;
tb.Format.HorizontalPosition = 150;
tb.Format.VerticalOrigin = VerticalOrigin.Page;
tb.Format.VerticalPosition = 50;
CharacterFormat format = new CharacterFormat(doc);
format.FontName = "Calibri";
format.FontSize = 11;
format.Bold = false;
Paragraph par1 = tb.Body.AddParagraph();
par1.AppendText(F1.ToString()).ApplyCharacterFormat(format);
//Save to file
doc.SaveToFile("job.docx", FileFormat.Docx);
} catch (Exception){}
}
public void f3() // 32
{
try
{
StringBuilder F3 = new StringBuilder(TEMPprocitano);
F3.Remove(0, 49);
F3.Remove(32, 650);
MessageBox.Show(F3.ToString());
//Create a Word document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
//Append a Textbox to paragraph
Spire.Doc.Fields.TextBox tb = paragraph.AppendTextBox(170, 20);
//Set the position of Textbox
tb.Format.HorizontalOrigin = HorizontalOrigin.Page;
tb.Format.HorizontalPosition = 250;
tb.Format.VerticalOrigin = VerticalOrigin.Page;
tb.Format.VerticalPosition = 150;
CharacterFormat format = new CharacterFormat(doc);
format.FontName = "Calibri";
format.FontSize = 11;
format.Bold = false;
Paragraph par1 = tb.Body.AddParagraph();
par1.AppendText(F3.ToString()).ApplyCharacterFormat(format);
//Save to file
doc.SaveToFile("job.docx", FileFormat.Docx);
} catch (Exception) { }
string TEMPprocitano;
private void button1_Click(object sender, EventArgs e)
{
citanjeReda();
}
public void citanjeReda()
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
int brojRedova=File.ReadLines(openFileDialog1.FileName).Count();
StreamReader sr = new StreamReader(openFileDialog1.FileName);
for (int i = 0; i <= brojRedova; i++)
{
TEMPprocitano = sr.ReadLine();
f1();
}
sr.Close();
}
}
public void f1() //doc_pers_no 11
{
try
{
StringBuilder F1 = new StringBuilder(TEMPprocitano);
F1.Remove(0, 22);
F1.Remove(11, 698);
MessageBox.Show(F1.ToString());
//Create a Word document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
//Append a Textbox to paragraph
Spire.Doc.Fields.TextBox tb = paragraph.AppendTextBox(170, 20);
//Set the position of Textbox
tb.Format.HorizontalOrigin = HorizontalOrigin.Page;
tb.Format.HorizontalPosition = 150;
tb.Format.VerticalOrigin = VerticalOrigin.Page;
tb.Format.VerticalPosition = 50;
tb.Format.NoLine = true;
CharacterFormat format = new CharacterFormat(doc);
format.FontName = "Calibri";
format.FontSize = 11;
format.Bold = false;
Paragraph par1 = tb.Body.AddParagraph();
par1.AppendText(F1.ToString()).ApplyCharacterFormat(format);
////// for F3
StringBuilder F3 = new StringBuilder(TEMPprocitano);
F3.Remove(0, 49);
F3.Remove(32, 650);
MessageBox.Show(F3.ToString());
//Append a Textbox to paragraph
Spire.Doc.Fields.TextBox tb3 = paragraph.AppendTextBox(170, 20);
//Set the position of Textbox
tb3.Format.HorizontalOrigin = HorizontalOrigin.Page;
tb3.Format.HorizontalPosition = 70;
tb3.Format.VerticalOrigin = VerticalOrigin.Page;
tb3.Format.VerticalPosition = 70;
tb3.Format.NoLine = true;
Paragraph par3 = tb3.Body.AddParagraph();
par3.AppendText(F3.ToString()).ApplyCharacterFormat(format);
//Save to file
doc.SaveToFile("job.docx", FileFormat.Docx);
} catch (Exception){}
}
I'd like to print my programmatically created flowdocument in landscape mode and I tried all versions what I've found but none of them works.
Here's my code below:
try
{
// Create a PrintDialog
PrintDialog printDlg = new PrintDialog();
printDlg.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;
// Create a FlowDocument dynamically.
FlowDocument doc = CreateFlowDocumentSum();
doc.Name = "FlowDoc";
doc.ColumnWidth = printDlg.PrintableAreaWidth;
// Create IDocumentPaginatorSource from FlowDocument
IDocumentPaginatorSource idpSource = doc;
// Call PrintDocument method to send document to printer
printDlg.PrintDocument(idpSource.DocumentPaginator, "sum");
doc.Blocks.Clear();
sumTable.Clear();
}
catch
{ }
I did it finally.
Just modified the code in the print button event:
PrintDialog printDlg = new PrintDialog();
LocalPrintServer ps = new LocalPrintServer();
PrintQueue pq = ps.DefaultPrintQueue;
PrintTicket pt = pq.UserPrintTicket;
pt.PageOrientation = PageOrientation.Landscape;
FlowDocument doc = CreateFlowDocumentSum();
doc.PageHeight = 768;
doc.PageWidth = 1104;
PageMediaSize pageMediaSize = new PageMediaSize(doc.PageWidth, doc.PageHeight);
pt.PageMediaSize = pageMediaSize;
IDocumentPaginatorSource source = doc as IDocumentPaginatorSource;
printDlg.PrintDocument(source.DocumentPaginator, "sum");
Then in my FlowDocument I set the width and height:
FlowDocument docSum = new FlowDocument();
docSum.PageHeight = 768;
docSum.PageWidth = 1104;
docSum.ColumnWidth = 1104;
I want to decorate various paragraphs in a PDF file by bolding some text, using different fonts, and colors. I thought I found the code for how to do that (below), but it's not working - all the text is the same font, color (black), and size. Why are my virtual sweat-inducing efforts to prettyify the PDF file so far in vain? Here is my code:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
// Mimic the appearance of Duckbill_Platypus.pdf
var docTitle = new Paragraph("Duckbilled Platypi - they're not what's for dinner");
var titleFont = FontFactory.GetFont("Courier", 18, BaseColor.BLACK);
docTitle.Font = titleFont;
doc.Add(docTitle);
var subTitle = new Paragraph("Baby, infant, toddler, and perhaps 'Terrible 2s' Platypi are called Platypups");
var subtitleFont = FontFactory.GetFont("Times Roman", 13, BaseColor.BLACK);
subTitle.Font = subtitleFont;
doc.Add(subTitle);
var importantNotice = new Paragraph("Teenage platypi are sometimes called Platydude[tte]s");
var importantNoticeFont = FontFactory.GetFont("Courier", 13, BaseColor.RED);
importantNotice.Font = importantNoticeFont;
doc.Add(importantNotice);
ListColumns lc;
for (int i = 0; i < listOfListItems.Count; i++)
{
lc = listOfListItems[i];
sb.AppendLine(String.Format(#"<p>Request date is {0}; Payee Name is {1}; Remit Address or Mail Stop is {2}; Last 4 of SSN or ITIN is {3}; 204 Submitted or on file is {4}; Requester Name is {5}; Dept or Div Name is {6}; Phone is {7}; Email is {8}</p>",
lc.li_requestDate, lc.li_payeeName, lc.li_remitAddressOrMailStop, lc.li_last4SSNDigitsOrITIN, lc.li_204SubmittedOrOnFile, lc.li_requesterName, lc.li_deptDivName, lc.li_phone, lc.li_email));
}
String htmlToRenderAsPDF = sb.ToString();
//XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(htmlToRenderAsPDF))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
doc.Close();
}
}
try
{
var bytes = ms.ToArray();
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "iTextSharpTest.pdf");
File.WriteAllBytes(testFile, bytes);
}
catch (Exception ex)
{
String exMsg = ex.Message;
; // what is "ex" here?
}
I'm setting two sizes of font (18 and 13), two colors (black and red), two fonts ("Courier" and "Times Roman") yet all my hours of travail here for PDF fancification seem yet in vain (apologies to Vachel Lindsay and Abraham Lincoln).
You should use the font when creating the Paragraph:
Font f = new Font(FontFamily.COURIER);
Paragraph p = new Paragraph("text", f);
document.add(p);
Or you should wait to add content until you've set the font:
Paragraph p = new Paragraph();
Font f = new Font(FontFamily.COURIER);
p.setFont(f);
p.addText("text");
document.add(p);
In your code, you have something like this:
Paragraph p = new Paragraph("text");
Font f = new Font(FontFamily.COURIER);
p.setFont(f);
document.add(p);
When setting the font using setFont(), you set the font for the text that will be added to the paragraph, not to the text that is already stored in the paragraph.
For instance:
Paragraph p = new Paragraph("font 1 ");
p.setFont(new Font(FontFamily.COURIER);
p.add("font 2");
document.add(p);
This will add the text font 1 in the default font and font 2 in Courier.
I was wondering how would it be possible to split the word document into two columns. The reason why I want to do this is because I want to be able to fit all of the information on one page.
Thank you so much for your help and time!
My Code
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var margin_size = 100;
PageMargin pargeMargins = new PageMargin();
pargeMargins.Top = margin_size;
pargeMargins.Bottom = margin_size;
SectionProperties sectionProps = new SectionProperties();
sectionProps.Append(pargeMargins);
Body body = mainPart.Document.AppendChild(new Body());
body.Append(sectionProps);
ParagraphProperties paragraphProperties = new ParagraphProperties
(
//new ParagraphStyleId() { Val = "No Spacing" },
new SpacingBetweenLines() { After = "0" }
);
Paragraph para_main = body.AppendChild(new Paragraph(paragraphProperties));
// Creating the Header where the Serial Number will exist
// Serial Number
Run run_mainHeader = para_main.AppendChild(new Run());
RunProperties runProp_mainHeader = new RunProperties(); // Create run properties.
FontSize size_mainHeader = new FontSize();
size_mainHeader.Val = new StringValue("48");
runProp_mainHeader.Append(size_mainHeader);
run_mainHeader.Append(runProp_mainHeader); // Append all of the properties
run_mainHeader.Append(new Text("S/N: " + sn));
// Serial Barcode
Run run_barcode = para_main.AppendChild(new Run());
RunProperties runProp_barcode = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode = new RunFonts(); // Create font
runFontMain_barcode.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode = new FontSize();
size_barcode.Val = new StringValue("48");
runProp_barcode.Append(runFontMain_barcode);
runProp_barcode.Append(size_barcode);
run_barcode.PrependChild<RunProperties>(runProp_barcode);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode.AppendChild(new Text("*" + sn + "*"));
run_barcode.AppendChild(new Break());
// Tube Type
Run run_tubetype = para_main.AppendChild(new Run());
RunProperties runProp_tubetype = new RunProperties(); // Create run properties.
FontSize size_tubetype = new FontSize();
size_tubetype.Val = new StringValue("38");
runProp_tubetype.Append(size_tubetype);
run_tubetype.Append(runProp_tubetype); // Append all of the properties
run_tubetype.Append(new Text("Tube Type: " + forms[0].TubeType + " "));
//run_tubetype.Append(new Break());
// Tube Barcode
Run run_barcode_tube = para_main.AppendChild(new Run());
RunProperties runProp_barcode_tube = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode_tube = new RunFonts(); // Create font
runFontMain_barcode_tube.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode_tube = new FontSize();
size_barcode_tube.Val = new StringValue("48");
runProp_barcode_tube.Append(runFontMain_barcode_tube);
runProp_barcode_tube.Append(size_barcode_tube);
run_barcode_tube.PrependChild<RunProperties>(runProp_barcode_tube);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode_tube.AppendChild(new Text("*" + forms[0].TubeType + "*"));
run_barcode_tube.AppendChild(new Break());
// Goes through all of the forms
foreach (var form in forms)
{
// Set up a header per form
Run run_header = para_main.AppendChild(new Run());
RunProperties runProp_formHeader = new RunProperties();
Bold bold = new Bold();
Underline ul = new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single };
FontSize size_formHeader = new FontSize();
size_formHeader.Val = new StringValue("24");
runProp_formHeader.Append(size_formHeader);
runProp_formHeader.Append(bold);
runProp_formHeader.Append(ul);
run_header.AppendChild(new RunProperties(runProp_formHeader));
//run_header.AppendChild(new RunProperties(new Bold(), new Underline()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header));
run_header.AppendChild(new Break());
// Goes through all of the fields that each form contains.
for (int i = 0; i < form.FieldList.Count; i++)
{
// Do not need to print out user or serial for each form.
if (!(form.FieldList[i].Token == "SNT"))
{
Run run_data = para_main.AppendChild(new Run());
if (form.FieldList[i].Default)
{
run_data.AppendChild(new Text(form.FieldList[i].Label));
}
else
{
run_data.AppendChild(new Text(form.FieldList[i].Label + " " + form.FieldList[i].Spec + form.FieldList[i].Value));
}
run_data.AppendChild(new Break());
}
}
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
Currently the code prints out everything top-down on one column. And I want it with two columns
You can two or how many columns you want using the Columns Class for the SectionProperties and ParagraphProperties Class
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.columns(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.paragraphproperties(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v=office.14).aspx
This should do it:
// Add a new main document part.
package.AddMainDocumentPart();
// Create the Document DOM.
package.MainDocumentPart.Document = new Document();
Body bd = package.MainDocumentPart.Document.Body = new Body();
//write a first paragraph on two columns
var paragrap1 = new Paragraph();
var paragraphSectionProperties = new ParagraphProperties(new SectionProperties());
var paragraphColumns = new Columns();
paragraphColumns.EqualWidth = true;
paragraphColumns.ColumnCount = 2;
paragraphSectionProperties.Append(paragraphColumns);
paragrap1.Append(paragraphSectionProperties);
paragrap1.Append(new Run(new Text(str)));
bd.AppendChild(paragrap1);
//write another paragraph without paragraph properties
bd.Append(new Paragraph(new Run(new Text(str))));
//set the body properties default three columns
var sectionProperties = new SectionProperties();
var columns = new Columns();
columns.EqualWidth = true;
columns.ColumnCount = 3;
sectionProperties.Append(columns);
bd.Append(sectionProperties);
package.MainDocumentPart.Document.Save();
You can do it for the complete document with this code:
var sectionProperty = document.Body.Descendants<SectionProperties>().First();
var paragraphColumns = new Columns {EqualWidth = true, ColumnCount = 2};
sectionProperty.Append(paragraphColumns);
Try with..
Word.Application WordApp = new Word.Application();
Word.Document BaseDoc = default(Word.Document);
Word.Document DestDoc = default(Word.Document);
int intNumberOfPages = 0;
string intNumberOfChars = null;
int intPage = 0;
//Word Constants
const var wdGoToPage = 1;
const var wdStory = 6;
const var wdExtend = 1;
const var wdCharacter = 1;
//Show WordApp
WordApp.ShowMe();
//Load Base Document
BaseDoc = WordApp.Documents.Open(Filename);
BaseDoc.Repaginate();
//Loop through pages
intNumberOfPages = BaseDoc.BuiltInDocumentProperties("Number of Pages").value;
intNumberOfChars = BaseDoc.BuiltInDocumentProperties("Number of Characters").value;
for (intPage = 1; intPage <= intNumberOfPages; intPage++) {
if (intPage == intNumberOfPages) {
WordApp.Selection.EndKey(wdStory); }
else {
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.MoveLeft(Unit = wdCharacter, Count = 1);
}
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Copy();
Application.DoEvents();
//Create New Document
DestDoc = WordApp.Documents.Add;
DestDoc.Activate();
WordApp.Selection.Paste();
DestDoc.SaveAs(NewFileName + intPage.ToString + ".doc");
DestDoc.Close();
DestDoc = null;
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Delete();
Application.DoEvents();
}
BaseDoc.Close(false);
BaseDoc = null;
WordApp.Quit();
WordApp = null;