Resize image after insert in excel sheet - c#

I want to resize image after I insert it on excel sheet. I'm inserting picture like this:
Excel.Pictures p = myWorkSheet.Pictures(System.Type.Missing) as Excel.Pictures;
Excel.Picture pic = null;
pic = p.Insert(path + pic_name + ".png", System.Type.Missing);
pic.Left = Convert.ToDouble(picPosition.Left);
pic.Top = picPosition.Top;
I've tried to resize the picture before insert but it looses its quality.

Solved!!! I've just put next three lines in code above:
pic.ShapeRange.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoCTrue;
pic.ShapeRange.Width = 170;
pic.ShapeRange.Height = 170;
So, now it looks like this:
Excel.Pictures p = myWorkSheet.Pictures(System.Type.Missing) as Excel.Pictures;
Excel.Picture pic = null;
pic = p.Insert(path + pic_name + ".png", System.Type.Missing);
pic.ShapeRange.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoCTrue;
pic.ShapeRange.Width = 170;
pic.ShapeRange.Height = 170;
pic.Left = Convert.ToDouble(picPosition.Left);
pic.Top = picPosition.Top;
and it works great.

Related

Closed XML can't change the font name and size of pivot table

I have created a pivot table using Closed XML. I want to change the font name and size of the pivot table (cells). When I try doing so, it changes the font name and size of the outer sheet (not of the cell content in pivot table). I also tried setting the font name of each cell but couldn't work. Below is the part of my code -
public void CreatePivotTable(List<EmployeeModel> employeeModels)
{
var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add("SourceData");
var table = sheet.Cell(1, 1).InsertTable(employeeModels, "SourceData", true);
var sheetName = "PivotTable";
var ptSheet = workbook.Worksheets.Add(sheetName);
ptSheet.Style.Font.FontName = "Arial";
ptSheet.Style.Font.FontSize = 8;
var pt = ptSheet.PivotTables.Add(sheetName, ptSheet.Cell(5, 2), table.AsRange());
// pt.SetPreserveCellFormatting(false);
pt.RowLabels.Add("EmpId").Compact = true;
pt.RowLabels.Add("EmpName");
pt.ColumnLabels.Add("Description");
pt.ColumnLabels.Add("Department");
pt.Values.Add("HR", "Sum of HR");
pt.Values.Add("MT", "Sum of MT");
pt.SetShowGrandTotalsRows(false);
ptSheet.Cell(1, 3).Value = DateTime.Now.ToString();
ptSheet.Cell(2, 3).Style.Font.Bold = true;
ptSheet.Columns().Width = 11;
ptSheet.Columns("C").Width = 25;
ptSheet.Columns("A").Width = 1;
ptSheet.Columns("B").Width = 0;
ptSheet.Columns("1,2").Hide();
ptSheet.SheetView.FreezeColumns(4);
ptSheet.SheetView.FreezeRows(7);
ptSheet.Rows(1, 4).Hide();
ptSheet.Rows(4, 4).Unhide();
pt.Theme = XLPivotTableTheme.None;
pt.SetClassicPivotTableLayout(true);
//Print Options.
PrintOptionsForPivotTable(ptSheet);
workbook.SaveAs(#"C:\Users\prags\source\repos\WindowsFormsApp1\ClosedXmlPivotTable\pivot.xlsx");
}

DataGridView drawing shows black regions

I have been developing an application using winforms c# .net 4.0.
this application use datagridview and i add combobox + textbox to the datagridview.
During binddata and resizing actions, a black rectangle will draw in the bottom portion of the datagridview.
see the image of the problems
it works perfectly on standard DPI, but problem on the high DPI.
here is the some of my code to binddata and resizing.
using (Class1.Connection = new OleDbConnection(Class1.ConnString))
{
string sql1 = "SELECT tbAuditDetails.AuditNo, tbAuditQuestions.AutoSubcontent, tbAuditQuestions.AutoID, tbAuditQuestions.Questions, tbScore.Description, tbAuditDetails.QuestionID, tbAuditQuestions.QuestAutoID, tbAuditDetails.ScoreID, tbScore.Score, tbAuditQuestions.SubContentID, tbAuditDetails.ProfileID, tbAuditDetails.ScoreRanges, tbAuditDetails.Comments FROM (tbAuditDetails INNER JOIN tbAuditQuestions ON tbAuditDetails.QuestionID = tbAuditQuestions.QuestionID) INNER JOIN tbScore ON tbAuditDetails.ScoreID = tbScore.ScoreID WHERE (([tbAuditDetails.AuditNo] = " + Class1.detailsauditno + ") AND ([tbAuditQuestions.AutoSubcontent] = '" + newautosubcontentid + "') AND ([tbAuditDetails.ProfileID] = " + proid + ")) ORDER BY [tbAuditQuestions.QuestAutoID], [tbAuditDetails.QuestionID]";
Class1.Connection.Open();
oleCommand = new OleDbCommand(sql1, Class1.Connection);
oleAdapter = new OleDbDataAdapter(oleCommand);
oleBuilder = new OleDbCommandBuilder(oleAdapter);
oleDs = new DataSet();
oleAdapter.Fill(oleDs, "tbAuditDetails");
oleTable = oleDs.Tables["tbAuditDetails"];
Class1.Connection.Close();
dataGridView1.DataSource = oleDs.Tables["tbAuditDetails"];
//SET DATAGRIDVIEW
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[8].Visible = false;
dataGridView1.Columns[9].Visible = false;
dataGridView1.Columns[10].Visible = false;
dataGridView1.Columns[1].HeaderText = " ";
dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[1].Width = 40;
dataGridView1.Columns[2].HeaderText = "ID";
dataGridView1.Columns[2].Width = 40;
dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[2].ReadOnly = true;
dataGridView1.Columns[3].Width = 600;
dataGridView1.Columns[3].ReadOnly = true;
dataGridView1.Columns[3].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Columns[11].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[11].HeaderText = "Score";
dataGridView1.Columns[12].Width = 220;
for (int iii = 0; iii < dataGridView1.Rows.Count; iii++)
{
DataGridViewComboBoxCell ComboBoxCell2 = new DataGridViewComboBoxCell();
ComboBoxCell2.Items.Add("0");
ComboBoxCell2.Items.Add("10");
ComboBoxCell2.Items.Add("20");
ComboBoxCell2.Items.Add("30");
ComboBoxCell2.Items.Add("40");
ComboBoxCell2.Items.Add("50");
ComboBoxCell2.Items.Add("60");
ComboBoxCell2.Items.Add("70");
ComboBoxCell2.Items.Add("80");
ComboBoxCell2.Items.Add("90");
ComboBoxCell2.Items.Add("100");
//ComboBoxCell.Items.AddRange(new string[] { "YES", "SOME", "NO", "N/A" });
ComboBoxCell2.FlatStyle = FlatStyle.Standard;
this.dataGridView1[11, iii] = ComboBoxCell2;
ComboBoxCell2.Dispose();
}
}
Any suggestions?
I don't know this is the right solution or not...
BUT, it fix my problem.
Here :
Right click on the .exe program (after you build) and Disable HIGH DPI

out of memory exception with grid in scrollviewer

I am very new in developing apps with C# for WP 8.1 Silverlight.
I developed an app to display data from a csv-file.
The data is displayed in a grid within a scrollviewer element with 7 columns.
All works fine. But when the app gets more then 600 lines from the csv-file the app crashes with an out of Memory exception.
How can I avoid this? It should be no problem to display 600 lines of text in a grid.
See my code:
//insert lines:
//Row create:
reihe1 = new RowDefinition();
reihe1.Height = new GridLength(zeilenhoehe);
grid_umsatzdetail.RowDefinitions.Add(reihe1);
reihe1 = null;
//Columns create:
//first column date:
textblock_name = dateizeile + "|" + index_daten + "|" + "0";
TextBlock textblock_new_datum = new TextBlock();
textblock_new_datum.Name = textblock_name;
textblock_new_datum.Height = zeilenhoehe;
textblock_new_datum.Width = Double.NaN;
textblock_new_datum.FontSize = schriftgroesse;
textblock_new_datum.Text = " " + teile[0] + " ";
Grid.SetRow(textblock_new_datum, zaehler_reihe);
Grid.SetColumn(textblock_new_datum, 0);
grid_umsatzdetail.Children.Add(textblock_new_datum);
textblock_new_datum = null;
//border insert into grid:
rand = new Border();
rand.BorderThickness = new Thickness(1);
rand.BorderBrush = new SolidColorBrush(Colors.White);
rand.Width = Double.NaN;
rand.Height = zeilenhoehe_head;
Grid.SetRow(rand, zaehler_reihe);
Grid.SetColumn(rand, 0);
grid_umsatzdetail.Children.Add(rand);
rand = null;
//second column amount:
... same coding as above for every column ...
I am really happy for any tips!

Generating report (invoice) in ASP.NET C#

So I have a gridview with orders filling it. On the side of each row I have set a link button which says "generate invoice". I've defined command name as "GenerateInvoiceCommand" and command argument OrderID so that I can get all the data I need about that order. Now my question is... Is there any way that I can generate a PDF report and once its generated that it automatically starts downloading? Is there any way I can do this without inserting the pdf report first into the database then downloading it?
What other ways are there to generate reports like this?
Any help is appreciated!
Thanks!
I can see there are two ways :
Use Crystal Report to generate PDF, this answer
Write your own code to generate PDFs, my answer
Because you have tagged Crystal Report, you may want to use first but for gaining more control on your report's appearance second option looks better.
you should first use a third party software like crystal-reports or stimulsoft to generate the report's template(myReport.mrt) and then do something like this :
StiReport report = new StiReport();
string path = "~/report/myReport.mrt";
report.Load(Server.MapPath(path));
// register your data to report's template
report.Render();
if (!Directory.Exists(Server.MapPath("~/report/PDF")))
Directory.CreateDirectory(Server.MapPath("~/report/PDF"));
string ReportFileName = Server.MapPath("~/report/PDF/test.pdf");
report.ExportDocument(StiExportFormat.Pdf, ReportFileName);
FileStream file = File.Open(ReportFileName, FileMode.Open);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
file.Close();
Response.WriteFile(ReportFileName);
hope it helps
You can generate a report programmatically using following code in asp.net C#
you should bound your datatable with your data
DataTable dt = GetDataTableFromDGV(AFIs, ArrayTitle, ArrayEnTitle, ArrayOrder, ArrayChecked);
DataView dataView = dt.DefaultView;
report.ScriptLanguage = StiReportLanguageType.CSharp;
report.RegData("view", dataView);
//fill dictionary
report.Dictionary.Synchronize();
StiPage page = report.Pages.Items[0];
if (Landscape)
page.Orientation = StiPageOrientation.Landscape;
else
page.Orientation = StiPageOrientation.Portrait;
//
Double pos = 0;
//Double columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dataView.Table.Columns.Count, 0.1, true);
Double columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dt.Columns.Count, 0.1, true);
int nameIndex = 1;
columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dt.Columns.Count, 0.1, true);
//create ReportTitleBand
StiReportTitleBand rt = new StiReportTitleBand();
rt.Height = 1.5f;
rt.Name = "ReportTitleBand";
StiText st = new StiText(new RectangleD(0, 0, page.Width, 1f));
st.Text.Value = ReportTitle;
st.HorAlignment = StiTextHorAlignment.Center;
st.Name = "TitleText1";
st.Font = new Font(FontName, 16f);
rt.Components.Add(st);
page.Components.Add(rt);
//create HeaderBand
StiHeaderBand headerBand = new StiHeaderBand();
if (chkRotate)
headerBand.Height = 0.9f;
else
headerBand.Height = 0.5f;
headerBand.Name = "HeaderBand";
page.Components.Add(headerBand);
//create Dataaband
StiDataBand dataBand = new StiDataBand();
dataBand.DataSourceName = "view" + dataView.Table.TableName;
dataBand.Height = 0.5f;
dataBand.Name = "DataBand";
dataBand.CanBreak = true;//Added 11 20 2014
page.Components.Add(dataBand);
//create FooterBand
StiFooterBand footerBand = new StiFooterBand();
footerBand.Height = 0.5f;
footerBand.Name = "FooterBand";
footerBand.Border = new StiBorder(StiBorderSides.All, Color.Black, 1, StiPenStyle.Solid);
footerBand.PrintOnAllPages = true;
page.Components.Add(footerBand);
pos = (page.Width - (columnWidth * Convert.ToDouble(dataView.Table.Columns.Count))) / Convert.ToDouble(2);
for (int i = dataView.Table.Columns.Count - 1; i != -1; i--)
{
DataColumn column = dataView.Table.Columns[i];
//initilized column value
Double headerHeight = 0.5f;
if (chkRotate)
headerHeight = 0.9f;
StiText headerText = new StiText(new RectangleD(pos, 0, columnWidth, headerHeight));
headerText.Text.Value = Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.Caption).Replace("_", " ");//ReplaceUnderLineWithSpace(column.Caption);
if (chkRotate)
headerText.Angle = 90;
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGreen);
headerText.Border.Side = StiBorderSides.All;
headerBand.Components.Add(headerText);
headerText.Font = new Font(FontName, 11.0f);
headerText.WordWrap = true;
headerText.GrowToHeight = true;
//initilized Data Band value
StiText dataText = new StiText(new RectangleD(pos, 0, columnWidth, 0.5f));
dataText.Text.Value = "{view" + dataView.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Border.Side = StiBorderSides.All;
dataText.WordWrap = true;
dataText.GrowToHeight = true;
dataText.Font = new Font(FontName, 11.0f);
//Add highlight
if (true)
{
StiCondition condition = new StiCondition();
condition.BackColor = Color.CornflowerBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1) == 1";
condition.Font = new Font(FontName, 11.0f);
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
}
dataBand.Components.Add(dataText);
pos += columnWidth;
nameIndex++;
}
////footer text
StiText footerText = new StiText(new RectangleD(0, 0, page.Width, 0.5f));
footerText.Text.Value = "صفحه {PageNumber}";
footerText.HorAlignment = StiTextHorAlignment.Center;
footerText.Name = "FooterText";
footerText.Brush = new StiSolidBrush(Color.WhiteSmoke);
footerText.Font = new Font(FontName, 11.0f);
footerBand.Components.Add(footerText);
report.Render(true);
StiWebViewer1.ResetReport();
StiWebViewer1.Report = report;

label printer incorrectly prints itextsharp documents

the code below generate pdf documents:
using (FileStream fs = new FileStream("st.csv", FileMode.Open))
{
using (StreamReader configFile = new StreamReader(fs, System.Text.Encoding.GetEncoding("windows-1250")))
{
string line = string.Empty;
while ((line = configFile.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
line = line.Replace("\"", "");
string[] varible = line.Split(';');
string number = varible[0];
string stName = varible[1];
string ewidenceNumber = varible[2];
string fileName = "barcodes\\" + Encryption.RandomString(10, true) + ".png";
Generate(line, fileName);
PdfPTable Table = new PdfPTable(2);
Table.WidthPercentage = 100;
Table.SetWidths(new[] { 110f, 190f });
iTextSharp.text.Image barcode = iTextSharp.text.Image.GetInstance(fileName);
barcode.Border = 0;
barcode.ScalePercent(180f);
PdfPCell imageCell = new PdfPCell(barcode);
imageCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(imageCell);
PdfPCell descriptionCell = new PdfPCell(new Paragraph(
"Enterprise 1 \n\n" +
number + "\n\n" +
"Number1: " + stName + "\n\n" +
"Number2: " + ewidenceNumber, _standardFont));
descriptionCell.HorizontalAlignment = Element.ALIGN_CENTER;
descriptionCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Table.AddCell(descriptionCell);
Table.KeepTogether = true;
Table.SpacingAfter = 10f;
doc.Add(Table);
}
}
}
}
and here is the problem: vertical and horizontal view in adobe acrobat displays correctly, but when I need to print labels with this information CITIZEN label printer always prints it in horizontal view. I can't adapt this data to print in correct orientation. Anyone has solution for this problem? Maybe I incorrectly rotate cells in table?
I would suggest you drop PDF and instead write to it's native format: http://www.citizen-europe.com/support/progman.htm
PDF printing support is supplied by the driver. If the driver doesn't know how to interpret the specific PDF commands then it's not going to work. Usually label printers don't provide very good driver support for anything but writing to their native format or emulating ZPL (zebra) and Datamax.

Categories

Resources