I have this snippet of code that should open a docx file and I would like to save it as pdf.
Unfortunately no error is thrown but the PDF is not saved.
Any hint on how to save it?
var wordApplication = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDocument = null;
try
{
wordDocument = wordApplication.Documents.Open(docPath + ".docx");
if (wordDocument != null)
wordDocument.SaveAs2(docPath + ".pdf", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
//wordDocument.ExportAsFixedFormat(docPath + ".pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
else throw new Exception("CUSTOM ERROR: Cannot Open Word Application");
}
catch (Exception ex)
{
new Exception("CUSTOM ERROR" + ex.Message);
}
There are a number of different options detailed on this post on stack already.
Word, and Interop especially, is particularly painful when doing this sort of this as it’s COM based nature means it does not always play by the .NET rules. You might need to Activate() the document first before saving or there may be other issues. You might want to try saving the doc as a normal docx just to isolate the issue. It might also be that there is something in the doc that is not saving so it’s worth testing with a basic doc first.
EDIT: See this link and this link
The IIS tweak is in advanced settings of the application pool. You will need to run the pool under a specific identity and then set Load User Profile to true. I have never used Interop like this and it may not work. If you are just trying to convert a word document to a pdf then there are easier ways than interop (OpenXML, pdf libraries etc). Is there are reason you are using Interop?
EDIT: You might want to give DocX a go. You can find it here
It looks like this is a common issue with conversion. I have done this in the past using Aspose but I have never had to convert a PDF on a server without being able to simply buy the best component (and Aspose is not cheap!). I would certainly advise trying to stay away from Interop if you can but after reading that post it may be needed.