Printing Text To Paper From Text Boxes - c#

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 ...

Related

bootstrap css file makes smaller my document when i convert html to PDF with itextsharp in c# Winforms

I am trying to build a customized PDF export form with HTML and bootstrap to use in any c# project. I want to use bootstrap designs to make my custom PDF designs. There is no problem with my own custom css file. It is working fine. But when I add the css file of bootstrap, it makes my document zoom out and be much smaller too. I cannot figure out how to fix this. I just want to create an A4 paper size form in PDF and print it.
Here is what I get when I add the bootstrap css file:
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace pdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
byte[] result;
Document documment = new Document(PageSize.A4);
string bootstrapCssFilePath = #"C:/Users/sea_h/Desktop/cop/fulhtml/pdf/bootstrap.min.css";
string customCssFilePath = #"C:/Users/sea_h/Desktop/cop/fulhtml/pdf/custom.css";
string htmlText = #"
<html>
<head>
</head>
<body>
<div class='container'>
<col-sm4>
<h1>Deneme H1</h1>
</col-sm4>
<col-sm4>
<h2>deneme h2</h2>
</col-sm4>
<col-sm4>
<h7>deneme h7</h7>
</col-sm4>
</div>
</body>
</html>";
using (var ms=new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(documment, ms);
writer.CloseStream = false;
documment.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(bootstrapCssFilePath, true);
cssResolver.AddCssFile(customCssFilePath, true);
IPipeline pipeLine = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(documment, writer)));
XMLWorker worker = new XMLWorker(pipeLine, true);
XMLParser xmlParser = new XMLParser(worker);
xmlParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(htmlText)));
documment.Close();
result = ms.GetBuffer();
string dest = #"C:\Users\sea_h\Desktop\deneme016.pdf";
System.IO.File.WriteAllBytes(dest, result);
}
}
}
}
My custom css is:
h1{
background-color:red;
}
There is no error message.
First you need a button or something to trigger the print job, then toss on some code like this, essentially this is just going pop a print menu and go ahead with print job when user hits submit (returns 1)
In the printImage method you are going to find the declarations for fonts etc you intend to use. I'm sure there are other ways, but I use rectangles to place my draw strings where I need them. tempPoint.X and tempPoint.Y are followed by rect.location = tempPoint, this allows you to move the rectangle around as needed and keep tracking of coordinates as you go. e.graphics.drawstring() is what actually writes the text, for more specifics I would go ahead and look up some further information. From this you can just keep replicating the tempPoint movement, rect location assignment, and drawstring to customize where things are placed in your print form. As far as turning it into a pdf, windows comes with tools that are in the print menu to automate that part of it all.
private void Button1_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintImage);
PrintDialog printdlg = new PrintDialog();
/*preview the assigned document or you can create a different previewButton for it
printPrvDlg.Document = pd;
printPrvDlg.ShowDialog(); // this shows the preview and then show the Printer Dlg below
*/
printdlg.Document = pd;
if (printdlg.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}
void PrintImage(object o, PrintPageEventArgs e)
{
const int ORIGIN = 150;
var near = new StringFormat() { Alignment = StringAlignment.Near };
var centered = new StringFormat() { Alignment = StringAlignment.Center };
var far = new StringFormat() { Alignment = StringAlignment.Far };
Point tempPoint = new Point();
var rect = new RectangleF(0, 0, 0, 0);
var headingRect = new RectangleF(0, 0, 0, 0);
// Create font and brush.
Font titleDrawFont = new Font("Times New Roman", 16, FontStyle.Bold);
Font subtitleDrawFont = new Font("Times New Roman", 12);
Font drawFont = new Font("Times New Roman", 8);
SolidBrush drawBrush = new SolidBrush(Color.Black);
Pen blackPen = new Pen(Color.Black, 1);
// Draw string to screen.
//***************************************************************
Image logo = Image.FromFile(imageLoc);
e.Graphics.DrawImage(logo, (e.PageBounds.Width - logo.Width) / 2,
10, logo.Width, logo.Height); //Created Centered Image in original size
rect.Width = 150;
rect.Height = 20;
headingRect.Width = e.PageBounds.Width;
headingRect.Height = 40; //Set to 40 to avoid cut off with larger title text
tempPoint.X = 0;
tempPoint.Y = 110;
headingRect.Location = tempPoint;
e.Graphics.DrawString(lblTitle.Text, titleDrawFont, drawBrush, headingRect, centered);
So i just figure out why this is happenning.
Bootstrap css file using rem units for sizing.
But itextsharp using 300ppi resulotion whic means A4 paper have 2480 px X 3508 px resulotion in 300ppi.And bootstrap sizing is so small for this resulotion.
So i can modify bootstrap css file with new higher sizes as manually to fix this problem.
Or if it is possible, i can try the set itextsharp paper ppi for lower as like 70ppi.
I think there is no clear solution for this problem.

How do I get the RTF value (Not plain text value)

Im using the TX TextEditingControl (free version) and I think this is absolutely great.
But I cant seem to get the RTF (Text) content that I need.
//Define
private TXTextControl.TextControl rtf = new TXTextControl.TextControl();
[...code...]
private void button_Click(object sender, EventArgs e) {..
//rtf.Save(s, TXTextControl.StreamType.RichTextFormat);
//This is what I would like to do but I cant find the property or function that does this.
string s = rtf.DocumentRTF;
//Im expecting the standard RTF Format but I get blank
MessageBox.Show(s);
}
Found it! There is no RTF property, to get the output you must use the save() function. Luckily you can write to streams and strings.
string s = "";
rtf.Selection.Bold = true;
//rtf.Selection.Save(TXTextControl.StreamType.RichTextFormat);
rtf.Save(out s,TXTextControl.StringStreamType.RichTextFormat);
MessageBox.Show(s);
dear use the following
for Vb.Net
Dim RegFont As New Font("Arial", UseFontSize, FontStyle.Bold)
Dim VIPFont As New Font("Arial", UseFontSize, FontStyle.Bold)
MyRitchText.SelectionFont = VIPFont
MyRitchText.SelectionAlignment = HorizontalAlignment.Center
MyRitchText.SelectionColor = Color.Green
for c#
Font RegFont = new Font("Arial", UseFontSize, FontStyle.Bold);
Font VIPFont = new Font("Arial", UseFontSize, FontStyle.Bold);
MyRitchText.SelectionFont = VIPFont;
MyRitchText.SelectionAlignment = HorizontalAlignment.Center;
MyRitchText.SelectionColor = Color.Green;
thanks :D

Barcode number under generated Barcode using Barcode Rendering Framework in web application

Following is my previous question that is working fine and generating the barcode.
My previous Question
Now, I just want the characters(forming the barcode) to be written under this barcode(image). How can i achieive that.? I am using Barcode Rendering Framework for generating the barcode. Please help.
Can I do it by taking a panel and adding the image and the text(barcode characters) and printing the panel.??
I did it by using asp panel in which i added the barcode image that is created. Under that I added the string i.e my barcode characters. Then using the print helper function I am able to print them.
Following is my code for adding image and text to panel.
Code39BarcodeDraw barcode39 = BarcodeDrawFactory.Code39WithoutChecksum;
// Panel pnl = new Panel();
Label str = new Label();
str.Text="SER1012308131";
// System.Drawing.Image img = barcode39.Draw("SER1012308131", 40);
//string path = Server.MapPath("~/Uploads/") + img+".jpeg";
string path = #"~/Uploads/abcd.jpeg";
// img.Save(path);
Image imgg = new Image();
imgg.ImageUrl=path;
pnlpnl.Width = Unit.Pixel(300);
pnlpnl.Height = Unit.Pixel(45);
pnlpnl.Controls.Add(imgg);
pnlpnl.Controls.Add(str);
Session["ctrl"] = pnlpnl;
ClientScript.RegisterStartupScript
(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=45px,width=300px,scrollbars=1');</script>");
Print helper function.
public PrintHelper()
{
}
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}
public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>");
HttpContext.Current.Response.End();
}

Creating a button on an existing pdf using itext sharp

I have been trying for long but no success i have an existing pdf that i wan to load to my current C# app and want to create a simpe pusbutton to it , plaese cite some working code the default directory of the pdf is "C:\abc.pdf".
I am using itextsharp, C# VS 2010
Thanks
The closest solution I can find is something like the following.
static void AddPushbuttonField(string inputFile, iTextSharp.text.Rectangle buttonPosition, string buttonName, string outputFile)
{
using (PdfStamper stamper = new PdfStamper(new PdfReader(inputFile), File.Create(outputFile)))
{
PushbuttonField buttonField = new PushbuttonField(stamper.Writer, buttonPosition, buttonName);
stamper.AddAnnotation(buttonField.Field, 1);
stamper.Close();
}
}
This came from here, but was not ranked up as a solution. The code looks good and based on my experience with itextsharp I think this will do the trick.
Source:
Adding button in a pdf file using iTextSharp
Rectangle _rect;
_rect = new Rectangle(50, 100, 100, 100);
PushbuttonField button = new PushbuttonField(writer, _rect, "button");
PdfAnnotation widget = button.Field;
button.BackgroundColor = new GrayColor(0.75f);
button.BorderColor = GrayColor.GRAYBLACK;
button.BorderWidth = 1;
button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
button.TextColor = GrayColor.GRAYBLACK;
button.FontSize = 11;
button.Text = "Text";
button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
button.ProportionalIcon = true;
button.IconHorizontalAdjustment = 0;

How to create pdfformfields using iTextSharp?

I am using iTextSharp and CSharp for creating the pdf. I need to add formfields like checkbox, radiobutton and dropdown which can not be edited.
I used this..
FileStream pdffile = new FileStream(path + "/Pdf/tes.pdf",FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(doc, pdffile);
doc.Open();
Rectangle rect = new Rectangle(100, 100, 100, 100);
RadioCheckField checkbox = new RadioCheckField(writer, rect, "bhjabsdf", "on");
checkbox.CheckType = RadioCheckField.TYPE_CHECK;
PdfFormField field = checkbox.CheckField;
writer.AddAnnotation(field);
doc.Close();
But it's not working. I also read about PdfStamper. But I am creating a new pdf, not changing the existing one.So I don't know whether I can use PdfStamper?
Thanks..
Edit:
private void CreateRadioButton(PdfWriter writer, PdfContentByte cb,Font font)
{
Rectangle rect;
PdfFormField field;
PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true);
radiogroup.FieldName = "language";
RadioCheckField radio;
int x = 20;
for (int i = 0; i < Petrol.Length; i++)
{
rect = new Rectangle(440 + i * x, 692, 450 + i * x, 682);
radio = new RadioCheckField(writer, rect, null, LANGUAGES[i]);
radio.BorderColor = GrayColor.GRAYBLACK;
radio.BackgroundColor = BaseColor.WHITE;
radio.CheckType = RadioCheckField.TYPE_CIRCLE;
if (Petrol[i] == "F")
radio.Checked = true;
field = radio.RadioField;
//Here i am setting readonly..
field.SetFieldFlags(PdfFormField.FF_READ_ONLY);
radiogroup.AddKid(field);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
new Phrase(Petrol[i], font), 451 + i * x, 684, 0);
if (i >= 1) x = 25;
}
writer.AddAnnotation(radiogroup);
}
You're creating a field 'the hard way'. There's a class named RadioCheckField that makes it much easier for you to create a field.
Please take a look at the book examples from Chapter 8. You can find C# versions of the examples here, for instance an example named Buttons.
checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "on");
checkbox.CheckType = RadioCheckField.TYPE_CHECK;
PdfFormField field = checkbox.CheckField;
You can create your custom form template using LiveCycle and then data bind the form fields using iTextSharp like this
string randomFileName = Helpers.GetRandomFileName();
string formTemplate = Server.MapPath("~/FormTemplate.pdf");
string formOutput = Server.MapPath(string.Format("~/downloads/Forms/Form-{0}.pdf", randomFileName));
PdfReader reader = new PdfReader(formTemplate);
PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(formOutput, System.IO.FileMode.Create));
AcroFields fields = stamper.AcroFields;
// set form fields
fields.SetField("Date", DateTime.Now.ToShortDateString());
fields.SetField("FirstName", user.FirstName);
fields.SetField("LastName", user.LastName);
fields.SetField("Address1", user.Address1);
fields.SetField("Address2", user.Address2);
fields.SetField("City", user.City);
fields.SetField("State", user.State);
fields.SetField("Zip", user.Zip);
fields.SetField("Email", user.Email);
fields.SetField("Phone", user.Phone);
// set document info
System.Collections.Hashtable info = new System.Collections.Hashtable();
info["Title"] = "User Information Form";
info["Author"] = "My Client";
info["Creator"] = "My Company";
stamper.MoreInfo = info;
// flatten form fields and close document
stamper.FormFlattening = true;
stamper.Close();
You do not need to use a PdfStamper to create AcroForm form fields in a PDF, PdfWriter also allows you to.
Unfortunately you neither said in which way your code didn't work nor what exact requirements you have; still some sample code might bring you on track:
Have a look at chapter 8 of iText in Action, 2nd edition; especially the sample Buttons will give you numerous hints on how to create radio buttons and check boxes. The sample ChoiceFields will show you how to create list and combo boxes.

Categories