在Visual Studio中添加pdf文件

本文关键字:pdf 文件 添加 Visual Studio | 更新日期: 2023-09-27 18:08:58

我有一个菜单栏,我已经创建了一个标签为"Contents"。我希望能够点击内容选项卡和一个窗口弹出一个pdf文件列出的内容。我有一个pdf文件,里面列出了保存在我桌面上的内容。是否有一种方法可以将此pdf文件添加到visual studio,以便当我单击Content选项卡时,pdf文件将被打开?

我不想点击另一个按钮来搜索我的计算机中的文件,如使用OpenFileDialog。我只是想点击Contents选项卡,打开一个pdf文件窗口

在Visual Studio中添加pdf文件

有多种方法可以做到这一点。

1)一种方法是从你的应用程序中启动一个进程,打开你PC上默认注册的PDF文件查看器(如Adobe Reader),并将PDF文件的完整路径作为参数传递给PDF文件:

在这里,您可以了解如何通过文件扩展名(在您的示例中为"。pdf")确定默认处理程序应用程序的路径:

http://www.pinvoke.net/default.aspx/shlwapi/AssocQueryString.html

string execPath = GetAssociation(".pdf");

一旦你知道了可执行文件的路径,你就可以用PDF文件的路径作为参数来启动它:

using System.Diagnostics;
...
// Start new process
Process.Start(execPath, "C:''myfile.pdf").WaitForExit(0);

2)另一种方法是在你的应用程序中创建一个Windows窗体,并添加web浏览器控件。然后,web浏览器控件可以通过编程"导航"到您的特定PDF文件。这是假设你的ie浏览器已经可以通过使用adobereader之类的工具在其窗口中显示PDF文件,即作为内联附件:

将项目中的引用添加到Microsoft Internet Controls 1.1(右键单击References>Add reference…)

> COM)。

在你的表单代码(这里panePdfViewer是一个占位符System.Windows.Forms.Panel控制):

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

然后:

// 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);
第三种方法是使用可以显示PDF文件的第三方控件库。