How to transfer text from RTF to Word Document in c# - ms-word

hI I need to transfer text from richTextbox to word document and also in plain text on button_click. I need assistance on this please.
I got a vb code but need in csharp.
Dim wrdApp As Word.Application
Private Sub Form_Load()
Set wrdApp = New Word.Application
End Sub
Private Sub Command2_Click()
Clipboard.SetText RichTextBox1.TextRTF, vbCFRTF
With wrdApp
.Documents.Add
.Selection.Paste
.ActiveDocument.SaveAs App.Path & "RTFDOC2.doc", _
wdFormatDocument
.Visible = True
.Activate
End With
End Sub

I found and put the following together based off this site:
object missing = System.Reflection.Missing.Value;
object Visible = true;
object start1 = 0;
object end1 = 0;
Word.Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Word.Range rng = adoc.Range(ref start1, ref missing);
try
{
Clipboard.SetText(richTextBox.Text, TextDataFormat.Rtf);
WordApp.Selection.Paste();
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
object filename = path + #"\MyWord.doc";
adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
WordApp.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

You can call this VBA code using the activeX-IF of msword.

Related

iText7 Merge pdf annotations on a new pdf document

I have multiple copies of a .pdf document that are commented by different users. I would like to merge all these comments into a new pdf "merged".
I wrote this sub inside a class called document with properties "path" and "directory".
Public Sub MergeComments(ByVal pdfDocuments As String())
Dim oSavePath As String = Directory & "\" & FileName & "_Merged.pdf"
Dim oPDFdocument As New iText.Kernel.Pdf.PdfDocument(New PdfReader(Path),
New PdfWriter(New IO.FileStream(oSavePath, IO.FileMode.Create)))
For Each oFile As String In pdfDocuments
Dim oSecundairyPDFdocument As New iText.Kernel.Pdf.PdfDocument(New PdfReader(oFile))
Dim oAnnotations As New PDFannotations
For i As Integer = 1 To oSecundairyPDFdocument.GetNumberOfPages
Dim pdfPage As PdfPage = oSecundairyPDFdocument.GetPage(i)
For Each oAnnotation As Annot.PdfAnnotation In pdfPage.GetAnnotations()
oPDFdocument.GetPage(i).AddAnnotation(oAnnotation)
Next
Next
Next
oPDFdocument.Close()
End Sub
This code results in an exception that I am failing to solve.
iText.Kernel.PdfException: 'Pdf indirect object belongs to other PDF document. Copy object to current pdf document.'
What do I need to change in order to perform this task? Or am I completely off with my code block?
You need to explicitly copy the underlying PDF object to the destination document. After that you will be easily able to add that object to the list of page annotations.
Instead of adding the annotation directly:
oPDFdocument.GetPage(i).AddAnnotation(oAnnotation)
Copy the object to the destination document first, wrap it into PdfAnnotation class with makeAnnotation method and then add it as usual. Code is in Java but you will easily be able to convert it into VB:
PdfObject annotObject = oAnnotation.getPdfObject().copyTo(pdfDocument);
pdfDocument.getPage(i).addAnnotation(PdfAnnotation.makeAnnotation(annotObject));
Here is a working Java code, with annotations copied from one document to other using the copyTo method.
PdfReader reader = new PdfReader(new
RandomAccessSourceFactory().createBestSource(sourceFileName), null);
PdfDocument document = new PdfDocument(reader);
PdfReader toMergeReader = new PdfReader(new RandomAccessSourceFactory().createBestSource(targetFileName), null);
PdfDocument toMergeDocument = new PdfDocument(toMergeReader);
PdfWriter writer = new PdfWriter(targetFileName + "_MergedVersion.pdf");
PdfDocument writeDocument = new PdfDocument(writer);
int pageCount = toMergeDocument.getNumberOfPages();
for (int i = 1; i <= pageCount; i++) {
PdfPage page = document.getPage(i);
writeDocument.addPage(page.copyTo(writeDocument));
PdfPage pdfPage = toMergeDocument.getPage(i);
List<PdfAnnotation> pageAnnots = pdfPage.getAnnotations();
if (pageAnnots != null) {
for (PdfAnnotation pdfAnnotation : pageAnnots) {
PdfObject annotObject = pdfAnnotation.getPdfObject().copyTo(writeDocument);
writeDocument.getPage(i).addAnnotation(PdfAnnotation.makeAnnotation(annotObject));
}
}
}
reader.close();
toMergeReader.close();
toMergeDocument.close();
document.close();
writeDocument.close();
writer.close();

CreateChangesetAsync - How to checkin an existing file without knowing enconding or file type (just file path)

i tried to follow the example on how to create a changeset with multiple files: [See link][1]
Although i am a bit stuck at the TFVCItem and ItemContent stage where i don't know how to extract the content and enconding of my file.
Im trying to write some code in order to checkin a file given to me by a filePath and check it in at a given location.
Would anyone care to help me out on how to do this?
This is what i came up so far:
Public Function CreateChangeset(ByVal projectName As String,
ByVal files As Dictionary(Of String, String),
ByVal comment As String) As TfvcChangesetRef
Dim c = TFSConnection.GetClient(Of TfvcHttpClient)
Dim newChangetset = New TfvcChangeset
Dim changes = New List(Of TfvcChange)
For Each fKP In files
Dim fileSource = fKP.Key
Dim fileTarget = fKP.Value
Dim newChange = New TfvcChange
newChange.ChangeType = VersionControlChangeType.Add
Dim newItem = New TfvcItem
newItem.Path = $"&/{projectName}/{fileTarget}"
newItem.ContentMetadata = New FileContentMetadata
'' TODO: How to extract the correct encoding, and type?...
'newItem.ContentMetadata.Encoding = GetFileEncoding(fileSource)
'newItem.ContentMetadata.ContentType = "text/plain"
'newChange.Item = newItem
'' TODO: How to extract the correct content, and type?...
'Dim newContent = New ItemContent
'newContent.Content = "Blabla"
'newContent.ContentType = ItemContentType.RawText
'newChange.NewContent = newContent
changes.Add(newChange)
Next
newChangetset.Changes = changes
newChangetset.Comment = comment
Dim changesetRef = c.CreateChangesetAsync(newChangetset).Result
Return changesetRef
End Function
UPDATE:
Ok so i managed to make it work but i still am not sure how to properly set the ContentType.
I have the choice between ItemContentType.RawText and ItemContentType.Base64Encoded but i am not sure when to use one or the other.
Here is the new code which seems to work:
Public Function CreateChangeset(ByVal projectName As String,
ByVal files As Dictionary(Of String, String),
ByVal comment As String) As TfvcChangesetRef
Dim c = TFSConnection.GetClient(Of TfvcHttpClient)
Dim newChangetset = New TfvcChangeset
Dim changes = New List(Of TfvcChange)
For Each fKP In files
' Extract and build our target and source paths.
Dim fileSource = fKP.Key
Dim fileTarget = fKP.Value
Dim fileName = IO.Path.GetFileName(fileSource)
Dim newChange = New TfvcChange
' Create the new TFVC item which will be checked-in.
Dim newItem = New TfvcItem
newItem.Path = $"$/{projectName}/{fileTarget}/{fileName}"
newItem.ContentMetadata = New FileContentMetadata
' Try to extract the item from the server.
Dim serverItem = c.GetItemAsync(newItem.Path).Result
If serverItem Is Nothing Then
' If the file is not on the server, then its a new file.
newChange.ChangeType = VersionControlChangeType.Add
Else
' Indicate that we are dealing with a file modification
' and specify which version we are editing.
newChange.ChangeType = VersionControlChangeType.Edit
newItem.ChangesetVersion = serverItem.ChangesetVersion
End If
' Read the file content to a stream.
Using reader = New StreamReader(fileSource,
Text.Encoding.Default,
True) ' This last parameter allows to extract the correct encoding.
Dim fileContent As String = String.Empty
' Read all the file content to a string so that we can store
' it in the itemcontent.
' NOTE: reading it also allows to retrieve the correct file enconding.
If reader.Peek() >= 0 Then
fileContent = reader.ReadToEnd
End If
' Set the file enconding and MIME Type.
newItem.ContentMetadata.Encoding = reader.CurrentEncoding.WindowsCodePage
newItem.ContentMetadata.ContentType = System.Web.MimeMapping.GetMimeMapping(fileSource)
newChange.Item = newItem
' Set the file content.
Dim newContent = New ItemContent
newContent.Content = fileContent
' TODO: What should be the logic to set the Content Type? Not too sure...
' If newItem.ContentMetadata.ContentType.StartsWith("text/") Then
newContent.ContentType = ItemContentType.RawText
' Else
' newContent.ContentType = ItemContentType.Base64Encoded
' End If
' Store the content to the change.
newChange.NewContent = newContent
End Using
changes.Add(newChange)
Next
newChangetset.Changes = changes
newChangetset.Comment = comment
Dim changesetRef = c.CreateChangesetAsync(newChangetset).Result
Return changesetRef
End Function

OpenXML c++/cli

I want to create a .docx document (Word 2007 and 2010) with OpenXML in C++/CLI
I use this code for generate the document:
WordprocessingDocument^ wordDoc = WordprocessingDocument::Create("C:\\...\MyFile.docx", WordprocessingDocumentType::Document);
MainDocumentPart^ mainPart = wordDoc->AddMainDocumentPart();
Document^ elt = gcnew Document( gcnew Body( gcnew Paragraph( gcnew Run( gcnew DocumentFormat::OpenXml::Wordprocessing::Text("Hello !") ) ) ) );
elt->Save(mainPart);
mainPart->Document->Save();
wordDoc->Close();
The file is created but it is empty.
If I write this code in C#, the file is good and it contains the text.
Why my code in C++/cli, create the file (MyFile.docx) with no text?
I repro this problem. Not sure what is going on, this syntax is documented to work. It works properly when you write the code explicitly, using the AppendChild() method. Like this:
WordprocessingDocument^ wordDoc = WordprocessingDocument::Create("C:\\temp\\MyFile.docx", WordprocessingDocumentType::Document);
MainDocumentPart^ mainPart = wordDoc->AddMainDocumentPart();
mainPart->Document = gcnew Document;
Body^ body = mainPart->Document->AppendChild(gcnew Body);
Paragraph^ para = body->AppendChild(gcnew Paragraph);
Run^ run = para->AppendChild(gcnew Run);
run->AppendChild(gcnew DocumentFormat::OpenXml::Wordprocessing::Text("Hello !"));
delete wordDoc;

How to generate word document in windows server 2003?

I had written a function to generate a word document by using the Office Interop Word object. My code is as shown below. It is working fine in my local system. But when i try to run it from window server 2003 it is not working. It keeps loading at Word.Document wordDoc = wordApp.Documents.Open and doesn't do anything. Could you help me out?
private void GenerateEmploymentCertificate()
{
object Nothing = System.Reflection.Missing.Value;
object format = Word.WdSaveFormat.wdFormatDocument;
Word.Application wordApp = new Word.ApplicationClass();
object srcFileName = Server.MapPath(ResolveUrl(#"~/HRLetter\Arabia\Templates\Employment Certificate.doc"));
Word.Document wordDoc = wordApp.Documents.Open
(ref srcFileName, ref format, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing);
try
{
object bookmarkDate = "Date";
wordDoc.Bookmarks.get_Item(ref bookmarkDate).Select();
wordApp.Selection.Text = string.Format("{0:MM/dd/yyyy}", lblRequestdate.Text);
object bookmarkEmployeeName = "EmployeeName";
wordDoc.Bookmarks.get_Item(ref bookmarkEmployeeName).Select();
wordApp.Selection.Text = lblEmployeeName1.Text;
object bookmarkCompany = "Company";
wordDoc.Bookmarks.get_Item(ref bookmarkCompany).Select();
wordApp.Selection.Text = lblCompanyName1.Text;
object bookmarkJoiningDate = "JoiningDate";
wordDoc.Bookmarks.get_Item(ref bookmarkJoiningDate).Select();
wordApp.Selection.Text = string.Format("{0:MM/dd/yyyy}", lblJoiningDate1.Text);
object bookmarkDesignation = "Designation";
wordDoc.Bookmarks.get_Item(ref bookmarkDesignation).Select();
wordApp.Selection.Text = lblDesignation1.Text;
string DocName;
DocName = string.Format("{0}_employment_certificate", lblRequestNo.Text);
hFilename.Value = DocName;
wordDoc.SaveAs(Server.MapPath(ResolveUrl(#"~/HRLetter\Arabia\Letters\" + DocName + ".doc")));
}
catch (Exception exp)
{
Session["generalError"] = null;
Session["generalError"] = "There was an error at generating the letter. Please send email to unify.admin#unilever.com with this screen shot.<br /><br /><br />Request No:" + lblRequestNo.Text + "<br />Action:Submit<br />" + exp.StackTrace.ToString();
LogManager logHelper = new LogManager(Request.PhysicalApplicationPath.Trim(), "Leave System - Malaysia");
logHelper.LogError("[btnSubmit_Click - ]" + exp.Message + ".StackTrace - " + exp.StackTrace.ToString());
Response.Redirect(ResolveUrl("~/Error/ErrorHandler.aspx"));
}
finally
{
// Close wordDoc2
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
if (wordDoc != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
wordDoc = null;
}
// close wordApp
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
if (wordApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
}
GC.Collect();}
MS office doesn't really work in server environment. Even MS says so.
We've made it work with LibreOffice. You can read it on our blog

CommandBars.FindControl throwing an exception

I am trying to use the FindControl Method of the CommandBars object in a VSTO Word addin to get what else a command bar object
Code is as follows
private void WireContextMenu(string MenuID,string Tag, string ID, ref Office.CommandBarButton Control)
{
try
{
object missing = System.Type.Missing;
Control = (Office.CommandBarButton)this.Application.CommandBars[MenuID].FindControl((object)Office.MsoControlType.msoControlButton, ID, Tag, missing, missing);
if (Control == null)
{
Control = (Office.CommandBarButton)this.Application.CommandBars[MenuID].Controls.Add(Office.MsoControlType.msoControlButton, ID, missing, missing, missing);
Control.Caption = "Biolit Markup Selection";
Control.Tag = Tag;
}
Control.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.cb_Click);
}
catch (Exception Ex)
{
}
}
The FindControl method is throwing a Type Mismatch Exception (-2147352571)
Any ideas
is this the right way anyhow to add a item to the right click menu of word and then make sure you dont add it if it already exists
Thanks
you are using Missing where Missing is not allowed as parameter
ref: link text
http://msdn.microsoft.com/en-us/library/system.type.missing.aspx
use code like this:
object type = MsoControlType.msoControlPopup;
object id = 1;
object tag = null;
object visible = 1;
object recusive = false;
//object missing = System.Type.Missing;
CommandBarControl barControl = popParent.FindControl(type, id, tag, visible, recusive);