Adding a pdf file into Visual Studio - c#

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.

Related

Open files downloaded from CEFSharp in default OS viewer application

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
}
}
}

PDF file isn't centered in webBrowser control of Windows Form

I'm trying to make a PDF utility app that will allow users to merge and split PDF files. The only problem I have right now is that on load my app shows the pdf file off center. Example
In order to make the PDF file center I have to manually mouse-click the dark grey area that is shown when the PDF file is off center. After that the pdf file will be center like so
So is there anyway possible to make the PDF file centered automatically like the 2nd image?
Code below is how I call webBrowser1 that is rendering the pdf file.
public Form1()
{
InitializeComponent();
string filename = "pdf_example.pdf";
string path = Path.Combine(Environment.CurrentDirectory, filename); // grab pdf file from root program file
webBrowser1.Url = new Uri(path); // <-- input pdf location, WebBrowser Code section, REDACTED
//"button1" == "Load PDF Files", EventHandler
button1.Click += new EventHandler(button1_click);
//"button2" == "Save PDF Files", EventHandler
button2.Click += new EventHandler(button2_click);
//"button3" == "Merge PDF Files", EventHandler
button3.Click += new EventHandler(button3_click);
//"button4" == "Split PDF Files", EventHandler
button4.Click += new EventHandler(button4_click);
}
I was thinking it had to do with the pdf being loaded before the Form1 window was completely loaded. So I tried making a method and set Form1 Shown properties to this method.
void Form1_Shown(object sender, EventArgs e)
{
string filename = "pdf_example.pdf";
string path = Path.Combine(Environment.CurrentDirectory, filename); // grab pdf file from root program file
webBrowser1.Url = new Uri(path); // <-- input pdf location, WebBrowser Code section, REDACTED
}
It didn't work.
Any help would be much appreciated.
Also I completely redid the app to use axAcroPDF control to render PDF instead of webBrowser control to render PDF and I still got the same problem where the PDF file was off-center.
For future reference. The problem was that my monitor resolution was set to 4k. This caused the pdf file to be open off center in IE every-time for some reason. If the program was open in a 1920x1080 resolution monitor then the pdf file is perfectly centered every-time the program starts.

While Opening Existing MS Word Document through VSTO Add-In Getting Exception, You cannot close Microsoft Word because a dialog box is open

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);
}

How to read word document story which is already open?

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?

WPF C# Opening files in multiple directories

I have 3 open file buttons which open a file open dialog, whenever one file is opened the starting directory for the next button is always the same as the last button that was used.
I need to be able to have each button open only the last directory that it was associated with, not what the last button opened was associated with.
How can make each dialog open in the directory that that specific dialog was opened in last?
Example, I have 3 buttons i want to open in the following order:
Btn1 Open File in dir C:\temp\1 then
Btn2 Open File in dir C:\temp\1 then change to C:\temp\2
Btn3 Open File in dir C:\temp\2 then change to C:\temp\3
Btn1 Open File in dir C:\temp\1 NOT in C:\temp\3
declare some private fields in your class:
string startLocationForDialog1 = "C:\";
string startLocationForDialog2 = "C:\";
string startLocationForDialog3 = "C:\";
Then in your methods, when you create the open file dialog, set the starting location to the value of the corresponding variable.
After the file is selected, save the location of the file (without the file name) in the corresponding variable. Next time you press the same button, you use that variable which contains the last location from which a file was selected.

Categories