How to center align and set bold a text in itext7 - c#

I am new to using itext for generating a pdf. I had a problem, I have added itext7 in my references
to add a pdf with values. I wanted to center align and set bold a text field in my pdf. I have looked at various examples. However,.SetBold and chunk shows error in visual studio.
This is the function which I am calling for the pdf.
[HttpGet]
[Route("GetCoilWiseReport")]
public HttpResponseMessage GetCoilWiseReport(string jwt, string fixture="", string
type="", string ID= "",
string delivery = "", string invoice = "", string wagon = "", string location = "",
string ICHP= "",string remarks="",string date="")
{
if (!Common.VerificationToken.VerifyJWToken(jwt))
{
return null;
}
var doc_date = DateTime.Now.Date.ToString("dd/MM/yyyy").Replace("-", "/");
var Type1 = type;
var id1 = ID;
var delivery1 = delivery;
var invoice1= invoice;
var wagon1 = wagon;
var location1 = location;
var ICHP1 = ICHP;
var remarks1 = remarks;
var date1 = date;
string pdfDocument = #"D:\Annexure_One IT.pdf";//Utilities.ISOP_DOCS_FOLDER +
"MasterDocs\\SupplierDespatchATP.pdf";
var dateLine = "Date:" + doc_date ;
var coilDetails = " COIL Details: " + ID;
var firstRow = "Type : " + type +" ID:"+ID+ " Delivery No:"+delivery;
var secondRow = "Invoice No.:" + invoice+" Wagon No:"+wagon+" Location:"+location;
var thirdRow = "ICHP : " + ICHP + " Remarks:" + remarks;
PdfDocument pdf = new PdfDocument(new PdfWriter(pdfDocument));
//Add new page
PageSize ps = PageSize.A4;
PdfPage page = pdf.AddNewPage(ps);
PdfCanvas canvas = new PdfCanvas(page);
iText.Layout.Document iDoc = new iText.Layout.Document(pdf, ps);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.COURIER);
PdfFont fontBold = PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD);
IList<String> text = new List<String>();
text.Add("");
text.Add(dateLine);
text.Add("");
text.Add("");
text.Add(coilDetails);
text.Add("");
text.Add("");
text.Add(firstRow);
text.Add("");
text.Add("");
text.Add(secondRow);
text.Add("");
text.Add("");
text.Add(thirdRow);
text.Add("");
text.Add("");
text.Add("");
text.Add("");
text.Add("");
text.Add("signature");
;
foreach (String s in text)
{
//Add text and move to the next line
//canvas.NewlineShowText(s);
if (s == "signature")
{
List<string> coilURL = new List<string>();
List<string> coilView = new List<string>();
string connectionstring = Utilities.SQL_DB1;// our SQL DB connection
SqlConnection conn1 = new SqlConnection(connectionstring);
DataTable dt = new DataTable();
string query = "Select CCD_IMAGE_URL,CCD_VIEW_DESC from T_CQL_COIL_DESC
where CCD_COIL_ID = '" + ID + "'";
//SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(query, conn1);
conn1.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; (i < dt.Rows.Count); i++)
{
coilURL.Add(imgurl + dt.Rows[i]["CCD_IMAGE_URL"].ToString());
coilView.Add(dt.Rows[i]["CCD_VIEW_DESC"].ToString());
var view = "View:"+coilView[i];
var sig = coilURL[i];
iText.Layout.Element.Paragraph p1 = new
iText.Layout.Element.Paragraph().Add(view);
//p.SetMaxHeight(20);
iDoc.Add(p1);
iText.Layout.Element.Image sigImage = new
iText.Layout.Element.Image(ImageDataFactory.Create(sig));
sigImage.SetAutoScale(true);
iText.Layout.Element.Paragraph p = new
iText.Layout.Element.Paragraph().Add(sigImage);
//p.SetMaxHeight(20);
iDoc.Add(p);
}
}
conn1.Close();
da.Dispose();
}
else
{
iText.Layout.Element.Paragraph para = new
iText.Layout.Element.Paragraph(s);
para.SetFont(font);
para.SetFontSize(9);
iDoc.Add(para);
}
}
//iDoc.Close();
//Close document
iDoc.Close();
// Add Paragraph to document
pdf.Close();
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StreamContent(new FileStream(pdfDocument,
FileMode.Open, FileAccess.Read));
//httpResponseMessage.Content.Headers.ContentType = new
MediaTypeHeaderValue("application / vnd.openxmlformats -
officedocument.wordprocessingml.document");
httpResponseMessage.Content.Headers.ContentType = new
MediaTypeHeaderValue("application/pdf");
httpResponseMessage.Content.Headers.ContentDisposition = new
ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Coil_Detail" +
fixture + "_" + ID + "_" + ".pdf";
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
I am trying to make CoilDetails bold and center alligned. How do I do that in the current context. Please help

Use p.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); for aligning it in center and for setting it to bold after add try using .SetBold() or .SetFont(bold)

I do a few scripts w/ itext7 using linqpad.net in c#
but I've no issues to convert to visual studio.
here's a line in C#
p = new Paragraph(targetText).SetFontSize(12).SetTextAlignment(TextAlignment.JUSTIFIED).SetFontColor(new DeviceRgb(0, 153, 0)).SetBold();

Related

c# Base64 in email attachment

I know that i'm stuck in a silly problem...and now i am here with hope, that you can help me. Simple situation: I need to send email with attachment from database. I have done it by myself, but...i don't know why, but attachment in email what was send is incorrect. Preciously attachment contents code, what i get from my database.
My code:
static void IncomeMessage()
{
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx");
SqlCommand cmd = new SqlCommand("Here is my SQL SELECT", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try
{
var AID = dr["ID"].ToString();
var Ids = dr["MessageID"].ToString();
var SuperOrganizationTitle = dr["SuperOrganizationTitle"].ToString();
var Date = dr["Date"].ToString();
var Title = dr["Title"].ToString();
var Description = dr["Description"].ToString();
var DBFile = dr["File"].ToString();
var Filename = dr["FileName"].ToString();
MailMessage oMail = new MailMessage("test#test.com", "guntisvindels#gmail.com", "New message with theme: " + Title, "Message Income: " + Date + " From " + SuperOrganizationTitle + ". Message Content: " + Description);
DBFile = GetBase64(DBFile);
var bytes = Encoding.ASCII.GetBytes(DBFile);
MemoryStream strm = new MemoryStream(bytes);
Attachment data = new Attachment(strm, Filename);
ContentDisposition disposition = data.ContentDisposition;
data.ContentId = Filename;
data.ContentDisposition.Inline = true;
oMail.Attachments.Add(data);
SmtpClient oSmtp = new SmtpClient();
SmtpClient oServer = new SmtpClient("test.test.com");
oServer.Send(oMail);
}
catch (Exception ex)
{
//TraceAdd("Error=" + ex.Message.ToString());
}
}
}
For removing unnessessary data ( tags) from database File field i use this code
public static string GetBase64(string str)
{
var index1 = str.IndexOf("<content>");
index1 = index1 + "<content>".Length;
var index2 = str.IndexOf("</content>");
var kek = Slice(str, index1, index2);
return kek;
}
public static string Slice(string source, int start, int end)
{
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
return source.Substring(start, len);
}
When launching my code I can send email to me, and I'll recieve it. But message content attachment with my Base64 code from database File field. Here is a question - Where I got wrong, and how can I recieve email with correct attachment that has been written into database. Thank you for your attention
P.S Attachment in database is written correctly, because K2 integration platform can correctly display it
Here is example what database contain in File column (DBFile)
<file><name>zinojums.html</name><content>PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiIC8+PHN0eWxlPmh0bWwsYm9keXtmb250LWZhbWlseTpBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZjtmb250LXNpemU6MTBwdDt9aDF7Zm9udC1zaXplOjE0cHQ7fWgye2ZvbnQtc2l6ZToxMnB0O31we2JhY2tncm91bmQtY29sb3I6I0Y3RUVEQTttYXJnaW46MDtwYWRkaW5nOjhweDt9aHJ7aGVpZ2h0OjFweDsgYm9yZGVyOjAgbm9uZTsgY29sb3I6ICM1RjlCRDQ7IGJhY2tncm91bmQtY29sb3I6ICM1RjlCRDQ7fTwvc3R5bGU+PC9oZWFkPjxib2R5PjxoMT5JbmZvcm3EgWNpamEgbm8gVmFsc3RzIGllxYbEk211bXUgZGllbmVzdGE8L2gxPjxoMj5Eb2t1bWVudHMgcGllxYZlbXRzPC9oMj48cD5Ob2Rva8S8dSBtYWtzxIF0xIFqYSBOci4gPGI+TEFUVklKQVMgVkFMU1RTIFJBRElPIFVOIFRFTEVWxKpaSUpBUyBDRU5UUlMgQVMgKDQwMDAzMDExMjAzKTwvYj4gaWVzbmllZ3RhaXMgZG9rdW1lbnRzICI8Yj5aacWGYXMgcGFyIGRhcmJhIMWGxJNtxJNqaWVtPC9iPiIgTnIuIDxiPjU1NDYyNTY5PC9iPiBwaWXFhmVtdHMgdW4gaWVrxLxhdXRzIFZJRCBkYXR1YsSBesSTLjxiciAvPjwvcD48IS0tY29udGVudC0tPjxociAvPsWgaXMgZS1wYXN0cyBpciBpenZlaWRvdHMgYXV0b23EgXRpc2tpLCBsxatkemFtIHV6IHRvIG5lYXRiaWxkxJN0LjxiciAvPlBpZXNsxJNndGllcyBWSUQgRWxla3Ryb25pc2vEgXMgZGVrbGFyxJPFoWFuYXMgc2lzdMSTbWFpOiA8YSBocmVmPSJodHRwczovL2Vkcy52aWQuZ292Lmx2Ij5lZHMudmlkLmdvdi5sdjwvYT4uPC9ib2R5PjwvaHRtbD4=</content></file>
Right now the method you're using to create binary data from your string takes no account of the fact the string is base64-encoded specifically.
You need to replace
var bytes = Encoding.ASCII.GetBytes(DBFile);
with
var bytes = Convert.FromBase64String(DBFile);

Can we create drop down list with check box option using epplus library

Initialize the worksheet:
public HttpResponseMessage ER_GenerateWBLWorksheet2()
{
ExcelPackage ExclPkg = new ExcelPackage();
ExcelWorksheet wsSheet1 = ExclPkg.Workbook.Worksheets.Add("Sheet1");
wsSheet1.Cells["A1"].Value = "ProductName";
wsSheet1.Cells["B1"].Value = "Price";
wsSheet1.Cells["C1"].Value = "ProductImageUrl";
wsSheet1.Cells["D1"].Value = "ProductUrl";
wsSheet1.Cells["E1"].Value = "StoreId";
wsSheet1.Cells["G1"].Value = "CategoryId";
wsSheet1.Cells["I1"].Value = "ColorId";
wsSheet1.Cells["K1"].Value = "FabricId";
wsSheet1.Cells["M1"].Value = "Gender";
Create Category list:
var categorylist = wsSheet1.DataValidations.AddListValidation(wsSheet1.Cells["G2:G500"].Address);
var categories = _categoryServices.GetAllCategory();
var categoryEntities = (categories != null) ? categories.ToList() : new List<CategoryEntity>();
for (int i = 0; i < categoryEntities.Count; i++)
{
categorylist.Formula.Values.Add(categoryEntities[i].CategoryName.ToString());
}
categorylist.ShowErrorMessage = true;
categorylist.ErrorTitle = "Error";
categorylist.Error = "Please select the Category from Dropdown";
wsSheet1.Cells["G2:G500"].Style.Locked = false;
Create color list:
var colorlist = wsSheet1.DataValidations.AddListValidation(wsSheet1.Cells["I2:I500"].Address);
var colors = _colorServices.GetAllColor();
var colorsEntities = (colors != null) ? colors.ToList() : new List<ColorEntity>();
for (int i = 0; i < colorsEntities.Count; i++)
{
colorlist.Formula.Values.Add(colorsEntities[i].ColorName.ToString());
}
colorlist.ShowErrorMessage = true;
colorlist.ErrorTitle = "Error";
colorlist.Error = "Please select the Color from Dropdown";
wsSheet1.Cells["I2:I500"].Style.Locked = false;
wsSheet1.Cells[wsSheet1.Dimension.Address].AutoFitColumns();
var filename = #"Inventory_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xlsx";
//string sPath = #"e:\" + filename;
var sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/exportedfiles/" + filename);
Stream stream = File.Create(sPath);
ExclPkg.SaveAs(stream);
stream.Close();
string strServerPath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["excelserverpath"]);
var sPathURL = (strServerPath + "exportedfiles/" + filename);
List<fileinfo> filelst = new List<fileinfo>();
fileinfo file = new fileinfo();
file.filename = filename;
file.fileurl = sPathURL;
//file.fileurl = sPath;
filelst.Add(file);
return new ResponseWrapper<fileinfo>(filelst, HttpStatusCode.OK, null, 0);
}
Using the above code I have created excel with drop down list, but my requirement is to select multiple values from drop down list. Is it possible using epplus library?

How can I get values from a csv file where some of the cells contain commas?

I have a script that imports a csv file and reads each line to update the corresponding item in Sitecore. It works for many of the products but the problem is for some products where certain cells in the row have commas in them (such as the product description).
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (UpdateFile.PostedFile != null)
{
var file = UpdateFile.PostedFile;
// check if valid csv file
message.InnerText = "Updating...";
Sitecore.Context.SetActiveSite("backedbybayer");
_database = Database.GetDatabase("master");
SitecoreContext context = new SitecoreContext(_database);
Item homeNode = context.GetHomeItem<Item>();
var productsItems =
homeNode.Axes.GetDescendants()
.Where(
child =>
child.TemplateID == new ID(TemplateFactory.FindTemplateId<IProductDetailPageItem>()));
try
{
using (StreamReader sr = new StreamReader(file.InputStream))
{
var firstLine = true;
string currentLine;
var productIdIndex = 0;
var industryIdIndex = 0;
var categoryIdIndex = 0;
var pestIdIndex = 0;
var titleIndex = 0;
string title;
string productId;
string categoryIds;
string industryIds;
while ((currentLine = sr.ReadLine()) != null)
{
var data = currentLine.Split(',').ToList();
if (firstLine)
{
// find index of the important columns
productIdIndex = data.IndexOf("ProductId");
industryIdIndex = data.IndexOf("PrimaryIndustryId");
categoryIdIndex = data.IndexOf("PrimaryCategoryId");
titleIndex = data.IndexOf("Title");
firstLine = false;
continue;
}
title = data[titleIndex];
productId = data[productIdIndex];
categoryIds = data[categoryIdIndex];
industryIds = data[industryIdIndex];
var products = productsItems.Where(x => x.DisplayName == title);
foreach (var product in products)
{
product.Editing.BeginEdit();
try
{
product.Fields["Product Id"].Value = productId;
product.Fields["Product Industry Ids"].Value = industryIds;
product.Fields["Category Ids"].Value = categoryIds;
}
finally
{
product.Editing.EndEdit();
}
}
}
}
// when done
message.InnerText = "Complete";
}
catch (Exception ex)
{
message.InnerText = "Error reading file";
}
}
}
The problem is that when a description field has commas, like "Product is an effective, preventative biofungicide," it gets split as well and throws off the index, so categoryIds = data[8] gets the wrong value.
The spreadsheet is data that is provided by our client, so I would rather not require the client to edit the file unless necessary. Is there a way I can handle this in my code? Is there a different way I can read the file that won't split everything by comma?
I suggest use Ado.Net, If the field's data are inside quotes and it will parse it like a field and ignore any commas inside this..
Code Example:
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

Using a join statement to link data together from 2 different datatables into one in C#

I am trying to get some data from one datatable (facilData) and data from another datatable (ownerData) and write it to another datatable (dataStore). The second is not identical to the first. When I attempted my code below, I get the following error: "Unable to case object of type System.DBnull to System.String". Then the debugger takes me back and highlights (int)table2["rowIndex"] in the code below.
public void Write2Sheet(DataTable dt1, DataTable dt2, DataTable dt3, String newFilePath)
{
try
{
//Merge the three Datatables into the single Datatable source
var mdata = from table1 in facilData.AsEnumerable()
join table2 in ownerData.AsEnumerable() on (int)table1["rowIndex"] equals (int)table2["rowIndex"]
select new
{
rowIndex = (int)table1["rowIndex"],
Prog = (string)table1["Prog"],
cStatus = (string)table1["cStatus"],
bStatus = (string)table1["bStatus"],
fID = (string)table1["fID"],
fNam = (string)table1["fNam"],
fAdd = (string)table1["fAdd"],
fCity = (string)table1["fCity"],
fState = (string)table1["fState"],
fCode = (string)table1["fCode"],
oInfo = (string)table2["oInfo"],
pgRecId = (string)table1["pgRecId"],
lAct = (string)table1["lAct"]
};
foreach (var rec in mdata)
{
var row = dataStore.NewRow();
row["rowIndex"] = rec.rowIndex;
row["Prog"] = rec.Prog;
row["cStatus"] = rec.cStatus;
row["bStatus"] = rec.bStatus;
row["fID"] = rec.fID;
row["fNam"] = rec.fNam;
row["fAdd"] = rec.fAdd;
row["fCity"] = rec.fCity;
row["fState"] = rec.fState;
row["fCode"] = rec.fCode;
row["oInfo"] = rec.oInfo;
row["pgRecId"] = rec.pgRecId;
row["lAct"] = rec.lAct;
dataStore.Rows.Add(row);
}
}
catch (Exception e)
{
Write2LogFile("The data tables couldn't merge because: " + e.Message);
}
//Write from the Datatable source to the new spreadsheet and save it
try
{
FileInfo newSheet = new FileInfo(fileName);
using (ExcelPackage xPkg = new ExcelPackage(newSheet))
{
ExcelWorksheet worksheet = xPkg.Workbook.Worksheets[1];
var cell = worksheet.Cells;
int rI = 2;
foreach (DataRow dr in dataStore.Rows)
{
string iDX = rI.ToString();
worksheet.Cells["A" + iDX].Value = dr["Prog"].ToString();
worksheet.Cells["B" + iDX].Value = dr["cStatus"].ToString();
worksheet.Cells["C" + iDX].Value = dr["bStatus"].ToString();
worksheet.Cells["D" + iDX].Value = dr["fID"].ToString();
worksheet.Cells["E" + iDX].Value = dr["fNam"].ToString();
worksheet.Cells["F" + iDX].Value = dr["fAdd"].ToString();
worksheet.Cells["G" + iDX].Value = dr["fCity"].ToString();
worksheet.Cells["H" + iDX].Value = dr["fState"].ToString();
worksheet.Cells["I" + iDX].Value = dr["fCode"].ToString();
worksheet.Cells["J" + iDX].Value = dr["oInfo"].ToString();
worksheet.Cells["K" + iDX].Value = dr["pgRecId"].ToString();
worksheet.Cells["L" + iDX].Value = dr["lAct"].ToString();
rI++;
}
xPkg.Save();
}
}
catch (Exception ex)
{
Write2LogFile("Data was not written to spreadsheet because: " + ex.Message);
}
}
So, I figured it out. Instead of trying to do the query syntax, I went with the method syntax. I added an additional class as a container for my objects I wanted to add to the single datatable. Although none of the row-indices were null, I added a null check anyway. Here is my updated code:
public void Write2Sheet(DataTable dt1, DataTable dt2, DataTable dt3, String newFilePath)
{
try
{
//Merge the three Datatables into the single Datatable source
//method syntax
var mdata = facilData.AsEnumerable().Where(f => f[0] != typeof(DBNull)).Join(ownerData.AsEnumerable(),
table1 => table1.Field<int>(0),
table2 => table2.Field<int>(0),
(table1, table2) => new Class1 //container class
{
rowIndex = (int)table1[0],
Prog = table1[1].ToString(),
cStatus = table1[2].ToString(),
bStatus = table1[3].ToString(),
fID = table1[4].ToString(),
fNam = table1[5].ToString(),
fAdd = table1[6].ToString(),
fCity = table1[7].ToString(),
fState = table1[8].ToString(),
fCode = table1[9].ToString(),
oInfo = table2[1].ToString(),
pgRecId = table1[10].ToString(),
lAct = table1[11].ToString()
});
foreach (var rec in mdata)
{
var row = dataStore.NewRow();
row["rowIndex"] = rec.rowIndex;
row["Prog"] = rec.Prog;
row["cStatus"] = rec.cStatus;
row["bStatus"] = rec.bStatus;
row["fID"] = rec.fID;
row["fNam"] = rec.fNam;
row["fAdd"] = rec.fAdd;
row["fCity"] = rec.fCity;
row["fState"] = rec.fState;
row["fCode"] = rec.fCode;
row["oInfo"] = rec.oInfo;
row["pgRecId"] = rec.pgRecId;
row["lAct"] = rec.lAct;
dataStore.Rows.Add(row);
}
}
catch (Exception e)
{
Write2LogFile("The data tables couldn't merge because: " + e.Message);
}
//Write from the Datatable source to the new spreadsheet and save it
try
{
FileInfo newSheet = new FileInfo(fileName);
using (ExcelPackage xPkg = new ExcelPackage(newSheet))
{
ExcelWorksheet worksheet = xPkg.Workbook.Worksheets[1];
var cell = worksheet.Cells;
int rI = 2;
foreach (DataRow dr in dataStore.Rows)
{
string iDX = rI.ToString();
worksheet.Cells["A" + iDX].Value = dr["Prog"].ToString();
worksheet.Cells["B" + iDX].Value = dr["cStatus"].ToString();
worksheet.Cells["C" + iDX].Value = dr["bStatus"].ToString();
worksheet.Cells["D" + iDX].Value = dr["fID"].ToString();
worksheet.Cells["E" + iDX].Value = dr["fNam"].ToString();
worksheet.Cells["F" + iDX].Value = dr["fAdd"].ToString();
worksheet.Cells["G" + iDX].Value = dr["fCity"].ToString();
worksheet.Cells["H" + iDX].Value = dr["fState"].ToString();
worksheet.Cells["I" + iDX].Value = dr["fCode"].ToString();
worksheet.Cells["J" + iDX].Value = dr["oInfo"].ToString();
worksheet.Cells["K" + iDX].Value = dr["pgRecId"].ToString();
worksheet.Cells["L" + iDX].Value = dr["lAct"].ToString();
rI++;
}
xPkg.Save();
MessageBox.Show("Data was successfully added to the current spreadsheet.");
}
}
catch (Exception ex)
{
Write2LogFile("Data was not written to spreadsheet because: " + ex.Message);
}
}

c# Printing a PDF with iTextSharp

I have a problem with printing a pdf.
So my Document is being created by writing some values in a pdf document and saving it
public void CreateDocument(string name)
{
string oldreport = #"..\Resources\FehlerReport.pdf";
string newreportpath = #"..\Resources\" + name;
using (var newFileStream = new FileStream(newreportpath, FileMode.Create))
{
var pdfReader = new PdfReader(oldreport);
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
form.SetField("Auftragsnummer", Kundeninformation.Auftragsnummer.ToString());
form.SetField("Kundensachnummer", Kundeninformation.Kundensachnummer.ToString());
form.SetField("Kundenname", Kundeninformation.Kundenname.ToString());
form.SetField("Kundenbestellnummer", Kundeninformation.Kundenbestellnummer.ToString());
form.SetField("Kundenrezepturnummer", Kundeninformation.Kundenrezepturnummer.ToString());
form.SetField("Spulennummer", Kundeninformation.Spulennummer.ToString());
form.SetField("Fertigungsdatum1", System.DateTime.Today.ToString("dd.MM.yy"));
int i = 1;
foreach (var item in _MeasurementReport.MeasurementReportItems)
{
form.SetField(("UhrzeitRow" + i).ToString(), item.Uhrzeit.ToString("HH:mm:ss"));
form.SetField(("FehlerindexRow" + i).ToString(), i.ToString());
form.SetField(("Position mmRow" + i).ToString(), (item.Laufmeter * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("HoeheRow" + i).ToString(), (item.DefectCountours.H * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Breite mmRow" + i).ToString(), (item.DefectCountours.W * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Flaeche Row" + i).ToString(), (item.DefectCountours.W * pixelSize * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
i++;
}
form.SetField("Datum", System.DateTime.Today.ToString("dd.MM.yy"));
form.SetField("Uhrzeit", System.DateTime.Now.ToString("HH:mm"));
stamper.FormFlattening = true;
stamper.Close();
pdfReader.Close();
}
}
So now i want to print the document with this function, which also calls the CreateDocument function. It prints, but the paper is white. I checked if the created pdf is being created, and it is being created but apparently not printed.
public void Print()
{
string name = Kundeninformation.Auftragsnummer + "_" + Kundeninformation.Spulennummer+".pdf";
CreateDocument(name);
List<string> PrinterFound = new List<string>();
PrinterSettings printer = new PrinterSettings();
foreach (var item in PrinterSettings.InstalledPrinters)
{
PrinterFound.Add(item.ToString());
}
printer.PrinterName = PrinterFound[7];
printer.PrintFileName = name;
PrintDocument PrintDoc = new PrintDocument();
PrintDoc.DocumentName = #"..\Resources\"+name;
PrintDoc.PrinterSettings.PrinterName = PrinterFound[7];
PrintDoc.Print();
}
make sure your file is created completely.. otherwise you will this issue. to test quickly put some delay between file creation and printing

Categories

Resources