I am Trying to Insert HTML Text Inside Apache Open Office .odt File
I try Statement with Bold as show Below but it is not Working.
Is There I am missing Something ?
XComponentContext oStrap = uno.util.Bootstrap.bootstrap();
XMultiServiceFactory oServMan = (XMultiServiceFactory)oStrap.getServiceManager();
XComponentLoader oDesk = (XComponentLoader)oServMan.createInstance("com.sun.star.frame.Desktop");
string url = #"private:factory/swriter";
PropertyValue[] propVals = new PropertyValue[0];
XComponent oDoc = oDesk.loadComponentFromURL(url, "_blank", 0, propVals);
string docText = "<b>This will</b> be my first paragraph.\n\r";
docText += "This will be my second paragraph.\n\r";
((XTextDocument)oDoc).getText().setString(docText);
string fileName = #"C:\test.odt";
fileName = "file:///" + fileName.Replace(#"\", "/");
((XStorable)oDoc).storeAsURL(fileName, propVals);
((XComponent)oDoc).dispose();
oDoc = null;
Output:
As answered already in the other question - you have to use character properties to get bold (or otherwise attributed) text
Related
This block of code throws an error called file name is invalid.
I want to create a folder named as "test" inside this there will be another folder named as today's date "date" , i want to keep the the word document inside this date folder, please help.
public string File_path;
public string docfile_path;
public string filename;
private void button1_Click(object sender, EventArgs e)
{
string time = DateTime.Now.ToString("HH.mm.ss");
string date = DateTime.Today.ToShortDateString();
docfile_path = File_path+ "test" + date;
Directory.CreateDirectory(docfile_path);
filename = docfile_path + "worddoc"+"-" +".docx";
Word.Application app = new Word.Application();
Word.Document doc = new Word.Document();
try
{
doc = app.Documents.Open(filename);
}
catch
{
}
Word.Paragraph oPara1;
oPara1 = doc.Content.Paragraphs.Add();
oPara1.Range.Text = "Test Result";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24;
oPara1.Range.InsertParagraphAfter();
oPara1.Range.InsertParagraphAfter();
Word.Paragraph oPara2;
oPara2 = doc.Content.Paragraphs.Add();
oPara2.Range.Text = "Test Name";
oPara2.Range.Font.Bold = 1;
oPara2.Format.SpaceAfter = 24;
oPara2.Range.InsertParagraphAfter();
doc.SaveAs2(filename);
doc.Close();
doc = null;
app.Quit();
app = null;
}
Surprisingly enough, this code compile and run, but the outcome is not what you probably wanted.
A couple of things is wrong in this code:
1.you cant add strings like that to create a path, a path should be created with the '/' symbol between directories.
this is a legal path:
string path = #"C:\Users\username\Desktop\Games";
this is not :
string path = #"C:UsersusernameDesktopGames";
you can fix it by using the Path.Combine function as follow:
docfile_path = Path.Combine(File_path , "test" , date);
be sure to this for all path strings (including File_path that is value is not shown in the code above).
2.you should use
Document doc = app.Documents.Add();
to create a new Word document and not
Document doc = new Document();
3.you should use a different format for string date, DateTime.ToShortDateString() is dividing the date with the '/' symbol which will create new folders.
try using:
string date = DateTime.Today.ToString("dd.MM.yyyy");
4.I don't see any reason for the line
doc = app.Documents.Open(filename);
You are trying to open the the file that you intent to create?
here is the code i used:
string File_path = #"C:\Users\yakir\Desktop";
string docfile_path;
string filename;
string time = DateTime.Now.ToString("HH.mm.ss");
string date = DateTime.Today.ToString("dd.MM.yyyy");
docfile_path = Path.Combine(File_path , "test" , date);
Directory.CreateDirectory(docfile_path);
filename = Path.Combine(docfile_path, "worddoc" + "-" + ".docx");
Application app = new Application();
Document doc = app.Documents.Add();
Paragraph oPara1;
oPara1 = doc.Content.Paragraphs.Add();
oPara1.Range.Text = "Test Result";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24;
oPara1.Range.InsertParagraphAfter();
oPara1.Range.InsertParagraphAfter();
Paragraph oPara2;
oPara2 = doc.Content.Paragraphs.Add();
oPara2.Range.Text = "Test Name";
oPara2.Range.Font.Bold = 1;
oPara2.Format.SpaceAfter = 24;
oPara2.Range.InsertParagraphAfter();
doc.SaveAs2(filename);
doc.Close();
doc = null;
app.Quit();
app = null;
}
So this code down here works fine, it does the job, word -> PDF.
Only got a problem, when the word doc has tables with united cells, when converting the word doc to pdf the pdf show the united cells combine but with no value inside.
Someone knows why? Is the any solution for this?
NOTE: This is converting on server side.
if (nomeDocTemplate == attachment)
{
web.AllowUnsafeUpdates = true;
string wordEdit =item2.Attachments.UrlPrefix + "Template" + item.ID + ".docx";
string wordAutomationServiceName = "Word Automation Services";
string filenamedest = web.Url + item.File.ServerRelativeUrl;
SPFile attachmentFile = item2.Web.GetFile(wordEdit);
using (MemoryStream destinationStream = new MemoryStream())
{
//Call the syncConverter class, passing in the name of the Word Automation Service for your Farm.
SyncConverter sc = new SyncConverter(wordAutomationServiceName);
////Pass in your User Token or credentials under which this conversion job is executed.
sc.UserToken = SPContext.Current.Site.UserToken;
sc.Settings.UpdateFields = true;
//Save format
sc.Settings.OutputFormat = SaveFormat.PDF;
////Convert to PDF by opening the file stream, and then converting to the destination memory stream.
ConversionItemInfo info = sc.Convert(attachmentFile.OpenBinaryStream(), destinationStream);
var filename = Path.GetFileNameWithoutExtension(item.File.Name) + ".pdf";
if (info.Succeeded)
{
//File conversion successful, then add the memory stream to the SharePoint list.
SPFile newfile = web.Lists["Tramitar"].RootFolder.Files.Add(filename, destinationStream, true);
}
else if (info.Failed)
{
throw new Exception(info.ErrorMessage);
}
}
//ConcatAndAddContent(anexosProcesso);
return;
}
Here is the doc and the pdf, to understand better the problem I'm having:
WORD:
PDF:
I want to convert my resulting txt file into a UTF8 formatted file so I can load it into my Azure SQL DW via Polybase. It is required the source file be in UTF8.
MSDN has an "IO Streaming example" HERE works perfectly for a single job. I am trying to architect an SSIS solution for around 30 tables though. I believe using this method would cause a race condition where the PS script will be locked by 1 SSIS package when another SSIS package needs it.
I am a sql dev, not a .NET dev so please forgive me. How would one convert the above to an SSIS C# Script task assuming I know how to pass parameters into the Script task?
PowerShell Code from MSDN
#Static variables
$ascii = [System.Text.Encoding]::ASCII
$utf16le = [System.Text.Encoding]::Unicode
$utf8 = [System.Text.Encoding]::UTF8
$ansi = [System.Text.Encoding]::Default
$append = $False
#Set source file path and file name
$src = [System.IO.Path]::Combine("<MySrcFolder>","<MyUtf8stage>.txt")
#Set source file encoding (using list above)
$src_enc = $ascii
#Set target file path and file name
$tgt = [System.IO.Path]::Combine("<MyDestFolder>","<MyFinalstage>.txt")
#Set target file encoding (using list above)
$tgt_enc = $utf8
$read = New-Object System.IO.StreamReader($src,$src_enc)
$write = New-Object System.IO.StreamWriter($tgt,$append,$tgt_enc)
while ($read.Peek() -ne -1)
{
$line = $read.ReadLine();
$write.WriteLine($line);
}
$read.Close()
$read.Dispose()
$write.Close()
$write.Dispose()
Update
I found a similar post which I was able to tweak to my needs, I swear I searched high and low before posting. Anyway here is what IS working for me. If you see anyway to improve it please share:
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Your code indicates that your are trying to convert an ASCII file to UTF-8 however that article also states the following:
As UTF-8 uses the same character encoding as ASCII PolyBase will also
support loading data that is ASCII encoded.
So my advice to you is to try the file first with Polybase, check for any conversion issues before you spend any time trying to convert the files.
var mySrcFolder = ""; // something from user variables?
var myUtf8stage = ""; // something from user variables?
var myFinalstage = ""; // something from user variables?
// Static variables
var ascii = System.Text.Encoding.ASCII;
var utf16le = System.Text.Encoding.Unicode;
var utf8 = System.Text.Encoding.UTF8;
var ansi = System.Text.Encoding.Default;
var append = false;
// Set source file path and file name
var src = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myUtf8stage));
// Set source file encoding (using list above)
var src_enc = ascii;
// Set target file path and file name
var tgt = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myFinalstage));
// Set target file encoding (using list above)
var tgt_enc = utf8;
using (var read = new System.IO.StreamReader(src, src_enc))
using (var write = new System.IO.StreamWriter(tgt, append, tgt_enc))
{
while (read.Peek() != -1)
{
var line = read.ReadLine();
write.WriteLine(line);
}
}
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Dim strTestExample As String
Private colTestExample As Collection
If(FileExists(strFullFile) Then
Open strTestExample For Input As #intFILE
Do While Not EOF(intTEST)
Input #intFILE, strFirstName, strLastName, strFavColor, strAge
Set objTestObject = New PracticeExample
With objTestObject
.FirstName = strFirstName
.LastName = strLastName
.FavColor = strFavColor
.Age = strAge
colTestExample.Add objTestObject, .FirstName
End With
Loop
Close #intFILE
End If
After numerous attempts to recreate this in C# its time that I consult the almighty powers. I have tried using FileSystemObject to open and write to the file. I am attempting to port this over to C#. I believe without checking i am working in .NET 4.0.
If you would like some further elaboration, just ask below. The contents are being input to a .txt file.
C# Attempt:
string Path;
string FullFile;
const string FileName = "People.txt";
TextStream TS;
FileSystemObject FSO = new FileSystemObject();
PracticeExample objTestObject = new PracticeExample();
Path = AppDomain.CurrentDomain.BaseDirectory;
File = FileSystem.FreeFile();
FullFile = Path + "\"" + FileName;
if (File.Exists(FullFile) == true)
{
FileSystem.FileOpen(File, strFirstName, strLastName, strFavColor, strAge);
TS = FSO.OpenTextFile(File.ToString(), IOMode.ForWriting, true);
FSO.
objTestObject.FirstName = strFirstName;
objTestObject.LastName = strLastName;
objTestObject.FavColor = strFavColor;
objTestObject.Age = strAge;
HashTableRouteDefinitions.Add(objTestObject,objTestObject.FirstName);
FileSystem.FileClose(File);
}
I have getters and setters on within PracticeExample.(WARNING, unfinished code.)
I use outlook Redemption dll for creating outlook message template with c# language.
Below is my code:
RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");
RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");
Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();
var msg = session.GetMessageFromMsgFile(templatePath);
msg.Subject = String.Format("Report");
String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;
RDOAttachment Attach = msg.Attachments.Add(ImageString);
Attach.ContentID = "image1";
String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";
msg.HTMLBody = htb;
msg.Save();
msg.SaveAs(newPath);
Everything work and image is saved to new location. But when i check that message template, i could not see Image anywhere. instead of image it gives me error.
Update
Instead of embedded image , I tried just to attach this file. But when I open file I didn't see any attachment. I check Total Attachments with OutlookSpy, It shows me 0 attachment. Does my code wrong for attachment?
I found solution for this. I need to call session two time. First time to save attachment to my template file and than again to create new instance of it. Below is my code:
RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");
RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");
Interop.Redemption.RDOSession session1 = RedemptionLoader.new_RDOSession();
var msg1 = session1.GetMessageFromMsgFile(templatePath);
msg1.Subject = String.Format("Report");
String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;
RDOAttachment Attach = msg1.Attachments.Add(ImageString);
Attach.ContentID = "image1";
String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";
msg1.HTMLBody = htb;
msg1.Save();
Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();
var msg = session.GetMessageFromMsgFile(templatePath);
msg.SaveAs(newPath);
This works for me.