private void txt_file_path_MouseClick(object sender, MouseEventArgs e)
{
// 创建 OpenFileDialog 对象
OpenFileDialog openFileDialog = new OpenFileDialog();
// 设置对话框标题
openFileDialog.Title = "选择一个Office文件";
// 设置文件过滤器,允许选择特定类型的文件
openFileDialog.Filter = "Office文件 (*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx)|*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx";
// 允许用户选择多个文件
openFileDialog.Multiselect = false;
// 显示对话框并检查用户是否点击了“确定”
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// 获取用户选择的文件路径
string[] selectedFiles = openFileDialog.FileNames;
// 输出选择的文件路径
foreach (string file in selectedFiles)
{
txt_file_path.Text = file;
}
// 设置输出PDF文件的路径
if (txt_file_path.Text != "")
{
string sourceFilePath = txt_file_path.Text;
string targetfilepath = (Public.Left(sourceFilePath, sourceFilePath.Length - 4) + ".pdf").Replace("..", ".");
if (File.Exists(targetfilepath))
{
btn_office2pdf.Enabled = false;
txt_result.Text = "文档“" + targetfilepath + "”已经存在,无需转换!";
Console.WriteLine("文档“" + targetfilepath + "”已经存在,无需转换!");
}
else
{
btn_office2pdf.Enabled = true;
}
}
}
}
private void btn_office2pdf_Click(object sender, EventArgs e)
{
string sourceFilePath = txt_file_path.Text;
if (sourceFilePath == "")
{
MessageBox.Show("转换失败:没有选择要转换的文件,请先选择!","系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
//转换Office文档为PDF文档
office2pdf(sourceFilePath, 0);
}
public void office2pdf(string sourceFilePath, int alertFlag)
{
// 检查源文件是否存在
if (!File.Exists(sourceFilePath))
{
Console.WriteLine("文档“" + sourceFilePath + "”不存在,请先选择!");
return;
}
// 检查源文件是否是指定格式
string sourceFileExt = Public.Right(sourceFilePath, 4).ToLower();
if (!(sourceFileExt == ".doc" || sourceFileExt == ".xls" || sourceFileExt == ".ppt" || sourceFileExt == "docx" || sourceFileExt == "xlsx" || sourceFileExt == "pptx"))
{
Console.WriteLine("文档格式“" + sourceFileExt + "”错误,必须为doc/xls/ppt文档!");
return;
}
// 设置输出PDF文件的路径
string targetfilepath = (Public.Left(sourceFilePath, sourceFilePath.Length - 4) + ".pdf").Replace("..", ".");
if (File.Exists(targetfilepath))
{
Console.WriteLine("文档“" + targetfilepath + "”已经存在,无需转换!");
return;
}
try
{
if (sourceFileExt == ".doc" || sourceFileExt == "docx")
{
// 读取doc文档
Aspose.Words.Document doc = new Aspose.Words.Document(sourceFilePath);
//保存为PDF文件,此处的SaveFormat支持很多种格式,如图片,epub,rtf 等等
doc.Save(targetfilepath, Aspose.Words.SaveFormat.Pdf);
}
if (sourceFileExt == ".xls" || sourceFileExt == "xlsx")
{
// 初始化Workbook对象
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(sourceFilePath);
// 将Excel保存为PDF格式
workbook.Save(targetfilepath, Aspose.Cells.SaveFormat.Pdf);
}
if (sourceFileExt == ".ppt" || sourceFileExt == "pptx")
{
// 加载PPT或PPTX文件
var pres = new Presentation(sourceFilePath);
// 保存为PDF格式
pres.Save(targetfilepath, Aspose.Slides.Export.SaveFormat.Pdf);
}
Console.WriteLine("文档“" + sourceFilePath + "”转换为PDF文档成功。");
}
catch
{
Console.WriteLine("文档“" + sourceFilePath + "”转换为PDF文档失败!\r\n请检查是否是本程序没有当前目录写入权限等。");
}
}