I have created a Word add-in. I want to read an active word document which is currently open(Content of word document story) by pressing a button which is on window form, and window form get open by click on the button from the ribbon. So let me be clear that how flow happens.
Ribbon -> Button on Ribbon (click it) -> A window form open (Having a button to read active document content) -> Reads the document.
I have tried to access document content by WordOpenXML property and the second method I've tried is to access paragraphs of the active document.
Try 1: Accessing paragraphs
private async Task<bool> SaveDocToCryptacomm1(string fileName)
{
[...some code here...]
StringBuilder sb = new StringBuilder();
long paraCount = application.ActiveDocument.Paragraphs.Count;
while (i < paraCount) {
sb.Append(application.ActiveDocument.Paragraphs[i].Range.Text);
}
[...some code here...]
}
Try 2: Accessing content from WordOpenXML property.
private async Task<bool> SaveDocToCryptacomm1(string fileName)
{
[...some code here...]
Encoding.Default.GetBytes(application.ActiveDocument.WordOpenXML);
[...some code here...]
}
Result of Try 1:
Document get saved successfully but no content is there.
Result of Try 2:
Document get saved successfully but when I try to open it, it is corrupted.
In this case, what should i do, to read active document from Window form button click event.
Does the Microsoft.Office.Interop.Word.Application.ActiveDocument will work? Am I doing something wrong or what?
Edit: Need to do this, without saving open document on local drive and Provided code I have written on Window form's button click event. Will it work?
Related
I have built a Winforms Application using .NET 4.7.2 and CEFSharp 84.4.10.
I have a website loaded that has links to various files PDF, TXT, DOCX etc...
The html for the links is like this:
icon_here
So when I click on a link to a docx for example, it CEFSharp opens a blank window over the top of my application and then opens the save file dialogue. When you press Save on the file dialogue it closes but the blank window stays open.
I want to do the following:
Not have the blank window open.
Detect the file type/mime being downloaded (my app only loads my site), and if they are PDF, TXT or DOCX then automatically download to a temp location, without showing the save dialogue, and open in the OS default viewer.
If not one of the above types then show the Save file dialogue and let user download to where they want.
I can work out how to open a file in the default OS viewer separately, I want to focus on automatic download of specific file types here.
I have spent hours searching for examples of how to do this and come up empty handed.
I was thinking I would be able to detect the type of file in DownloadHandler.OnBeforeDownload, and then based on the following post, just set showDialogue to false in the callback and then in DownloadHandler.OnDownloadUpdated detect downloadItem.IsComplete and then launch the file if it is of the correct type.
Force CEFSharp to download without showing dialog
However when I tried this I ran into the following issues:
The blank window still opens and stays open.
I find that if I set a break point in DownloadHandler.OnDownloadUpdated that I can see the ReceivedBytes go from zero to the TotalBytes, and InProgress being true, and then as I keep pressing F5 to continue ReceivedBytes changes back to zero, and InProgress is false, but IsComplete and IsCanceled remain false the entire time. I would have expected that once the download completed IsComplete would have been true.
I am enjoying working with CEFShap and any direction or examples that could be provided would be much appreciated.
Thanks for your time.
UPDATE 1:
The code I have tried as as follows:
NOTE: I found that after assigning a path to the callback.Continue in OBeforeDownload it fixed the IsComplete not being set to true issue. However the issue of the blank window opening remains.
In winform hosting CEFSharp I have initialised the control as follows:
browser = new ChromiumWebBrowser("https://localhost:44393/Default.aspx");
var downloadHandler = new DownloadHandler();
browser.DownloadHandler = downloadHandler;
In DownloadHandler.cs:
public class DownloadHandler : IDownloadHandler
{
public event EventHandler<DownloadItem> OnBeforeDownloadFired;
public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
public void OnBeforeDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
{
OnBeforeDownloadFired?.Invoke(this, downloadItem);
if (!callback.IsDisposed)
{
using (callback)
{
//TODO: Detect file Type/Mime and auto download or show Save File dialogue as needed here
callback.Continue(Path.Combine(#"C:\Temp", downloadItem.SuggestedFileName), showDialog: false); // set to false so we don't show
}
}
}
public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{
OnDownloadUpdatedFired?.Invoke(this, downloadItem);
if (downloadItem.IsComplete)
{
//TODO: Detect File Type/Mime and automatically open in default OS viewer
}
}
}
I've developed a VSTO Add-In. I've created a Ribbon, which makes a search button appearing into MS Word's Add-In tab.
This Search button opens a Window which allows users to Search the Document from Cloud and Open/ Download the Same.
I want to open the document being searched and downloaded from the cloud to be opened into existing MS Word Window.
My Logic is:
When selected document is downloaded by user. I'm copying it in the Local Directory and trying to open the same.
Sample Code:
public void OpenDocument(string documentPath, Form form)
{
_searchForm.Close();
_searchForm.Dispose();
Word.Document newDoc = Globals.ThisAddIn.Application.Documents.Open(documentPath);
newDoc.Activate();
}
But, I'm getting following exception.
You cannot close Microsoft Word because a dialog box is open. Click OK, switch to Word, and then close the dialog box.
Opening the document in active window of MS Word is not possible. But, I could manage to use a work around to achieve the same.
When any new document is being opened through MS Word, I'm checking, if the parent window (Active Window) is blank, then
I'm adding the new document to be opened
Then, I'm closing the active window (after checking, if it's blank).
Sample Code
//Get the active document.
Word.Document activeDocument = Globals.ThisAddIn.Application.ActiveDocument;
//Check, if Active Window is blank, then we can close it. Once the new Window is Opened. If not,
//we'll open the document in new window
bool closeParentWindow = activeDocument.Content.End - activeDocument.Content.Start == 1 ;
string activeDocName = activeDocument.Name;
//Add the new document which's supposed to open
Word.Document newDoc = this.Application.Documents.Add(path, System.Type.Missing, System.Type.Missing);
newDoc.ActiveWindow.Caption = matterDocument.Document.Name;
if (closeParentWindow)
{
//If Earlier Window/ Document Could be closed. Then need to invoke Close
Word._Document docToClose = Application.Documents[activeDocName] as Word._Document;
docToClose.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
I have a menustrip that has a tab I have created to be labeled "Contents". I want to be able to click on the Content tab and a window pop up with a pdf file listing the contents. I have the pdf file that lists the contents saved to my desktop. Is there a way to add this pdf file to visual studio so that when I click on the Content tab, the pdf file will be opened?
I do not want to have to click another button to search my computer for the file such as using OpenFileDialog. I just want to click the Contents tab and have it open a window with the pdf file.
There are multiple ways of doing that.
1) One way would be to launch a process from your app that will open the default registered viewer of PDF files (such as Adobe Reader) on your PC and pass the full path to the PDF file as a parameter:
Here you can find out ho to determine the path to the default handler application by file extension (".pdf" in your case):
http://www.pinvoke.net/default.aspx/shlwapi/AssocQueryString.html
string execPath = GetAssociation(".pdf");
Once you know the path to the executable, you can launch it with a path to your PDF file as a parameter:
using System.Diagnostics;
...
// Start new process
Process.Start(execPath, "C:\\myfile.pdf").WaitForExit(0);
2) Another way would be to create a Windows form in your app and add web browser control to it. The web browser control can then be programmatically "navigated to" your specific PDF file. That is assuming that your Internet Explorer can display PDF files already by using something like Adobe Reader within its window, i.e. as an inline attachment:
Add a reference from your project to Microsoft Internet Controls 1.1 (Right-click on References > Add reference... > COM).
In your form code (here panePdfViewer is a placeholder System.Windows.Forms.Panel control):
private AxSHDocVw.AxWebBrowser axWebBrowser;
...
private void InitializeWebControl()
{
this.SuspendLayout();
this.axWebBrowser = new AxSHDocVw.AxWebBrowser();
((ISupportInitialize)(this.axWebBrowser)).BeginInit();
this.axWebBrowser.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom)
| AnchorStyles.Left)
| AnchorStyles.Right)));
this.axWebBrowser.Enabled = true;
this.axWebBrowser.Location = this.panelPdfViewer.Location;
this.axWebBrowser.Size = this.panelPdfViewer.Size;
((ISupportInitialize)(this.axWebBrowser)).EndInit();
this.axWebBrowser.Visible = false;
this.Controls.Add(this.axWebBrowser);
this.ResumeLayout(false);
}
and then:
// Clear browser
object blank = "about:blank";
this.axWebBrowser.Navigate2(ref blank);
// Display file
object loc = "file:///" + System.IO.Path.GetFullPath(fileName).Replace('\\', '/');
object null_obj_str = null;
object null_obj = null;
this.axWebBrowser.Navigate2(ref loc, ref null_obj, ref null_obj, ref null_obj_str, ref null_obj_str);
3) A third way is to use a third party control library that can display PDF files.
I have some trouble using the webbrowser control in C#, especially when I print it. The thing is, I have a Barcode in my html file and I have to print it (I use a font to create the code). When I open the html file with Firefox or any other Web browser, my barecode is good and I can scan it. But, when I open my file with my webbrowser in c#, or when I print it, the webbrowser ad 2 characters after the barecode. And, when I print the file, my document is not centered, it's like the webbrowser add a margin-left property. So my question is, is there any way to print an html file, using a webbroser, exactly how I see the html file when I use firefox or chrome for example. Here is the code I use.
curDir = Directory.GetCurrentDirectory();
webBrowserA4.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(PrintDocument);
webBrowserA4.Url = new Uri(String.Format("file:///{0}/print.html", curDir));
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Print the document now that it is fully loaded.
((WebBrowser)sender).Print();
// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
EDIT: So, now, I have another problem, here is the screen of what my file looks like when I print it: http://imgur.com/q7ovEA1 As you can see, there is a "margin-left", and I can't remove it. I also want to remove this "page 1 of 1" and the Title.
May be this question is asked in past but I have searched and not found its solution yet.
I have tried all the options that I have found till now but all in vain.
SendKeys doesn't work as it does not fill the file input box with file path, that is to be uploaded.
Cannot set file input box "SetAttribute" value as there is no value attribute available:
thats all.
If I use element.focus() it pops up "choose file to upload" dialog and now I don't know how to fill it programmatically and open it in file input box.
I want it to be automated completed so that user does not have to interact with the application.
Application shall pick the file from hard disk from given file path and fill other fields of form then start uploading, all using webbrowser control in windows form application.
No solutions found!
Can anyone help please? (This is my first ever question on stackoverflow, therefore if I am doing anything wrong then please guide, I mean if I am not allowed to post such question!)
Here is the code:
HtmlElementCollection heCollection = doc.GetElementsByTagName("input");
foreach (HtmlElement heSpan in heCollection)
{
string strType = heSpan.GetAttribute("type");
string strName = heSpan.GetAttribute("name");
if (strType.Equals("file") && strName.Equals("file"))
{
heSpan.Focus();
//heSpan.SetAttribute("value", "test.jpg");
SendKeys.Send("C:\\1.txt");
//heSpan.InnerText = "c:\\1.txt";
}
//Title for the attachment
if (strName.Equals("field_title"))
{
heSpan.InnerText = "1.txt";
}
}
When this code executes, cursor starts blinking in fine input box (as I have set heSpan.focus()) but the file path doesn't show in the file input box.
If I implement
heSpan.InvokeMember("click");
It opens the choose a file to upload dialoge/popup window and there I get stuck, because I don't know how to fill that popup dynamically and then insert the file path in file input box.
Try setting the focus to the WebBrowser control right before you set the focus to the input field.
That worked for me.