【C#】Winform如何利用Aspose.Words/Cells/Slides将Office文档Word/Excel/PowerPoint一键转为PDF文件
|
admin
2025年2月11日 11:1
本文热度 858
|
【C#】Winform如何利用Aspose.Words/Cells/Slides将Office文档Word/Excel/PowerPoint一键转为PDF文件
先在项目中添加:Aspose.Cells.dll、Aspose.Words.dll、Aspose.Slides.dll 三个dll的引用。
然后在代码中引入相关组件:
using Aspose.Words;
using Aspose.Cells;
using Aspose.Slides;
然后在组件上执行相关转换操作:
private void txt_file_path_MouseClick(object sender, MouseEventArgs e)
{
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;
}
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;
}
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;
}
string targetfilepath = (Public.Left(sourceFilePath, sourceFilePath.Length - 4) + ".pdf").Replace("..", ".");
if (File.Exists(targetfilepath))
{
Console.WriteLine("文档“" + targetfilepath + "”已经存在,无需转换!");
return;
}
try
{
if (sourceFileExt == ".doc" || sourceFileExt == "docx")
{
Aspose.Words.Document doc = new Aspose.Words.Document(sourceFilePath);
doc.Save(targetfilepath, Aspose.Words.SaveFormat.Pdf);
}
if (sourceFileExt == ".xls" || sourceFileExt == "xlsx")
{
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(sourceFilePath);
workbook.Save(targetfilepath, Aspose.Cells.SaveFormat.Pdf);
}
if (sourceFileExt == ".ppt" || sourceFileExt == "pptx")
{
var pres = new Presentation(sourceFilePath);
pres.Save(targetfilepath, Aspose.Slides.Export.SaveFormat.Pdf);
}
Console.WriteLine("文档“" + sourceFilePath + "”转换为PDF文档成功。");
}
catch
{
Console.WriteLine("文档“" + sourceFilePath + "”转换为PDF文档失败!\r\n请检查是否是本程序没有当前目录写入权限等。");
}
}
该文章在 2025/2/11 17:23:47 编辑过