本文主要是介绍C# 使用Microsoft.Office.Interop.Word 将WORD转成PDF,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// <summary>
/// 测试文件
/// </summary>
/// <param name="input">文件名</param>
/// <returns></returns>
[ApiDescriptionSettings(Name = "Getword")]
[HttpGet]
public IActionResult getWord(string wordName)
{
string templatePath = "D:\\Template\\wordTemplate.docx";
string log = "D:\\Template\\l123jpg";
var tt = new MiniWordPicture() { Extension = DocumentFormat.OpenXml.Packaging.ImagePartType.Jpeg.ToString(), Bytes = File.ReadAllBytes(log), Width = 200, Height = 100 };
var baidu = new MiniWordHyperLink()
{
Url = "https://www.baidu.com/",
Text = "百度"
};
//var tt = new MiniWordPicture() { Extension = ImagePartType.Jpeg.ToString(), Bytes = FileToByte(log), Width = 100, Height = 100 };
var endDate = new MiniWordColorText { Text = DateTime.Parse("2022-09-15 15:30:00").ToString(), HighlightColor = "#eb70AB", FontColor = "#ffffff" };
var value = new Dictionary<string, object>()
{
["Name"] = "Jack",
["Department"] = "IT Department",
["Purpose"] = "Shanghai site needs a new system to control HR system.",
["StartDate"] = DateTime.Parse("2022-09-07 08:30:00"),
["EndDate"] = endDate,//
["Approved"] = true,
["Total_Amount"] = 123456,
//["Logo"] = new MiniWordPicture() { Path = log, Width = 180, Height = 180 },
["Logo"] = tt,
["baidu"] = baidu,
["person"] = new List<Dictionary<string, object>> {
new Dictionary<string, object>{ { "name","wade"},{ "age","HR" } },
new Dictionary<string, object>{ { "name","admin"},{ "age","it" } },
new Dictionary<string, object>{ { "name","erid"},{ "age","测试" } },
new Dictionary<string, object>{ { "name","张三"},{ "age","HR" } },
new Dictionary<string, object>{ { "name","大"},{ "age","HR在" } },
}
};
MemoryStream wordStream = new MemoryStream();
MiniWord.SaveAsByTemplate(wordStream, templatePath, value);
wordStream.Close();
return new FileStreamResult(new MemoryStream(wordStream.GetBuffer()), "application/octet-stream") { FileDownloadName = wordName + ".docx" };
}
public static byte[] ConvertWordToPdf(string wordUrl, string pdfUrl)
{
wordUrl = "D:\\Template\\wordTemplate.docx"; //源word地址
pdfUrl = @"D:\WechatFile\123.pdf"; //生成后的pdf文件地址
// 创建Word应用程序对象
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
// 将Word文件加载到Document对象中
Document document = wordApplication.Documents.Open(wordUrl);
// 创建内存流,并将PDF文件流保存到其中
MemoryStream pdfStream = new MemoryStream();
document.SaveAs(pdfUrl, WdExportFormat.wdExportFormatPDF);
// 关闭Word文档和应用程序对象
document.Close(false);
wordApplication.Quit(false);
// 将生成的PDF转换为byte数组并返回
byte[] pdfBytes = pdfStream.ToArray();
pdfStream.Close();
return pdfBytes;
}
对应的几个dll版本都在截图中,在nuget 中都可以下载 无水印的
这篇关于C# 使用Microsoft.Office.Interop.Word 将WORD转成PDF的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!