Repository navigation
Thank you to @lahma (PRs #95, #96, #97 and #98) and @chrisbbe (PR #82) for this release.
This is a major release. Read Breaking Changes below before upgrading: the built-in retry and the Polly and Newtonsoft.Json dependencies are gone, JObject is replaced by IDictionary<string, object> and JsonObject, and TimeOut now covers the whole call.
The client now supports Gotenberg 9 next to 7 and 8. It reads the version of the service and sends each request in the form that API takes, so most code needs no change. Gotenberg 9 refuses a few options of Gotenberg 8, and some behave differently; Gotenberg 9 lists them and says what to do. Requests to Gotenberg 7 and 8 are unchanged except for the entries under Changed and Fixed.
- Added:
GotenbergSharpClientOptions.ApiVersionandGotenbergSharpClient.ApiVersionchoose the Gotenberg API requests are rendered for:Auto(the default) reads the version of the service,V8(Gotenberg 7 and 8) andV9do not.GotenbergSharpClient.GetApiVersionAsyncreturns the API in use. The clients created byAddGotenbergSharpClient()share one version cache per service address, so the version is read once per application instead of once per client; when a response reports a version other than the cached one in itsGotenberg-Versionheader, the cached version is replaced, so a service upgraded or rolled back while the application runs is noticed on the next request- For Gotenberg 9 the client renames the fields it renamed (
nativePages,nativeBookmarks,nativeTaggedPdf, the LibreOfficenative*options, the native watermark colour as#rrggbband its rotation in degrees), sends the post-processing options (PDF/A, PDF/UA, flatten, metadata, passwords, rotation, split, stamps) as onestagesfield, sends the PDF operations to theforms/pdfroutes (pipe,metadataandbookmarks), and writes bookmarks as aset-bookmarksstage and embedded files asattachstages.ReadPdfBookmarksAsyncreads the outline of either major. Every PDF operation applies the post-processing options of its request on Gotenberg 9, as the Chromium and LibreOffice routes do; Gotenberg 8.40 read them on the merge route (all but the split options) and the split route (all of them), the PDF/A and PDF/UA options on the conversion route, and on no other PDF route, so anEncryptPdfRequestwithRotationOptionsrotates on 9 and not on 8, and aMergeRequestwithSplitOptionsreturns a zip of PDFs on 9 and one PDF on 8 - An option that Gotenberg 9 has no equivalent for throws
GotenbergVersionNotSupportedExceptionbefore anything is sent, andSupportsAsyncanswersfalse: a watermark, a stamp with free-form options, an image or PDF stamp set without its file (Gotenberg 9 cannot read a file named on the server: useSetImageStamporSetPdfStamp), metadata keys other than the eight Gotenberg 9 writes, bookmarks per file, PDF/A with a password, and a webhook without an events URL, and an embedded file relationship other thanSource,Data,Alternative,SupplementorUnspecified(Gotenberg 8 wrote any string; one of the five in another case is sent in the form Gotenberg 9 reads). The exception reports such a feature withFeature,RemovedInVersionandReplacement - Explicit Gotenberg 9 stages:
WithStages(s => ...)on the HTML, URL, Office merge and PDF merge builders, andPdfEngineBuilders.Pipe(s => ...)for PDFs alone (forms/pdf/pipe).StagesBuilderhas typed methods for merge, split, select, rotate (90, 180 or 270, asPdfEngineBuilders.Rotate),stamp-text,stamp-imageandstamp-pdfwith their position, offset, size, font, color, opacity and rotation, flatten-form, set-metadata, set-bookmarks, attach, remediate (PdfProfile, PDF/A-1a to PDF/A-4f and PDF/UA-1 and -2, alone or paired), encrypt (algorithm and permissions) and optimize, andAdd(op, options)(anIDictionary<string, object>or aJsonObject) withAddFilefor every other operation. Stages are sent as listed, after the merge of a merge request. They need Gotenberg 9: on Gotenberg 7 and 8 the request throwsGotenbergVersionNotSupportedExceptionbefore anything is sent. A request with stages and a cross-cutting option the client sends as a stage throwsInvalidOperationExceptionwhen it is validated. See Stages WebhookBuilder.SetEventsUrlandWebhook.EventsUrlset the URL that receives JSONwebhook.successandwebhook.errorevents (Gotenberg-Webhook-Events-Url). Gotenberg 9 requires it and has no error URL, so set both URLs to run on every release. Gotenberg 8.29.0 and newer accept it as an alternative to the error URL, which is no longer required when an events URL is set; the client does not check the release of Gotenberg 7 or 8 for itWatermarkOptionsBuilder.SetImageWatermarkandSetPdfWatermark, andStampOptionsBuilder.SetImageStampandSetPdfStamp, take the file name and the content (bytes, a stream or aContentItem) of an image or PDF overlay and optionally its pages;WatermarkOptionsandStampOptionscarry them asFileNameandFileContent. Gotenberg 7 and 8 receive the file in thewatermarkorstampform field (needs Gotenberg 8.28.0 or newer); Gotenberg 9 receives an image or PDF stamp as astamp-imageorstamp-pdfstage with the file uploaded underfiles, and refuses a stamp file named like another file of the request with anArgumentException- Request classes render their form parts in
ToHttpContent(GotenbergApiVersion)and their route inGetApiPath(GotenbergApiVersion);FacetBase.ToHttpContent(GotenbergApiVersion)does the same for a facet (page properties, behaviors, LibreOffice options and your own subclasses), andGotenberg9FieldAttributedeclares next to a[MultiFormHeader]property the name Gotenberg 9 gives that form field, for example[Gotenberg9Field("nativeBookmarks")]. A custom request or facet that overrides onlyToHttpContent()still works on Gotenberg 7 and 8 and throwsInvalidOperationExceptionfor Gotenberg 9 before anything is sent; to render it for that API, overrideToHttpContent(GotenbergApiVersion)and return its parts together withbase.ToHttpContent(api). A PDF operation that leaves Gotenberg 9 with no stage to run (WriteMetadatawith no value to write, aPdfConversionBuilderwith no PDF format, PDF/UA or other option) throwsInvalidOperationExceptiontoo, where Gotenberg 9 would answer400(stages is required). For both,SupportsAsyncanswersfalseandEnsureSupportedAsyncthrows the exception that sending would GotenbergResiliencePredicates.IsTransientFailureandCanResendtell a retry strategy, such as one of Microsoft.Extensions.Http.Resilience, which failed requests are worth sending again: connection failures, 429, 502 and 503, and only requests without a non-seekable stream. They are what the built-in retry decided, without its Polly dependency. See Retries and Timeouts
- Changed:
- With
ApiVersion = Auto, every request first reads the version of the service once, not only requests on routes that need a minimum version. WhenGET /versionfails with anything but a 404 (a401,403or5xx, for instance from a proxy), the request throws aGotenbergApiExceptionwhose message says what Gotenberg answered and to setApiVersiontoV8orV9to skip the lookup, orEnforceMinimumVersion = falsewhenApiVersionis already set and the request is on a route with a minimum version. It keeps the status code and has the original exception asInnerException. The failure is not cached, so the next request tries again.ApiVersion = V9skips the lookup for the routes with a minimum version too, as they are all older than Gotenberg 9; withV8they still read the version unlessEnforceMinimumVersionisfalse ConfigBuilder.SetResultFileNamenow takes effect: the name is sent as theGotenberg-Output-Filenamerequest header, the only place Gotenberg reads it, instead of a form field that was ignored. A name with characters other than printable ASCII is cleaned up before it is sent, as HTTP headers cannot carry them: accents are stripped (Mülleris sent asMuller) and every other such character, line breaks included, becomes_.ResultFileNamekeeps the name as you set itGotenbergVersionNotSupportedException.RequirementandRequiredVersionare nullable: they are null when the exception reports a removed feature, which setsRemovedInVersion- A webhook needs an error URL or an events URL. The
ArgumentNullExceptionof a webhook with neither says "A webhook error url or events url is required" instead of "An webhook error url is required", and a webhook with only an events URL counts as configured AddGotenbergSharpClient()keeps the primary handler ofIHttpClientFactoryand turns gzip and deflate decompression on for it, instead of replacing it with anHttpClientHandler. From .NET 9 that handler is aSocketsHttpHandlerwhose connections are renewed with the handler lifetime- The handler lifetime is the default of
IHttpClientFactory, 2 minutes, instead of a fixed 6 minutes.SetHandlerLifetimeon the builder thatAddGotenbergSharpClient()returns changes it
- With
- Fixed:
- Image and PDF watermarks and stamps can now be sent at all: the client sent their source but never the file Gotenberg reads them from, so Gotenberg answered 400 (8.32.0 and later). On Gotenberg 9, an image or PDF stamp without its file throws an
ArgumentExceptionnaming the builder method to use - Screenshot requests no longer send
nativePageRanges, which no screenshot route accepts. URL requests for Gotenberg 9 no longer sendextraLinkTagsandextraScriptTags(AddExtraResources): Gotenberg 9 answers400to them, and Gotenberg 8.40 ignored them, so the page is converted without the tags on both. Requests to Gotenberg 7 and 8 still send them - A file that a Gotenberg 9 stage reads (a stamp image or PDF,
AddFile, an embedded file) with a name outside ASCII, such ascafé.png, is found by its stage: the client writes the name asfilename*(RFC 5987) instead of the RFC 2047 encoded word .NET writes, which Gotenberg stored under its encoded text, so the stage answered 400 "form file is required". The check for a stage file named like another upload sees such names too MergeOfficeBuilderrequests sendmergeandnativePageRangesat most once; when both the request and its config set page ranges, the config value is used, as Gotenberg already didPdfConversionBuilderrequests send each PDF once instead of twice- On the .NET Standard builds, which .NET Framework and .NET before 8 use, the cancellation token of a call stops the reading of the response. The client read a document without it, so a body that stalled after the headers was never cut off. When the token fires, the client disposes the response, which ends a read that the response stream of .NET Framework does not cancel, and throws an
OperationCanceledExceptionfor the token
- Image and PDF watermarks and stamps can now be sent at all: the client sent their source but never the file Gotenberg reads them from, so Gotenberg answered 400 (8.32.0 and later). On Gotenberg 9, an image or PDF stamp without its file throws an
- Testing:
- The integration tests start Gotenberg 7, 8 and 9 containers and run against all three. The containers run with
--api-timeout=5m, so the first Chromium conversion of a freshly started container no longer fails with a 503 after Gotenberg's default 30 seconds on a busy machine [GotenbergTest]takes an optional exclusiveuntilversion, so a test can skip servers that dropped a route, for example[GotenbergTest("8.15.0", until: "9.0.0")]- The solution holds every project under
examples/, sodotnet buildand CI compile them. Six were missing from it, and five of those had not compiled since the namespaces changed in 3.0
- The integration tests start Gotenberg 7, 8 and 9 containers and run against all three. The containers run with
- Docs:
- New pages Gotenberg 9 and Stages. The quick starts and
docker/docker-compose-basic-auth.ymlpingotenberg/gotenberg:9 - New page Retries and Timeouts: a retry with Microsoft.Extensions.Http.Resilience,
TimeOutfor the whole call and a timeout for each attempt, the standard resilience handler with timeouts that fit conversions, webhooks sent twice, the client without DI, and how theRetryPolicysettings map. The DIExample retries that way
- New pages Gotenberg 9 and Stages. The quick starts and
- Native AOT and Trimming Support:
- The package is marked
IsAotCompatiblefor .NET 8 and newer and builds without trim or AOT warnings - JSON is now written and read with source-generated
System.Text.Json; theNewtonsoft.Jsondependency is removed - New
test/GotenbergSharpClient.AotSmokeTestproject publishes the client with Native AOT and exercises it end to end
- The package is marked
- Breaking Changes:
- The built-in retry is removed, and with it the dependency on
Microsoft.Extensions.Http.Pollyand every reference to Polly: the client sends each request once.AddGotenbergSharpClient()returns theIHttpClientBuilder, so add a resilience handler to it, for exampleAddResilienceHandlerof Microsoft.Extensions.Http.Resilience withGotenbergResiliencePredicates; see Retries and Timeouts TimeoutHandleris removed, andAddGotenbergSharpClient()no longer puts it in front of the transport. It cut every attempt off after 5 minutes with aTimeoutException, which nothing could configure.TimeOut, theHttpClient.Timeout, is now the only time limit the client sets: aTimeOutabove 5 minutes now applies in full, and a request that outlasts it throwsTaskCanceledException, as it already did whenTimeOutwas shorter. For a limit per attempt, add a timeout to a resilience pipeline; see Retries and Timeouts. Code that created aTimeoutHandlersetsHttpClient.TimeoutinsteadTimeOutlimits a call to the end of its response, not to the response headers. The client counts it from the start of the call: the version lookup the call may make first, the request and the reading of the document or text Gotenberg returns. A document that takes longer thanTimeOut(3 minutes by default) to convert and download now fails, where its download had no limit; raiseTimeOutfor large documents on slow links. A client you construct yourself counts theTimeoutof itsHttpClient(100 seconds by default) the same way. A call that outlasts it throwsTaskCanceledExceptionwith aTimeoutExceptioninside it on every build: on .NET Framework,HttpClientthrew it without one. A call that its cancellation token ends throws anOperationCanceledExceptionfor that token, on .NET Framework too. The timeouts of a resilience pipeline still end at the response headers; see Retries and TimeoutsRetryOptionsandGotenbergSharpClientOptions.RetryPolicyare obsolete and nothing reads them.RetryPolicy.Enabled = true, in code or in appsettings.json, fails options validation with anOptionsValidationExceptionthat points to the new page, so a configuration that turned retry on is noticed instead of silently losing it. RemoveRetryPolicyfrom the configuration; the negativeRetryCountandBackoffPowerchecks are gone with the retryJObjectis gone from the public API.PdfOutputOptions.MetaData,WriteMetadataRequest.Metadata,WatermarkOptions.Options,StampOptions.Options, andHtmlConversionBehaviors.ExtraHeadersare nowIDictionary<string, object>- Builder overloads that took a
JObject(SetMetadata,WriteMetadata,SetOptions,AddAdditionalHeaders) now take anIDictionary<string, object>or aSystem.Text.Json.Nodes.JsonObject - Dictionary values must be one of:
null,string,char,bool,byte,sbyte,short,ushort,int,uint,long,ulong,float,double,decimal,DateTime,DateTimeOffset,Guid,Uri, an enum (written as its number, includingulongvalues abovelong.MaxValue),byte[](written as base64),JsonNode,JsonElement,JsonDocument, or a dictionary or collection of these. Anything else throwsNotSupportedExceptionwhen it is supplied, instead of being serialized by reflection. This includesDateOnly,TimeOnly,TimeSpan, anonymous types and other classes,NaNand infinite numbers, a dictionary or collection that contains itself, nesting more than 1000 levels deep (counting the levels inside aJsonNode), and a dictionary with two keys that convert to the same property name (such as1and"1") - Dictionaries passed to
SetMetadata,WriteMetadata,SetOptionsandAddAdditionalHeadersare deep-copied, asJObject.FromObjectdid, so later changes to them or to nested dictionaries and collections are not sent PdfOutputOptionsBuilder.SetMetadata(IDictionary)throwsArgumentNullExceptionfor null, as it did before; theJsonObjectoverloads report the caller's parameter nameAddAdditionalHeaders(string, string)throwsArgumentExceptionfor a missing header name andArgumentNullExceptionfor a null value- Calling
AddAdditionalHeadersmore than once now keeps the headers from every call instead of only the last. A header with the same name, ignoring case, replaces the earlier one ReadPdfBookmarksAsync()throwsSystem.Text.Json.JsonExceptionon malformed JSON instead of a Newtonsoft exceptionGotenbergApiException.ToVerboseJson()writes a fixed set of response and request fields rather than a reflection dump of the underlying objects- JSON form fields are sent compact rather than indented
- The built-in retry is removed, and with it the dependency on