How to add header and footer txt file in C#? - c#

I want to add a header and footer inside of my text file. How can i do that? My target should like This:
tr.AddHeaderAndFooter("Header","footer";
For example:
using (var fileStream = new FileStream(ConfigurationManager.AppSettings["TargetDir"] + swiftFile, FileMode.Open, FileAccess.Read))
{
TextReader tr = new StreamReader(fileStream);
tr.AddHeaderAndFooter("Header","footer";
}

A .txt file does not have a header or footer.
But you can simulate this behaviour with the following code sample:
// since there is no predefined method to add a string into the beginning
// of a file, you have to first read the whole file content into a temporary
// variable
string currentContent = String.Empty;
if (File.Exists(filePath))
{
currentContent = File.ReadAllText(filePath);
}
// now you can put your header into the beginning of the file so:
string header = "My Header";
File.WriteAllText(filePath, header + Environment.NewLine + currentContent );
// and finally you use the append method to add footer to the end of the file
string footer = "My Footer";
File.AppendAllText(filepath, Environment.NewLine + footer);

Do you mean something along the lines of:
string text = "header" + Environment.NewLine + "rest of file ... asjdhakjdh" + Environment.NewLine + "footer";
File.WriteAllText("filename.txt", text);
This will save
header
rest of file ... asjdhakjdh
footer
in a .txt file named filename.txt
So you could read your file, store it in a string, add your header and footer line and write it back to the same file it came from.

Related

Convert bytes to PDF File

I am able to create a word doc using the code below.
Question: how do i create a pdf instead of word doc?
Code
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, tdindb.TDCode + "-test.doc")))
{
string html = string.Format("<html>{0}</html>", sbHtml);
outputFile.WriteLine(html);
}
string FileLocation = docPath + "\\" + tdindb.TDCode + "-test.doc";
byte[] fileBytes = System.IO.File.ReadAllBytes(FileLocation);
string fileName = Path.GetFileName(FileLocation);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
Thank you
You need to use one of PDF creating libraries. I tried to use iText , IronPDF, and PDFFlow. All of them create PDF documents from scratch.
But PDFFlow was better for my case because i needed automatic page creation and multi-page spread table)
This is how to create a simple PDF file in C#:
{
var DocumentBuilder.New()
.AddSection()
.AddParagraphToSection("your text goes here!")
.ToSection()
.ToDocument()
.Build("Result.PDF");
}
feel free to ask me if you need more help.
Converting a Word document to HTML has been answered here before. The linked example is the first result of many on this site.
Once you have your HTML, to create a PDF you need to use a PDF creation library. For this example we will use IronPDF which requires just 3 lines of code:
string html = string.Format("<html>{0}</html>", sbHtml);
var renderer = new IronPdf.ChromePdfRenderer();
// Save PDF file to BinaryData
renderer.RenderHtmlAsPdf(html).BinaryData;
// Save file to location
renderer.RenderHtmlAsPdf(html).SaveAs("output.pdf");

Reading a CSV file in C# correctly for a print preview

First of all, I'm using a csv file to store data from a DataGridView into it. Now I'm trying to show a printPreview with the data in the csv file. I'm using this:
public void ReadDocument()
{
string docName = #"printDataGridView.csv";
string docPath = Directory.GetCurrentDirectory();
form1.printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + #"\" + docName, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
{
form1.documentContents = reader.ReadToEnd();
}
form1.stringToPrint = form1.documentContents;
}
My problem is that I'm getting a print preview where the values are just listed seperated by semicolons. Want I need is to show the data like it is displayed in the CSV file - tabularly and "clean". So one column with the header and it's values right under it, then the second column and so on...
Is this possible somehow?

How to merge multiple RTF files into one RTF in C#

I'm trying to merge multiple rtf documents into one. the size of the merged is increased (size of all the documents) but when i open, i could see only the first RTF file content only.
string srcpath = #"C:\CSI\RTFtest\src\";
string despath = #"C:\CSI\RTFtest\dest\single.rtf";
string content = "";
List<string> files = new List<string>(Directory.GetFiles(srcpath, "*.rtf"));
StreamReader read;
if (files.Count > 1)
{
for (int i = 0; i < files.Count; i++)
{
String filename = files[i];
content = File.ReadAllText(filename);
//content = content + read.ReadToEnd();
File.AppendAllText(despath, content.ToString());
File.AppendAllText(despath, System.Environment.NewLine);
}
RTF Files are not text files. You can't jsut concatenate the text as there are headers and other structures involved. You can read all about this spec here http://support.microsoft.com/kb/86999 (yuck).
You can use a TextRange object if you're using wpf, load the first file into it then append each additional file's content. Or you could read files into richtextbox objects in winforms and append the content (how to load: http://msdn.microsoft.com/en-us/library/1z7hy77a.aspx).
I guess you could use TextBox1.Rtf = TextBox1.Rtf + textBox2.rtf untill all are loaded since the rtf property is the string with rtf encoding in it.
Use StringBuilder. You can append RTF to RTF.
Example:
StringBuilder sb = new StringBuilder();
sb.Append(#"{\rtf1\ansi");
sb.Append(#"...
HPIrichTextBox.Rtf = sb.ToString();

XMLWriter issues in C#

My issue is that I can't have the XML's file name be saved based on the text of a given field: here is the line:
XmlTextWriter writer = new XmlTextWriter(#"{0}\ops\op-" + OpName.Text.Replace(" ", "_") + ".xml",
System.Text.Encoding.UTF8);
The issue I get is that it can't find the path: C:\[stuff]\{0}\op\op-.xml and if I remove the {0}(in the code) I get can't find C:\op\op-.xml
I am needing it to find C:\[stuff]\op\ so it can make the file in that folder.
How could I change this line?
What does {0} represents in your path? XmlTextWriter constructor takes file path, not a formatted string. It would be much more readable if you'd prepare your file path in steps, eg. by utilizing Path.Combine method:
var fileName = string.Format("op-{0}.xml", OpName.Text.Replace(" ", "_"));
var rootDir = /* this would be {0} from your original example */
var filePath = Path.Combine(rootDir, "ops", fileName);
XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
string additionalStr=OpName.Text.Replace(" ", "_");
if (string.IsNullOrEmpty(additionalStr))
{
return;
//or throw error or make default file name depending on the required logic
}
string directoryPath=String.Format(#"{0}\ops\",dirPrefix);
bool isDirectoryExists=Directory.Exists(directoryPath);
if (!isDirectoryExists){
//required logic. for example set default directory
}
string fileName=additionalStr+".xml";
string filePath=Path.Combine(directoryPath,fileName);
XmlTextWriter writer = new XmlTextWriter(filePath,System.Text.Encoding.UTF8);

Convert blank .txt file to PDF in C#

I am converting a .txt to .pdf in c#. This works fine if the .txt file is not blank. if it is, it threw an error of "The document has no pages".
The pdf gets generated but threw an error of "There was an error opening this document. The file is damaged and could not be repaired" when opening a pdf file.
Code is seen below
public void converttxttoPDF(string sourcePath, string destPath)
{
try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
string filename = Path.GetFileNameWithoutExtension(sourcePath);
System.IO.StreamReader myFile = new System.IO.StreamReader(sourcePath);
string myString = myFile.ReadToEnd();
myFile.Close();
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
document.Open();
document.Add(new iTextSharp.text.Paragraph(myString));
document.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
let me know if any info needed.
thanks
You need to add some content to the pdf. So try this:
myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));
You need to convince iText that there IS something on that page.
Two Methods:
Be explicit. writer.setPageEmpty(false);
Trick it (which is what Darin suggests). writer.getDirectContent().setLiteral(" ");

Categories