api

package
v8.40.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package api manages a LibreOffice instance via the UNO API.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidPdfFormats happens if LibreOffice cannot handle the PDF
	// formats option.
	ErrInvalidPdfFormats = errors.New("invalid PDF formats")

	// ErrUnoException happens when unoconverter returns exit code 5. That code
	// is the residual bucket of unoconverter's catch-all UNO exception handler:
	// it covers a malformed page range, a password supplied to a document that
	// does not need one, a failure to open the document and a failure to write
	// the output alike. It names the exception class that was caught, not a
	// cause. See https://github.com/gotenberg/gotenberg/issues/1588.
	ErrUnoException = errors.New("uno exception")

	// ErrRuntimeException happens when unoconverter returns exit code 6.
	// unoconverter's own message for it reads "Office probably died", yet a
	// wrong or missing password also surfaces there. Like [ErrUnoException], it
	// does not establish who is at fault.
	ErrRuntimeException = errors.New("runtime exception")

	// ErrIoException happens when unoconverter returns exit code 3. LibreOffice
	// could not read the source document.
	ErrIoException = errors.New("io exception")

	// ErrCannotConvertException happens when unoconverter returns exit code 4.
	// LibreOffice read the document but could not convert it to PDF.
	ErrCannotConvertException = errors.New("cannot convert exception")

	// ErrIllegalArgumentException happens when unoconverter returns exit code
	// 8. LibreOffice rejected the source document, usually because its contents
	// do not match its extension.
	ErrIllegalArgumentException = errors.New("illegal argument exception")

	// ErrCoreDumped happens randomly; sometimes a conversion will work as
	// expected, and some other time the same conversion will fail.
	// See https://github.com/gotenberg/gotenberg/issues/639.
	ErrCoreDumped = errors.New("core dumped")
)

Functions

This section is empty.

Types

type Api

type Api struct {
	// contains filtered or unexported fields
}

Api is a module that provides a Uno to interact with LibreOffice.

func (*Api) Checks

func (a *Api) Checks() ([]health.CheckerOption, error)

Checks adds a health check that verifies if LibreOffice is healthy.

func (*Api) Debug added in v8.17.0

func (a *Api) Debug() map[string]any

Debug returns additional debug data.

func (*Api) Descriptor

func (a *Api) Descriptor() gotenberg.ModuleDescriptor

Descriptor returns a Api's module descriptor.

func (*Api) Extensions

func (a *Api) Extensions() []string

Extensions returns the file extensions available for conversions. FIXME: don't care, take all on the route level?

func (*Api) LibreOffice

func (a *Api) LibreOffice() (Uno, error)

LibreOffice returns a Uno for interacting with LibreOffice.

func (*Api) Metrics

func (a *Api) Metrics() ([]gotenberg.Metric, error)

Metrics returns the metrics.

func (*Api) Pdf

func (a *Api) Pdf(ctx context.Context, logger *slog.Logger, inputPath, outputPath string, options Options) error

Pdf converts a document to PDF.

func (*Api) Provision

func (a *Api) Provision(ctx *gotenberg.Context) error

Provision sets the module properties.

func (*Api) Ready

func (a *Api) Ready() error

Ready returns no error if the module is ready.

func (*Api) Start

func (a *Api) Start() error

Start does nothing if auto-start is not enabled. Otherwise, it starts a LibreOffice instance.

func (*Api) StartupMessage

func (a *Api) StartupMessage() string

StartupMessage returns a custom startup message.

func (*Api) Stop

func (a *Api) Stop(ctx context.Context) error

Stop stops the current browser instance.

func (*Api) Validate

func (a *Api) Validate() error

Validate validates the module properties.

type ApiMock

type ApiMock struct {
	PdfMock        func(ctx context.Context, logger *slog.Logger, inputPath, outputPath string, options Options) error
	ExtensionsMock func() []string
}

ApiMock is a mock for the Uno interface.

func (*ApiMock) Extensions

func (api *ApiMock) Extensions() []string

func (*ApiMock) Pdf

func (api *ApiMock) Pdf(ctx context.Context, logger *slog.Logger, inputPath, outputPath string, options Options) error

type Options

type Options struct {
	// Password specifies the password for opening the source file.
	Password string // #nosec

	// Landscape allows changing the orientation of the resulting PDF.
	Landscape bool

	// PageRanges allows selecting the pages to convert.
	PageRanges string

	// UpdateIndexes specifies whether to update the indexes before conversion,
	// keeping in mind that doing so might result in missing links in the final
	// PDF.
	UpdateIndexes bool

	// ExportFormFields specifies whether form fields are exported as widgets
	// or only their fixed print representation is exported.
	ExportFormFields bool

	// AllowDuplicateFieldNames specifies whether multiple form fields exported
	// are allowed to have the same field name.
	AllowDuplicateFieldNames bool

	// ExportBookmarks specifies if bookmarks are exported to PDF.
	ExportBookmarks bool

	// ExportBookmarksToPdfDestination specifies that the bookmarks contained
	// in the source LibreOffice file should be exported to the PDF file as
	// Named Destination.
	ExportBookmarksToPdfDestination bool

	// ExportPlaceholders exports the placeholder fields visual markings only.
	// The exported placeholder is ineffective.
	ExportPlaceholders bool

	// ExportNotes specifies if notes are exported to PDF.
	ExportNotes bool

	// ExportNotesPages specifies if notes pages are exported to PDF.
	// Notes pages are available in Impress documents only.
	ExportNotesPages bool

	// ExportOnlyNotesPages specifies if the property ExportNotesPages is set
	// to true if only notes pages are exported to PDF.
	ExportOnlyNotesPages bool

	// ExportNotesInMargin specifies if notes in the margin are exported to
	// PDF.
	ExportNotesInMargin bool

	// ConvertOooTargetToPdfTarget specifies that the target documents with
	// .od[tpgs] extension will have that extension changed to .pdf when the
	// link is exported to PDF. The source document remains untouched.
	ConvertOooTargetToPdfTarget bool

	// ExportLinksRelativeFsys specifies that the file system related
	// hyperlinks (file:// protocol) present in the document will be exported
	// as relative to the source document location.
	ExportLinksRelativeFsys bool

	// ExportHiddenSlides exports, for LibreOffice Impress, slides that are not
	// included in slide shows.
	ExportHiddenSlides bool

	// SkipEmptyPages specifies that automatically inserted empty pages are
	// suppressed. This option is active only if storing Writer documents.
	SkipEmptyPages bool

	// AddOriginalDocumentAsStream specifies that a stream is inserted to the
	// PDF file which contains the original document for archiving purposes.
	AddOriginalDocumentAsStream bool

	// SinglePageSheets ignores each sheet’s paper size, print ranges and
	// shown/hidden status and puts every sheet (even hidden sheets) on exactly
	// one page.
	SinglePageSheets bool

	// InitialView specifies how the PDF document should be displayed when
	// opened. 0 = neither outlines nor thumbnails, 1 = outline pane open,
	// 2 = thumbnail pane open.
	InitialView int

	// InitialPage specifies the page on which the PDF document should be
	// opened in the viewer.
	InitialPage int

	// Magnification specifies the action to be performed when the PDF document
	// is opened. 0 = default, 1 = fit entire page, 2 = fit page width,
	// 3 = fit visible, 4 = use zoom value from Zoom property.
	Magnification int

	// Zoom specifies the zoom level the PDF document is opened with. Only
	// used if Magnification is set to 4.
	Zoom int

	// PageLayout specifies the page layout when the document is opened.
	// 0 = default, 1 = single page, 2 = one column, 3 = two columns.
	PageLayout int

	// FirstPageOnLeft is used with PageLayout value 3. If true, the first
	// page is displayed on the left side.
	FirstPageOnLeft bool

	// ResizeWindowToInitialPage specifies that the PDF viewer window is
	// resized to show the whole initial page.
	ResizeWindowToInitialPage bool

	// CenterWindow specifies that the PDF viewer window is centered on the
	// screen.
	CenterWindow bool

	// OpenInFullScreenMode specifies that the PDF viewer window is opened
	// full screen.
	OpenInFullScreenMode bool

	// DisplayPDFDocumentTitle specifies that the document title is displayed
	// in the PDF viewer title bar.
	DisplayPDFDocumentTitle bool

	// HideViewerMenubar specifies whether to hide the PDF viewer menubar.
	HideViewerMenubar bool

	// HideViewerToolbar specifies whether to hide the PDF viewer toolbar.
	HideViewerToolbar bool

	// HideViewerWindowControls specifies whether to hide the PDF viewer
	// window controls.
	HideViewerWindowControls bool

	// UseTransitionEffects specifies that slide transitions are exported to
	// PDF. Only active for Impress documents.
	UseTransitionEffects bool

	// OpenBookmarkLevels specifies how many bookmark levels should be opened
	// in the reader. -1 = all levels, 1-10 = specific level.
	OpenBookmarkLevels int

	// LosslessImageCompression specifies if images are exported to PDF using
	// a lossless compression format like PNG or compressed using the JPEG
	// format.
	LosslessImageCompression bool

	// Quality specifies the quality of the JPG export. A higher value produces
	// a higher-quality image and a larger file. Between 1 and 100.
	Quality int

	// ReduceImageResolution specifies if the resolution of each image is
	// reduced to the resolution specified by the property MaxImageResolution.
	ReduceImageResolution bool

	// MaxImageResolution, if the property ReduceImageResolution is set to
	// true, tells if all images will be reduced to the given value in DPI.
	// Possible values are: 75, 150, 300, 600 and 1200.
	MaxImageResolution int

	// NativeWatermarkText specifies the text for a watermark to be drawn on
	// every page of the exported PDF file.
	// See https://help.libreoffice.org/latest/en-US/text/shared/guide/pdf_params.html.
	NativeWatermarkText string

	// NativeWatermarkColor specifies the color for the watermark text as a
	// decimal long value. Default is 8388223 (light green).
	NativeWatermarkColor int

	// NativeWatermarkFontHeight specifies the font size for the watermark text.
	NativeWatermarkFontHeight int

	// NativeWatermarkRotateAngle specifies the rotation angle for the watermark
	// text in tenths of a degree (e.g., 450 = 45°).
	NativeWatermarkRotateAngle int

	// NativeWatermarkFontName specifies the font name for the watermark text.
	// Default is "Helvetica".
	NativeWatermarkFontName string

	// NativeTiledWatermarkText specifies the tiled watermark text.
	NativeTiledWatermarkText string

	// GenerateTaggedPdf specifies whether to generate a tagged (accessible)
	// PDF without declaring PDF/UA conformance. PdfFormats.PdfUa implies it.
	GenerateTaggedPdf bool

	// PdfFormats allows to convert the resulting PDF to PDF/A-1b, PDF/A-2b,
	// PDF/A-3b, PDF/A-4 and PDF/UA.
	PdfFormats gotenberg.PdfFormats
}

Options gathers available options when converting a document to PDF. See: https://help.libreoffice.org/latest/en-US/text/shared/guide/pdf_params.html.

func DefaultOptions added in v8.8.0

func DefaultOptions() Options

DefaultOptions returns the default values for Options.

type PasswordProtection added in v8.35.0

type PasswordProtection int

PasswordProtection describes whether a document requires a password to open.

const (
	// PasswordProtectionUnknown means the document's encryption state could not
	// be determined.
	PasswordProtectionUnknown PasswordProtection = iota

	// PasswordProtectionNone means the document opens without a password.
	PasswordProtectionNone

	// PasswordProtectionRequired means the document is encrypted.
	PasswordProtectionRequired
)

func DetectPasswordProtection added in v8.35.0

func DetectPasswordProtection(path string) PasswordProtection

DetectPasswordProtection reports whether the document at path is encrypted.

Detection is advisory and never fails: an unreadable file, an unknown format or a malformed archive all yield PasswordProtectionUnknown. It exists to refine the diagnosis of a conversion that already failed, since LibreOffice's exit codes do not distinguish a missing password from a crash.

type Provider

type Provider interface {
	LibreOffice() (Uno, error)
}

Provider is a module interface that exposes a method for creating a Uno for other modules.

func (m *YourModule) Provision(ctx *gotenberg.Context) error {
	provider, _ := ctx.Module(new(libreofficeapi.Provider))
	libreOffice, _      := provider.(api.Provider).LibreOffice()
}

type ProviderMock

type ProviderMock struct {
	LibreOfficeMock func() (Uno, error)
}

ProviderMock is a mock for the Provider interface.

func (*ProviderMock) LibreOffice

func (provider *ProviderMock) LibreOffice() (Uno, error)

type Uno

type Uno interface {
	Pdf(ctx context.Context, logger *slog.Logger, inputPath, outputPath string, options Options) error
	Extensions() []string
}

Uno is an abstraction on top of the Universal Network Objects API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL