0

While developing, I had encountered a problem. Main idea of code is using MS Word to convert .doc and .rtf to .pdf files format. Code is working perfectly for exe-application. But using this code in a service application causes a problem: calling ExportAsFixedFormat method raises an exception "Invalid variant operation". I'd running out of ideas, how to fix this. Do anybody has one?

function DocToPDFByWord (sFileName,sPDFFileName :string;) : byte;
  const
    wdExportFormatPDF = 17;
    wdDoNotSaveChanges = 0;
  var
    vOLEApp ,vDocument : OleVariant;

begin
  Result := 0;
  CoInitialize (nil);

  vOLEApp := CreateOLEObject ('Word.Application');
  if VarIsNull(vOLEApp) then
    begin
      Result := 1;
      Exit;
    end;
  vOLEApp.Visible:= False;


  try
    vDocument := vOLEApp.Documents.Open(FileName:= sFileName, ConfirmConversions:= False, ReadOnly:= True, AddToRecentFiles:= False, PasswordDocument:= 'dummy', PasswordTemplate:= 'dummy', Revert:= True, Visible:= False, OpenAndRepair:= False, NoEncodingDialog:= True);
    if VarIsNull(vDocument) then
      Result := 2
    else
      try
        vDocument.ExportAsFixedFormat (sPDFFileName ,wdExportFormatPDF);
      except
        Result := 3;
      end;
  except
    Result:= 4;
  end;

  vOLEApp.Quit (wdDoNotSaveChanges);
  vOLEApp := Unassigned;
  CoUnInitialize;
end;
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Try running the service under specific user account of some local user. Maybe this will give you some ideas. – Eugene Mayevski 'Callback Oct 28 '14 at 17:21
  • 4
    This is pretty hard to make work. Word wants to run in an interactive desktop. It's really not a good choice to solve your problem. You might find some hope here: http://stackoverflow.com/questions/1006923/automating-office-via-windows-service-on-server-2008 and many other similar questions that I'm sure you can find with web search – David Heffernan Oct 28 '14 at 17:30
  • Sorry to ask an obvious q, but have you considered doing the PDF stuff in a non-service application and using IPC to get the service to tell the application what to do? Might be less easily tripped up by host config/OS issues than trying to hack the functionality into the service. – MartynA Oct 28 '14 at 21:35
  • As a little aside I wrote a simple conversion tool using delphi to convert doc to rtf, pdf. You can find code and exe here https://github.com/tobya/DocTo – Toby Allen Oct 29 '14 at 08:03
  • 1
    Keep in mind that Microsoft officially does not support server-side Office automation: http://support2.microsoft.com/kb/257757 – iPath ツ Oct 29 '14 at 09:24

0 Answers0