Saving to pdf from OpenOffice
Asked Answered
G

1

3

Since I just asked this question and got a very useful reply I wonder if anyone has already the code for using the documentTopdf routine built in in Open Office for saving odt, doc, docx files to pdf.

Here there is the c# example anyway since having it in Delphi direcly would be great for many users.

Goncourt answered 19/10, 2011 at 9:29 Comment(0)
I
8

Very similarly :)

Here is the tutorial describing all features used for configuration of the generated document.

For the following example I chose fit to width magnification, password protection and hidden window controls. The export is done in hidden mode when the OpenOffice window isn't shown at conversion.

Note that the following code is again without error handling.

uses
  ComObj;

procedure OpenOfficeExportToPDF(const ASourceFileURL: string; const ATargetFileURL: string);
var
  StarOffice: Variant;
  StarDesktop: Variant;
  StarDocument: Variant;
  FilterParams: Variant;
  ExportParams: Variant;
  ExportObject: Variant;

  function CreateProperty(const AName: AnsiString; AValue: Variant): Variant;
  begin
    Result := StarOffice.Bridge_GetStruct('com.sun.star.beans.PropertyValue');
    Result.Name := AName;
    Result.Value := AValue;
  end;

begin
  StarOffice := CreateOleObject('com.sun.star.ServiceManager');
  StarDesktop := StarOffice.CreateInstance('com.sun.star.frame.Desktop');

  FilterParams := VarArrayCreate([0, 0], varVariant);
  FilterParams[0] := CreateProperty('Hidden', True);

  StarDocument := StarDesktop.LoadComponentFromURL(ASourceFileURL, '_blank', 0, FilterParams);

  ExportParams := VarArrayCreate([0, 3], varVariant);
  ExportParams[0] := CreateProperty('Magnification', 2);
  ExportParams[1] := CreateProperty('EncryptFile', True);
  ExportParams[2] := CreateProperty('DocumentOpenPassword', AnsiString('StackOverflow'));
  ExportParams[3] := CreateProperty('HideViewerWindowControls', True);

  ExportObject := StarOffice.Bridge_GetValueObject;
  ExportObject.Set('[]com.sun.star.beans.PropertyValue', ExportParams);

  FilterParams := VarArrayCreate([0, 1], varVariant);
  FilterParams[0] := CreateProperty('FilterName', AnsiString('writer_pdf_Export'));
  FilterParams[1] := CreateProperty('FilterData', ExportObject);

  StarDocument.StoreToURL(ATargetFileURL, FilterParams);

  StarDocument.Close(True);
  StarDesktop.Terminate;

  StarDocument := Unassigned;
  StarDesktop := Unassigned;
  StarOffice := Unassigned;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  OpenOfficeExportToPDF('file:///C:/SourceFile.odt', 'file:///C:/TargetFile.pdf');
end;
Impale answered 19/10, 2011 at 10:5 Comment(2)
Thanks: if you can expand the code I think not only me but many community members will appreciate it!Goncourt
You're welcome, I've added some PDF export parameter settings to the example ;)Impale

© 2022 - 2024 — McMap. All rights reserved.