【发布时间】:2014-09-13 17:29:17
【问题描述】:
我现在有一个函数可以使用 Microsoft.Office.Interop.Word 将 docx(以字节 [] 格式)转换为 pdf(以字节 [] 格式)
而且效果很好。除了它不能在线工作,因为它需要在服务器上安装 WinOffice,而我对此无能为力。
所以我需要去做别的事情,我正在考虑 openXML(除非你知道更好的方法)。
但是我该如何解决这个问题呢? 我只想获取这个 docx 文件,将其转换为字节 [] 格式的 pdf 并返回。
我之前在 Microsoft.Office 中的代码是这样的
public static byte[] ConvertDocx2PDF(byte[] DocxFile, string FileName)
{
try
{
string path = Path.Combine(HttpRuntime.AppDomainAppPath, "MailFiles/DOCX2PDF");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
Guid id = Guid.NewGuid();
FileName = id.ToString() + FileName;
path += "/" + FileName;
if (File.Exists(path))
File.Delete(path);
File.WriteAllBytes(path, DocxFile);
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object oMissing = System.Reflection.Missing.Value;
word.Visible = false;
word.ScreenUpdating = false;
// Cast as Object for word Open method
Object filename = (Object)path;
// Use the dummy value as a placeholder for optional arguments
Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
doc.Activate();
object outputFileName = (object)path.ToLower().Replace(".docx", ".pdf");
object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
if (File.Exists(outputFileName.ToString()))
File.Delete(outputFileName.ToString());
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
object saveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
((Microsoft.Office.Interop.Word._Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
doc = null;
((Microsoft.Office.Interop.Word._Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
try
{
File.Delete(path);
}
catch { }
return File.ReadAllBytes(path.ToLower().Replace(".docx", ".pdf"));
}
catch (Exception e)
{
}
byte[] erroByte = new byte[0];
return erroByte;
}
如前所述。它工作得很好,但在我的服务器上不起作用。
知道如何在 openXML 或其他任何方法中执行此操作吗?
感谢您的宝贵时间
【问题讨论】: