I convert small html strings to pdf like this:
// set a path to where you want to write the PDF to.
string sPathToWritePdfTo = #"path\new_pdf.pdf";
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
sbHtml.Append("<html>");
sbHtml.Append("<html>");
sbHtml.Append("<body>");
sbHtml.Append("<font size='14'> my first pdf</font>");
sbHtml.Append("<br />");
sbHtml.Append("this is my pdf!!!!");
sbHtml.Append("</body>");
sbHtml.Append("</html>");
// create file stream to PDF file to write to
using (System.IO.Stream stream = new System.IO.FileStream
(sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))
{
// create new instance of Pdfizer
Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();
// open stream to write Pdf to to
htmlToPdf.Open(stream);
// write the HTML to the component
htmlToPdf.Run(sbHtml);
// close the write operation and complete the PDF file
htmlToPdf.Close();
I wonder i can make the above conversion for big html strings,without using the append method.I tried this line:
string sbHtml=File.ReadAllText("mypath/pdf.html");
Instead of this line:
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
but it didn't work:I had an exception in line:
htmlToPdf.Run(sbHtml);
"xmlexception was unhandled bu user code
I also have to mention that the path i read the html file is from my pc!!
It's not from a server or anything else.I would like to get asnwers for both paths.
If the converter has an overload for string, you can simply use:
htmlToPdf.Run(File.ReadAllText(#"mypath/pdf.html"));
If not and accepts only StringBuilder:
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
sbHtml.Append(File.ReadAllText(#"mypath/pdf.html"));
Would this help?
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
sbHtml.Append(File.ReadAllText("mypath/pdf.html"));
In regards to the exception, make sure the HTML is valid XHTML. PDFizer requires valid XHTML.
Related
I'm trying out to use the XML - Mind converter https://www.xmlmind.com/foconverter/ to convert some xsl-fo to an rtf and this works well . Just to be clear this is nothing specific to the conveter or its functionality but just a clarification I would like to get which is why I am asking this on stack overflow .
So I have the following code (that was obtained from some documentation)
string foFilePath = #"D:\Temp\test.fo";
string ourPutFilePath = #"D:\Temp\test.rtf";
Converter converter = new Converter();
converter.OutputFormat = OutputFormat.Rtf;
converter.OutputEncoding = "windows-1252";
converter.ImageResolution = 120;
converter.SetInput(foFilePath);
converter.SetOutput(ourPutFilePath);
converter.Convert();
What happens here is quite simple Reads a file from the input path and stores the converted file in the specified output . The question I would like to clarify here is , wheather it would be possible to store this content that is being saved in the file out put path within a variable as well to may be do some processing during the application runtime ?
Maybe I can use the MemoryStream for it ? I'm just not sure how to do it and would really appreciate some help here.
I understand that I can always read it back from the file output path but I am looking for something better than that as saving the file to a certain location may not always be possible in my case
EDIT :- The converter.SetOutput() method allows 3 overloads in the parameters
String fileName
Stream stream
TextWriter writer
Sine you need the output as a string you could try doing something like this
string content;
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
Converter converter = new Converter();
converter.OutputFormat = OutputFormat.Rtf;
converter.OutputEncoding = "windows-1252";
converter.ImageResolution = 120;
converter.SetInput(foFilePath);
converter.SetOutput(writer);
converter.Convert();
stream.Position = 0;
content = Encoding.UTF8.GetString(stream.ToArray());
}
}
I'm not sure about the Encoding though, and if the Convert() uses a different encoding this might not work
I have a hindi RTF file with content like:
कोलकाता, 11 दिसंबर पश्चिम बंगाल के बर्दवान जिले में कक्षा नौ की एक छात्रा ने फांसी लगाकर आत्महत्या कर ली।
In my console application I want to read that RTF file and Change some content programatically.
I using streamreader to read the file but when converting to string it is producing the following output:
ÚUæCþUèØ-SßæS‰Ø
×Âý Ñ Sßæ§Ù Üê •¤è ¼ßæ ÂØæü# ×æ˜æ ×ð´ ãUôÙð •¤æ ¼æßæ
ÖæðÂæÜ, vv ç¼â¢ÕÚ (¥æ§ü°°Ù°â)Ð ×ŠØ Âý¼ðàæ ×ð´ Sßæ§Ù Üê ¥æñÚ ÇðU¢»ê âð ¥Õ Ì•¤ •¤§ü Üæð»æð´ •¤è ×æñÌ ãUæð ¿é•¤è ãñU ¥õÚU ¥SÂÌæÜ ×ð´ ç¿ç•¤ˆâ•¤èØ âéçßÏæ¥ô´ •¤è •¤×è •ð¤ âæÍ-âæÍ ¼ßæ¥ô´ •ð¤ ¥Öæß •ð¤ Öè ¥æÚUæð ܻÌð ÚãðU ãñU¢Ð
SßæS‰Ø çßÖæ» Ùð ãUæÜæ¢ç•¤ ØãU ¼æßæ 畤Øæ ãñU 畤 Úæ…Ø ×ð´ ×æñâ×è ÚUæð», Sßæ§Ù Üê •ð¤ ©Â¿æÚ •ð¤ çÜ° Âý¼ðàæ •ð¤ ¥SÂÌæÜæð´ ×ð´ ¥æßàØ•¤ ¼ßæ¥æð´ •¤æ ÂØæü# ÂýÕ¢Ï ç•¤Øæ »Øæ ãñUÐ
I have tried the windows form RichTextBox to read the RTF file, but it always show Invalid File Format.
So what will be the best possible solution to read and modify rtf file in C#
StreamReader sr = new StreamReader(fpath, Encoding.Default, true);
string s1 = sr.ReadToEnd();
sr.Close();
also tried
using (System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox())
{
// Get the contents of the RTF file. Note that when it is
// stored in the string, it is encoded as UTF-16.
string s = System.IO.File.ReadAllText(fpath);
// Convert the RTF to plain text.
rtBox.Rtf = s; // error file format invalid
string plainText = rtBox.Text;
}
The RichTextBox control can load an RTF file directly, do not use StreamReader to read RTF file because it can contain a lot of Control Characters.
After loading the file to the RichTextBox, use the Text property to get the plain text of the file.
RichTextBox also has a SaveFile method to save the modified content to a file.
I would like to know the best way to create a simple html file using c#.
Is it using something like System.IO.File.Create?
Something like -
using (FileStream fs = new FileStream("test.htm", FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<H1>Hello</H1>");
}
}
I'll say that File.WriteAllText is a stupid-proof way to write a text file for C# >= 3.5.
File.WriteAllText("myfile.htm", #"<html><body>Hello World</body></html>");
I'll even say that File.WriteAllLines is stupid-proof enough to write bigger html without fighting too much with string composition. But the "good" version is only for C# 4.0 (a little worse version is C# >= 2.0)
List<string> lines = new List<string>();
lines.Add("<html>");
lines.Add("<body>");
lines.Add("Hello World");
lines.Add("</body>");
lines.Add("</html>");
File.WriteAllLines("myfile.htm", lines);
// With C# 3.5
File.WriteAllLines("myfile.htm", lines.ToArray());
I would go with File.Create and then open a StreamWriter to that file if you dont have all the data when you create the file.
This is a example from MS that may help you
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// Create the file.
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Have a look at the HtmlTextWriter class. For an example how to use this class, for example look at http://www.dotnetperls.com/htmltextwriter.
Reading and writing text files and MSDN info. HTML is just a simple text file with *.HTML extension ;)
Simply opening a file for writing (using File.OpenWrite() for example) will create the file if it does not yet exist.
If you have a look at http://msdn.microsoft.com/en-us/library/d62kzs03.aspx you can find an example of creating a file.
But how do you want to create the html file content? If that's just static then you can just write it to a file.. if you have to create the html on the fly you could use an ASPX file with the correct markup and use a Server.Execute to get the HTML as a string.
Yep, System.IO.File.Create(Path) will create your file just fine.
You can also use a filestream and write to it. Seems more handy to write a htm file
this is the code in question:
using (var file = MemoryMappedFile.OpenExisting("AIDA64_SensorValues"))
{
using (var readerz = file.CreateViewAccessor(0, 0))
{
var bytes = new byte[567];
var encoding = Encoding.ASCII;
readerz.ReadArray<byte>(0, bytes, 0, bytes.Length);
File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));
var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
using (var reader = XmlReader.Create("C:\\myFile.txt", readerSettings))
{
This is what myfile.txt looks like:
<sys><id>SCPUCLK</id><label>CPU Clock</label><value>1598</value></sys><sys><id>SCPUFSB</id><label>CPU FSB</label><value>266</value></sys><sys><id>SMEMSPEED</id><label>Memory Speed</label><value>DDR2-667</value></sys><sys><id>SFREEMEM</id><label>Free Memory</label><value>415</value></sys><sys><id>SGPU1CLK</id><label>GPU Clock</label><value>562</value></sys><sys><id>SFREELVMEM</id><label>Free Local Video Memory</label><value>229</value></sys><temp><id>TCPU</id><label>CPU</label><value>42</value></temp><temp><id>TGPU1</id><label>GPU</label><value>58</value></temp>
if i write the data to a txt file on the hard drive with:
File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));
then read that same text file with the fragment XmlReader:
XmlReader.Create("C:\\myFile.txt");
it reads it just fine, the program runs and completes like it supposed to, but then if i directly read with the fragment XmlReader like:
XmlReader.Create(encoding.GetString(bytes));
I get exception when run " illegal characters in path" on the XmlReader.Create line.
ive tried writing it to a separate string first and reading that with xmlreader, and it wouldn't help to try to print it to CMD to see what it looks like because CMD wouldnt show the invalid characters im dealing with right?
but oh well i did Console.WriteLine(encoding.GetString(bytes)); and it precisely matched the txt file.
so somehow writing it to the text file is removing some "illegal characters"? what do you guys think?
XmlReader.Create(encoding.GetString(bytes));
XmlReader.Create() interprets your string as the URI where it should read a file from. Instead encapsulate your bytes in a StringReader:
StringReader sr = new StringReader(encoding.GetString(bytes));
XmlReader.Create(sr);
Here:
XmlReader.Create(encoding.GetString(bytes));
you are simply invoking the following method which takes a string representing a filename. However you are passing the actual XML string to it which obviously is an invalid filename.
If you want to load the reader from a buffer you could use a stream:
byte[] bytes = ... represents the XML bytes
using (var stream = new MemoryStream(bytes))
using (var reader = XmlReader.Create(stream))
{
...
}
The method XmlReader.Create() with a single string as argument needs a URI passed and not the XML document as string, please refer to the MSDN. It tries to open a file named "<..." which is an invalid URI. You can pass a Stream instead.
You are passing the xml content in the place where it is expecting a path, as evidenced by the error - illegal characters in path
Use an appropriate overload, and pass a stream - http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx
I am trying to make a text file in memory, add some lines to it and at the end save the file in a text file. I can handle the savedialog part but I dont know how to get the text file from memory. Any help and tips will be appriciated.
What I am doing so far is:
//Initialize in memory text writer
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
please note
I will call tw.WriteLine() add more lines in different places so I want to save this at end of program (so this shouldent be wrapped between something like using{} )
UPDATE
StringBuilder seems to be a more reliable option for doing this! I get strange cut-outs in my text file when I do it using MemoryStream.
Thanks.
I think your best option here would be to write to a StringBuilder, and when done, File.WriteAllText. If the contents are large, you might consider writing directly to the file in the first place (via File.CreateText(path)), but for small-to-medium files this should be fine.
var sb = new StringBuilder();
sb.AppendLine("HELLO WORLD!");
sb.AppendLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
File.WriteAllText(path, sb.ToString());
Or, something nigh-on the same as #Marc's answer, but different enough that I think it's worth putting out there as a valid solution:
using (var writer = new StringWriter())
{
writer.WriteLine("HELLO WORLD!");
writer.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
File.WriteAllLines(path, writer.GetStringBuilder().ToString());
}
Where path is a string representing a valid file system entry path, predefined by you somewhere in the application.
Assume your SaveFileDialog name is "dialog"
File.WriteAllBytes(dialog.FileName, Encoding.UTF8.GetBytes("Your string"));
or
var text = "Your string";
text += "some other text";
File.WriteAllText(dialog.FileName, text);
also in your own solution you can do this :
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
// just add this
File.WriteAllBytes(dialog.FileName, ms.GetBuffer());
Something like this.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
using (FileStream file = File.CreateText(dlg.FileName)
{
ms.WriteTo(file)
}
}
I haven't worried about whether the file already exists but this should get you close.
You might need a ms.Seek(SeekOrgin.Begin, 0) too.
Another way of appending text to the end of a file could be:
if (saveFileDialog.ShowDialog() == DialogResult.OK) {
using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
writer.WriteLine(text);
}
}
supposing that text is the string you need to save into your file.
If you want to append new lines to that string in an easy way, you can do:
var sb = new StringBuilder();
sb.AppendLine("Line 1");
sb.AppendLine("Line 2");
and the resulting string will be sb.ToString()
If you already have a Stream object (in your example, a MemoryStream), you can do the same but replace the line:
using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
by
using (var writer = new StreamWriter(memoryStream)) {
Edit:
About wrapping the statements inside using:
Take in count that this is not a problem at all. In my first example, all you will have to do is to keep that StringBuilder object, and keep adding lines to it. Once you have what you want, just write the data into a text file.
If you are planning to write more than once to the text file, just clear the StringBuilder everytime you write, in order to not get duplicated data.