I warmly welcome...
I have a question I'm trying to convert PDF to txt and I can not save a txt file ?? Someone please help me ??
using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace ZestawienieFaktur
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(#"D:\\faktury\\", "*.pdf");
foreach (string fp in filePaths)
{
ExtractTextFromPdf(fp);
}
}
public static string ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
string lines = text.ToString();
using (var file = new StreamWriter(#"D:\faktury\test1.txt"))
{
file.WriteLine(lines);
file.Close();
}
}
}
}
}
In the folder I have a few pdf files with different names.
And I want all converted to the format of txt.
Big thx for answer...
You should remove the return keyword instead and just return void. The reason why it's not executing is because it stops executing the rest of the code after return. Change it to this:
public static void ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
string lines = "";
using(var file = new StreamWriter(path2))
{
file.WriteLine(lines);
file.Close();
}
}
}
Hope it helps!
OK WORKS thx friends...
using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace ZestawienieFaktur
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(#"D:\faktury\", "*.pdf");
foreach (string fp in filePaths)
{
ExtractTextFromPdf(fp);
}
}
public static string ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
string lines = text.ToString();
using (var file = new StreamWriter(#"D:\faktury\test1.txt"))
{
file.WriteLine(lines);
file.Close();
}
return lines;
}
}
}
}
Related
so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.
I have a windows form that uses a StreamReader to read form data into some text boxes. That works perfectly fine. The problem now is that I want to display the data from the file in order alphabetically by names. Early I tried an array.Sort method, by it didn't work so well.
Here is my code:
Note: I close the reader and file in the dispose method.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ViewArchives
{
public partial class Form1 : Form
{
const char DELIM = ',';
const string FILENAME = #"F:\lscSpring2016\CIS2620\FinalProject\TicketMaster\bin\Debug\SoldTickets.txt";
string recordIn;
string[] fields;
static FileStream file = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file);
public Form1()
{
InitializeComponent();
}
private void btnView_Click(object sender, EventArgs e)
{
try
{
recordIn = reader.ReadLine();
fields = recordIn.Split(DELIM);
nameBox.Text = fields[0];
ticketsBox.Text = fields[1];
purchaseBox.Text = fields[2];
dateBox.Text = fields[3];
}
catch (NullReferenceException)
{
label5.Text = "You have viewed\nall the records filed.";
btnView.Enabled = false;
}
}
}
}
There is a simpler way.
First, introduce a class for containing data from a single line:
class Record
{
public string Name { get; set; }
public string Tickets { get; set; }
public string Purchase { get; set; }
public string Date { get; set; }
}
In your Form1 class do the followings:
Create two fields.
One for the record list and one for indicating the current index in the record collection.
Record[] soldTickets; // This will contain the file data
int currentRecordIndex = -1;
Create a method that loads the whole file in one step into the record collection:
private void LoadRecords()
{
soldTickets =
File
.ReadAllLines(FILENAME)
.Select(line =>
{
string[] data = line.Split(DELIM);
return
new Record()
{
Name = data[0],
Tickets = data[1],
Purchase = data[2],
Date = data[3]
};
})
.OrderBy(record => record.Name)
.ToArray();
currentRecordIndex = -1;
}
Then your button click event handler can look like this:
private void btnView_Click(object sender, EventArgs e)
{
Record currentRecord = soldTickets.ElementAtOrDefault(++currentRecordIndex);
if (currentRecord == null)
{
label5.Text = "You have viewed\nall the records filed.";
btnView.Enabled = false;
return;
}
nameBox.Text = currentRecord.Name;
ticketsBox.Text = currentRecord.Tickets;
purchaseBox.Text = currentRecord.Purchase;
dateBox.Text = currentRecord.Date;
}
I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}
Hi am a fairly novice when it comes to c# and I have being trying to read out a text file then splitting it into sections with classes but have trouble with where to declare them an then how to cycle through the records. here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Windows.Forms;
namespace Assignment_3
{
public partial class Form1 : Form
{
string s;
string ss;
int i = 1;
string infilename;
int num;
SortedList sList = new SortedList();
int x = 0;
public Form1()
{
InitializeComponent();
student myself = new student();
infilename = "text.txt";
StreamReader sr1 = new StreamReader(infilename);
sList.Clear();
while ((s = sr1.ReadLine()) != null)
{
string[] strs = s.Split(',');
myself.firstname = strs[0];
myself.middlename = strs[1];
myself.surname = strs[2];
myself.dob = DateTime.Parse(strs[3]);
myself.dob.ToString(strs[3]);
myself.sex = strs[4];
ss = myself.dob.ToString("u");
sList.Add(myself.firstname, myself);
}
sr1.Close();
num = sList.Count;
student[] pArray = new student[num];
string[] keys = new string[num];
foreach (DictionaryEntry d in sList)
{
keys[x] = (string)d.Key;
pArray[x] = (student)d.Value;
x++;
}
if (i == 0)
{lblmessage.Text = "Already at the first record."; i = 1; }
if (i == num)
{lblmessage.Text = "Already at the last record.";i = num-1; }
lbllastname.Text = pArray[i].surname;
lblfirstname.Text = pArray[i].firstname;
lblsecondname.Text = pArray[i].middlename;
lbldob.Text = pArray[i].dob.ToString();
lblsex.Text = pArray[i].sex;
}
private void btnlast_Click(object sender, EventArgs e)
{
i = num;
}
private void btnfirst_Click(object sender, EventArgs e)
{
i = 0;
}
private void btnnext_Click(object sender, EventArgs e)
{
i++;
}
private void btnprev_Click(object sender, EventArgs e)
{
i--;
}
}
}
and my class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_3
{
class student
{
public string firstname;
public string middlename;
public string surname;
public DateTime dob;
public string sex;
}
}
anyone have any ideas where am going wrong?? I have no errors but find that the text fields do not update with the new record's and then when stepped through the array class holds the correct amount of records and fields, I feel its going to be something very obvious put cant put my finger on it.
Any help would be very appreciated.
You should create new instance of student inside for loop. Because at the moment you have only one instance of student class and all items in SortedList are pointing to same object.
I got a windows form application with a listbox that display content, I wanna be able to move the items from the listbox up and down, when a button is clicked. at the moment the items in the list box stored are in text file, which is loaded into configuration class when the application start. How would I move the items up/down and change the order in the text file?
my main application form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace company1
{
public partial class Form1 : Form
{
List<Configuration> lines = new List<Configuration>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
//Read in every line in the file
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
string[] array = new string[] { "\\n" };
string[] parts = new string[3];
parts = line.Split(array, StringSplitOptions.RemoveEmptyEntries);
lines.Add(new Configuration(parts[0], int.Parse(parts[1]), int.Parse(parts[2])));
line = reader.ReadLine();
}
}
listBox1.DataSource = lines;
listBox1.DisplayMember = "CompanyName";
}
}
}
the configuration class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace company1
{
class Configuration
{
string _CompanyName;
int _Employees;
int _Half;
public Configuration(string companyname, int number_of_Employees, int half)
{
_CompanyName = companyname;
_Employees = number_of_Employees;
_Half = half;
}
//program properties and validation
public string CompanyName
{
set
{
_CompanyName = value;
}
get
{
return _CompanyName;
}
}// End of levelname validation
//program properties and validation
public int EmployeesNumber
{
set
{
_Employees = value;
}
get
{
return _Employees;
}
}// End of levelname validation
//program properties and validation
public int Half
{
set
{
_Half = value;
}
get
{
return _Half;
}
}// End of levelname validation
}
}
any help appreciated, been trying for days to get it work.
// change the items in source list
var tmpLine = lines[10];
lines[10] = lines[9];
lines[9] = tmpLine;
// refresh datasource of listbox
listBox1.DataSource = null;
listBox1.DataSource = lines;
You could define an extension method for list to move items based on index:
public static class ExtensionClass
{
public static void Move<T>(this List<T> list, int index1, bool moveDown = true)
{
if (moveDown)
{
T temp = list[index1];
list[index1] = list[index1 + 1];
list[index1 + 1] = temp;
}
else
{
T temp = list[index1];
list[index1] = list[index1 - 1];
list[index1 - 1] = temp;
}
}
}
Then in Code you can:
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine("Original List");
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 2 Down");
list.Move(2);
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 3 Up");
list.Move(3, false);
foreach (int i in list)
{
Console.Write(i + ",");
}
Output will be:
Original List
1,2,3,4,5,6,7,
Move Index 2 Down
1,2,4,3,5,6,7,
Move Index 3 Up
1,2,3,4,5,6,7,