Code Monkey home page Code Monkey logo

gotenberg-js-client's Introduction

Gotenberg JS/TS client

Build Status Coverage Status License NPM Made with Love

A simple JS/TS client for interacting with a Gotenberg API.
Gotenberg is a Docker-powered stateless API for converting HTML, Markdown and Office documents to PDF.

  • HTML and Markdown conversions using Google Chrome headless
  • Office conversions (.txt, .rtf, .docx, .doc, .odt, .pptx, .ppt, .odp and so on) using unoconv
  • Assets: send your header, footer, images, fonts, stylesheets and so on for converting your HTML and Markdown to beautiful PDFs!
  • Easily interact with the API using Go and PHP libraries (and now - JavaScript too ;)

Install

$ yarn add gotenberg-js-client

Or using npm

$ npm install --save gotenberg-js-client

NB ⚠️

This library is not yet fully compatible with Gotenberg 7.
You can find more info in this comment.

There are three main issues:

  • Gotenberg 7 has introduced new concept of conversion modules, thus, changing conversion URLs, so now they are different, than ones, this library creates. This can be sidestepped using custom connection string or adjusting URL manually (see this comment).
  • New modules has some new possibilities/parameters, which are impossible to pass, using this library. This can be sidestepped using adjust, and casting to any, if you use TypeScript (see this issue for reference).
  • Gotenberg 7 can potentially has many many different custom conversion modules, you can even write your own one. You can combine p.1 and p.2 to use any module with any path with any parameters, but I guess it will look not good. But it should work nonetheless.

So, nothing you can live without, but there are some inconveniences. For a while ;)

Usage

import { pipe, gotenberg, convert, html, please } from 'gotenberg-js-client'

const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  html,
  please
)

// --- 8< ---

// convert file from disk
const pdf = await toPDF('file://index.html')

// or convert stream
const pdf = await toPDF(fs.createReadStream('index.html'))

// or convert string!
const pdf = await toPDF('<html>...</html>')

// library returns NodeJS.ReadableStream,
// so you can save it to file, if you want, for example
pdf.pipe(fs.createWriteStream('index.pdf'))

// or you can send it as response in Express application
app.get('/pdf', function (req, res) {
  //...
  pdf.pipe(res)
})

You can define any source like string, Buffer, file link, stream.Readable, or URL (for url conversions).
Detailed sources format you can find here.

Header, footer and assets

You can define sources as array or object, for example:

// `toPDF` function is defined above ↑↑↑

// as object
const pdf = await toPDF({
  'index.html': 'file://index.html',
  'header.html': 'file://header.html',
  'footer.html': 'file://footer.html',
  'style.css': 'file://style.css',
  'img.png': 'file://img.png',
  'font.wof': 'file://font.wof',
})

// as array of tuples
const pdf = await toPDF([
  ['index.html', 'file://index.html'],
  ['header.html', 'file://header.html'],
  ['footer.html', 'file://footer.html'],
])

// as even 1-dimensional array of files
// in that case filenames will be retrieved from file path
const pdf = await toPDF([
  'file://index.html',
  'file://header.html',
  'file://footer.html',
])

Instead of array you can use any iterable, like Map, Set, arguments, iterator from generator function, or any object with [Symbol.iterator] defined.
Detailed sources format you can find here.

Paper size, margins, orientation

When converting HTML or Markdown, you can use to helper, to set paper size, margins and orientation:

import {
  pipe,
  gotenberg,
  convert,
  html,
  please,
  to,
  a4,
  landscape,
} from 'gotenberg-js-client'

const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  html,
  to(a4, landscape),
  please
)

You can use simple object(s) for to argument(s) as well:

//...
to({
  paperWidth: 8.27,
  paperHeight: 11.69,
  marginTop: 0,
  marginBottom: 0,
  marginLeft: 0,
  marginRight: 0,
  landscape: true,
})
//...

// or
to([8.27, 11.69], [0, 0, 0, 0], { landscape: true })
//...

// or
to({ paper: [8.27, 11.69], margins: [0, 0, 0, 0], landscape: true })
//...

// or
to({ width: 8.27, height: 11.69 }, { landscape: true })
//...

// or
to({ top: 0, bottom: 0 })
//...

// or any other combination

When using array for paper size, order should be [width, height]
When using array for margins, order should be [top, right, bottom, left] (just like in CSS)

Common options

You can set common options, like resultFilename, or waitTimeout, or, actually, you can override any option, using set helper:

//...
set({
  resultFilename: 'foo.pdf',
  waitTimeout: 2.5,
})
//...

There are some modifiers functions as well, like filename, timeout, delay, webhook and googleChromeRpccBufferSize:

//...
set(filename('foo.pdf'), timeout(2.5))
//...

Also you can specify page ranges using set(range) (will not work with merge):

//...
set(range('1-1'))
//...

or scale, using set(scale) (works with HTML, Markdown and URL conversions):

//...
set(scale(0.75))
//...
import { pipe, gotenberg, convert, markdown, please } from 'gotenberg-js-client'

const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  markdown,
  please
)

// --- 8< ---

const pdf = await toPDF({
  'index.html': `
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>My PDF</title>
      </head>
      <body>
        {{ toHTML .DirPath "content.md" }}
      </body>
    </html>`,

  'content.md': `
    # My awesome markdown
    ...
  `,
})

Note: I use strings here as an example, remind that you can use other supported source type.

import {
  pipe,
  gotenberg,
  convert,
  office,
  to,
  landscape,
  set,
  filename,
  please,
} from 'gotenberg-js-client'

const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  office,
  to(landscape),
  set(filename('result.pdf')),
  please
)

// --- 8< ---

const pdf = await toPDF('file://document.docx')

Note: I use file link here as an example, remind that you can use other supported source type, say, Buffer, or stream.Readable:

https.get(
  'https://file-examples.com/wp-content/uploads/2017/02/file-sample_100kB.docx',
  async (document) => {
    const pdf = await toPDF({ 'document.docx': document })
    // ...
  }
)
import { pipe, gotenberg, convert, url, please } from 'gotenberg-js-client'

const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  url,
  please
)

// --- 8< ---

// you can use link as string
const pdf = await toPDF('https://google.com')

// or URL object
const pdf = await toPDF(new URL('https://google.com'))

Note: The only supported source for Url conversion is text url or instance of URL class.

You can set remote url header (for example, for authentication or host specifying) with helper add(header) (or add(headers), or both):

const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  url,
  add(
    header('Foo-Header', 'Foo'),
    header('Bar-Header', 'Bar'),
    headers({ 'Baz1-Header': 'Baz1', 'Baz2-Header': 'Baz2' })
  ),
  please
)

(This also applies for Webhook headers, just use webhookHeader instead of header and webhookHeaders instead of headers).

Like you would think:

import { pipe, gotenberg, merge, please } from 'gotenberg-js-client'

const toMergedPDF = pipe(
  gotenberg('http://localhost:3000'),
  merge,
  please
)

Advanced fine adjustment

There is special function adjust, which you can use to modify any field in prepared internal Request object. You can check internal Request object structure in types. Any object, passed to adjust, will be merged with prepared Request.

For example, you can modify url, if your Gotenberg instance is working behind reverse proxy with some weird url replacement rules:

import { pipe, gotenberg, convert, html, adjust, please } from 'gotenberg-js-client'

// Original Gotenberg HTML conversion endpoint is
//   -> /convert/html
// But your reverse proxy uses location
//   -> /hidden/html/conversion
const toPDF = pipe(
  gotenberg('http://localhost:3000'),
  convert,
  html,
  adjust({ url: '/hidden/html/conversion' }),
  please
)

But, using that function, remember about Peter Parker principle:

"With great power comes great responsibility"

Bonus

If you happen to use this package from JavaScript, you will, obviously, lost type safety, but in return, you can use proposed pipe operator (with Babel plugin), to get beauty like this:

const toPDF = source =>
  source
    |> gotenberg('http://localhost:3000')
    |> convert
    |> html
    |> to(a4, noMargins)
    |> set(filename('out.pdf'))
    |> please

Names clashes

If you don't like to have simple imported names in your namespace, you can use import * syntax:

import * as got from 'gotenberg-js-client'

const toPDF = got.pipe(
  got.gotenberg('http://localhost:3000'),
  got.convert,
  got.html,
  got.please
)

Sponsored

Setplex OTT Platform

Setplex OTT Platform

gotenberg-js-client's People

Contributors

dependabot[bot] avatar dooafus avatar victordidenko avatar xiaojian-hong avatar yumauri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gotenberg-js-client's Issues

Cannot convert xls file due to "context deadline exceeded"

I'm trying to convert xls file(185KB) but always got "context deadline exceeded" error.

I set timeout 30 and pageRanges '1-10' but no luck.

tested using thecodingmachine/gotenberg:6

curl --request POST
--url http://localhost:3001/convert/office
--header 'Content-Type: multipart/form-data'
--form [email protected]
--form waitTimeout=30
--form pageRanges='1-10'
-o result.pdf

in the excel file there are 1656 rows and 3 columns. Looks like this.
image

Is there any way to set timeout more than 30 seconds, or any way to convert partial without "context deadline exceeded" error???

Adding page numbers to PDF

Hello @yumauri ,

I am currently using your package for converting my html files into pdf files. Thanks a lot by the way.
But I'm running into a small issue. Is there any way to show page numbers on the generated PDF? For example "Page 1 of 3" and etc.
I tried doing it in html but I believe the issue is when it comes down to the conversion html only reads one whole page but pdf converts it into multiple.

Your help would be greatly appreciated.

Gotenberg 7, WebHooks Headers and 204 response

Hi,

Firstly, thanks so much for your client library.

We are attempting to use your library to make calls to Gotenberg 7.53. I have read the comments about making the necessary adjustments for version 7 and so far everything seems to work fine when Gotenberg returns a 200 response.

However, we would really like to use the WebHooks feature and we have the following issues -

  1. The WebHook header function seems to use the incorrect name -
    Gotenberg-Webhookurl-${name} instead of Gotenberg-Webhook-Url-${name}

We are currently working around this issue by setting the headers by hand in a custom function within the pipe method.

  1. It seems that Gotenberg return 204 No Content instead of 200 when the WebHook headers are set.

Gottenberg Docs

In your node.ts file it seems that the client is configured to reject all responses other than 200.

req.on('response', (res) => {
      if (res.statusCode === 200) {
        resolve(res)
      } else {
        let error = res.statusCode + ' ' + res.statusMessage

Do you know of anyway to override or workaround this issue this? Currently I am just catching the error and looking for the words '204 No Content'.

Regards,
Tarek

cannot find name URL

The _types.ts & gotenberg.ts is missing the URL import which throws error when building the project ( hopefully I think only backend ) that depends on Gotenberg service.

Error: node_modules/gotenberg-js-client/dist-types/_types.d.ts(68,30): error TS2304: Cannot find name 'URL'.
Error: node_modules/gotenberg-js-client/dist-types/gotenberg.d.ts(3,57): error TS2304: Cannot find name 'URL'.

To re-create:

  • Use gotenberg-js-client on backend project
  • Build the project

`to` type signature does not support UrlRequest

For the code:

pipe(
  gotenberg('http://localhost:3000'),
  convert,
  url,
  to(landscape),
  please
)(address)

TypeScript complains:

Type 'RequestType.Url' is not assignable to type 'RequestType.Html'

in the url line. The actually execution works fine.

Could it be that the function overloading in to.ts lacks this additional signature?

(...opts: ConversionOptions[]): (request: UrlRequest) => UrlRequest

Let me know if I should create a PR!

Thanks

set delay

`
gotenberg('http://localhost:3000/forms/chromium'),
convert,
url,
set({ waitDelay: 10000 }),
request => {
(
request.fields as unknown as {
url: string;
}
).url = request.fields.remoteURL;
delete request.fields.remoteURL;
return request;
},
please,
);

`

Why when adding the set({ waitDelay: 10000 }), it stops working?

New version of Gotenberg 🚀

Hello @yumauri 👋

I've just released version 7.0.0 of Gotenberg 🎉

A lot of minor changes, the best if you wish to update your JS/TS client is to head to the new documentation.

Also, I've added your repository to the awesome list 😄 currently, I've marked it as only compatible with Gotenberg 6.x, but do not hesitate to open a PR when your client is compatible with version 7 👍

PS: if you have any questions, please ask them!

How to set headers for the gotenberg request?

In the README there is an example on how to set the header for the request gotenberg does to an external URL, but there isn't any reference on how to set a header to the request to gotenberg itself.

Maybe if we could pass it to the gotenberg call like this?

const toPDF = pipe(
  gotenberg('https://cloud-run', { headers: { 'Authorization': 'Bearer abc' } }),
  convert,
  office,
  set(filename('result.pdf')),
  please
);

Source name doesn't look like file name

I got this error: Error: Source name "ces La esencia del cristianismo Dios es persona (jóvenes).docx" doesn't look like file name

edit: Seems like the issue is not with the name, but that there is hard cap limit of name length of 50 characters. Can we edit it somehow or at least make it bigger? 50 char names are not that rare.

Same thing with the minimum number of 3 characters - users sometimes do have like 1 char names for whatever reason :)

edit: After testing the problem is with ³ character. Exploring why is that.

Finish tests to get 100% coverage

------------------------|----------|----------|----------|----------|-------------------|
File                    |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------------------|----------|----------|----------|----------|-------------------|
All files               |    58.26 |    58.39 |    70.97 |     58.7 |                   |
 src                    |    64.24 |    62.25 |    81.48 |     65.4 |                   |
  _fields.ts            |      100 |      100 |      100 |      100 |                   |
  _path.ts              |      100 |      100 |      100 |      100 |                   |
  _pipe.ts              |      100 |      100 |      100 |      100 |                   |
  _source-checkers.ts   |      100 |      100 |      100 |      100 |                   |
  _source-converters.ts |        0 |        0 |        0 |        0 |... 23,124,125,127 |
  _type.ts              |      100 |      100 |      100 |      100 |                   |
  convert.ts            |      100 |      100 |      100 |      100 |                   |
  gotenberg.ts          |        0 |        0 |        0 |        0 |... 34,37,45,48,57 |
  html.ts               |      100 |      100 |      100 |      100 |                   |
  index.ts              |        0 |      100 |      100 |        0 |... 16,17,18,19,22 |
  markdown.ts           |      100 |      100 |      100 |      100 |                   |
  merge.ts              |      100 |      100 |      100 |      100 |                   |
  office.ts             |      100 |      100 |      100 |      100 |                   |
  page.ts               |      100 |      100 |      100 |      100 |                   |
  ping.ts               |      100 |      100 |      100 |      100 |                   |
  please.ts             |        0 |        0 |        0 |        0 |... 62,66,67,68,71 |
  set-helpers.ts        |      100 |      100 |      100 |      100 |                   |
  set.ts                |      100 |      100 |      100 |      100 |                   |
  to-helpers.ts         |      100 |      100 |      100 |      100 |                   |
  to.ts                 |      100 |      100 |      100 |      100 |                   |
  url.ts                |      100 |      100 |      100 |      100 |                   |
 src/client             |        0 |        0 |        0 |        0 |                   |
  native.ts             |        0 |        0 |        0 |        0 |... 68,69,73,84,90 |
------------------------|----------|----------|----------|----------|-------------------|

Problem converting docx to pdf format A-1a

Thank you for this amazing library.

I have a NestJs application that has a method that communicates with a docker image of gotenberg7 via this js-client.
I need to convert docx files to pdf with an A-1a format.
What I wrote is

private toPDF = pipe(
    gotenberg(''),
    convert,
    office,
    adjust({
      url: `${this.configService.get(
        'GOTENBERG_URL',
      )}/forms/libreoffice/convert`,
      fields: {
        pdfFormat: 'PDF/A-1a',
      } as any,
    }),
    please,
  );

and the method is

async convertToPdf(
    fileName: string,
    uint8Array: Uint8Array,
  ): Promise<NodeJS.ReadableStream> {
    return await this.toPDF({ 'fileName.pdf': Buffer.from(uint8Array) });
  }

This method is called multiple times because it is trying to convert multiple docx files that will be zipped later on.
When I convert to pdf without adding the pdfFormat field, it works with no errors. But when I add pdfFormat: 'PDF/A-1a' the files are not all converted correctly.
I am testing with two files for now and one out of two is damaged and cannot be read. Every time it's a different pdf out of the two that is damaged. Sometimes both are damaged.
I am not getting why I am having this issue since one of the pdf is converted correctly and I am sending the docx twice.

Got an IncomingMessage instance from the api of /convert/office, is that normal?

Hi~
Firstly, I'm new to Node.js.
I got a problem when I'd like to convert some docs to pdfs. I just followed the documentation described and when I debug the code below, I found it's actually an IncomingMessage instance. Is that normal? I've browsed the issues page. It's seam like no one had the same problem. Doesn't the response return the pdf buffer directly if it would work? How can I get the response body from it? Or is it something I did wrong?
const pdf = await toPDF([docName, docBuffer])
where the docName and docBuffer are variables.
I am using 6.x gotenberg and 0.7.2 of gotenberg-js-client.
In addition, no errors were found in Gotenberg logs, just INFO logs.
Thx!

Addtional code segment:

    const toPDF = pipe(
        gotenberg('http://node04:3000'),
        convert,
        office,
        to(landscape),
        set({
            resultFilename: filename(ossFileName.substring(0, ossFileName.lastIndexOf('.')) + '.pdf'),
            waitTimeout: 20
        }),
        please
    )

using Buffer is undocumented, and not easy to find how to use

It's seems this :

const myBuffer = fs.readFileSync('myDoc.docx');
const pdf = await toPDF(myBuffer);

Doesn't work, because the file name send to gotenberg is 'index.html' ...

After some debug, I found a solution :

const myBuffer = fs.readFileSync('myDoc.docx');
const pdf = await toPDF(["myDoc.dox", myBuffer]);

But it's either undocumented, and maybe need to throw an exception if the fileName is not retrievable with the argument (Buffer, stream ...) ...

Error: 404 Not Found

I had a problem converting from html

The documentation says to specify your host

const toPDF = pipe( gotenberg('http://localhost:3000'), convert, html, please )

But it gave out Error: 404 Not Found

But if specify http://localhost:3000/forms/chromium
it works

I think it's worth mentioning in the documentation =)

index.html covers header.html

Hello
I am sending it like this:

                pdf = await toPDF({"header.html": fs.createReadStream(`${convertPath}header.html`), "index.html": fs.createReadStream(`${convertPath}index.html`)})

and in the resulting pdf I can see the header image I had just barely showing to the left where i put some margins on the config:

            const toPDF = pipe(
                gotenberg(getVariableValue("GOTENBERG_BASE_URL")),
                convert,
                html,
                set({
                    waitTimeout: getVariableValue("ENVIRONMENT") == "dev" ? 30 : 180
                }),
                to({
                    marginTop: margin.top,
                    marginBottom: margin.bot,
                    marginLeft: margin.left,
                    marginRight: margin.right,
                    landscape
                }),
                please
            )

For the record the actual margins used there are 0 bot and top, 0.2 left and right, and I can only see the header.html file I sent barely, and behind the index.html margins.
Any way I could make it appear on top? I tried z-index in css no luck.

When I send it through postman directly to the gotenberg container the header.html shows on top.

Thanks

Can I convert a remote docx (on s3) to PDF?

Not sure what the syntax would be.

I try

    const signedUrl = await this.getSignedURL(bucket, docxKey);
    console.log('signed url: ', signedUrl);
    const toPDF = pipe(
      gotenberg('http://localhost:8008'),
      convert,
      url,
      office,
      set(filename('result.pdf')),
      please
    )

    const pdfStream = await toPDF(signedUrl);

and I always get 404 from Gotenberg as if it wasn't able to fetch the signed url tough it is accessible from curl or browser.

Add a polka/express implementation

Subject

It would be useful to have one example of how to bind this client to a polka and/or express server.

A complete example with a url extension matching .pdf would be enough for a good demo.

Concrete case

I use the Sapper framework which has ssr rendering.

I can create a .pdf.svelte route with html rendering.

I would like to match this kind of route to wrap the renderd html on a pdf file.

How to convert multiple Office to pdf and merge at the same time?

With curl, we can perform something like this
curl --request POST http://localhost:3000/forms/libreoffice/convert --form [email protected] --form [email protected] --form merge=true -o out.pdf

Is that possible to do equivalent in this library? If I try using merge and office together, i get the following message:
Error: Cannot set "Merge" conversion, already set to "Office"

In addition, passing multiple Office files (docx only here) together is also problematic. Here is example:

import * as got from 'gotenberg-js-client'
const toPDF = got.pipe(
  got.gotenberg(''),
  got.convert,
  got.office,
  got.adjust({
    //adjust due to v7
    url: 'http://localhost:3000/forms/libreoffice/convert',
  }),
  got.please,
);
const pdf = await toPDF([
  'file://in1.docx', 
  'file://in2.docx', 
  'file://in3.docx'
]);
pdf.pipe(fs.createWriteStream('out.pdf'))

There is no problem if just having 1 file.

If I have only 2 files, it complain with
Error: Source name "file://in1.docx" doesn't look like file name

If I have 3 or more, it run but the saved file is not valid PDF.

I believe I am not converting multiple files in right way, but I cannot find any documentation of multiple docx file conversion. The HTML one also seems to be one web page as well (but with other assets file to render so multi-files).

Currently, one workaround is convert each of them to PDF one by one, and trigger PDF merge then. However, this will result extra bandwidth for each separate PDF download and upload again for merging.

Cant convert using buffer

Hi,
I tried the convert office file passing buffer but I have no response.

Im downloading a file from s3 (uint8array) converting it to arraybuffer and using:

const toPDF = pipe(
        gotenberg("http://localhost:3000"), 
        convert,
        office,
        set(filename("result.pdf")),
        please
      );
const pdf = await toPDF({ "document.docx": resp.Body.buffer });

Any way to check if the api is up with the ping request? I didnt see it on the doc

url to pdf conversion bad request

hi, im using version 0.7.4 and im trying to use the gotenberg demo to a conversion.

itl works with postman :curl --location 'https://demo.gotenberg.dev/forms/libreoffice/convert'
--form 'files=@"/myFile.docx"'

however i could not make it work using gotenberg-js-client, what am i doing wrong? i keep getting status 404

const { pipe, gotenberg, adjust, add, header, convert, office, url, to, landscape, set, filename, please, } = require('gotenberg-js-client');

async function officeToPdf() {
const toPDF = pipe(
gotenberg(https://demo.gotenberg.dev/forms/chromium),
convert,
office,
please,
)

const res = await toPDF('file://myfile.docx');

return res;

}

Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.

Hi, I wanted to use this JS implementation with direct html injection. But when the formData should be implemented I have this error : Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'
Here is the script I used, is there something wrong ?

  const toPDF = pipe(
    gotenberg('http://localhost:3000'),
    convert,
    html,
    please
  )
  const pdf = await toPDF("<html><head></head><body>Make my day</body></html>")
  pdf.pipe(fs.createWriteStream('index.pdf'))`

404 Not found Error

const {
    pipe,
    gotenberg,
    convert,
    markdown,
    office,
    to,
    landscape,
    set,
    filename,
    please,
  } = require('gotenberg-js-client')
  
  const toPDF = pipe(
    gotenberg('http://localhost:3000'),
    convert,
    office,
    to(landscape),
    set(filename('result.pdf')),
    please
  )
  
  // --- 8< ---
  
  // --- 8< ---
  
app.get('/api/convert_docs',async(req,res)=>{
   
    try {
        const pdf = await toPDF('file://mock_amikus_2.docx')
      
    } catch (error) {
        console.error(error.message)
    }

Usinn gotenberg-js-client in firebase function

I am trying to use gotenberg-js-client module in a firebase function as below:

**exports.officeToPdf = functions.https.onCall((req, res) => {

const https = require('https');

const {
pipe,
gotenberg,
convert,
url,
please,
} = require('gotenberg-js-client');

const signedUrlOptions = {
// stale options persist even after expiration date
action: 'read',
expires: Date.now() + 1000 * 60 * 2, // invalid date after ten minutes pass
};

const toPDF = pipe(
gotenberg('http://localhost:3000'),
convert,
url,
please,
);

admin
.storage()
.bucket()
.file(req)
.getSignedUrl(signedUrlOptions)
// eslint-disable-next-line promise/always-return
.then(url => {
console.log(url[0]);
// eslint-disable-next-line promise/no-nesting
toPDF(new URL(url[0]))
// eslint-disable-next-line promise/always-return
.then(pdf => {
console.log('ok');
console.log(pdf);
})
.catch(error => {
console.log(error);
});
})
.catch(err => {
console.log(err);
});
});**

but it gives error and it says:

Error: connect ECONNREFUSED 127.0.0.1:3000

I think I need to do something with http://localhost:3000 but I don't know what to do.

Could you help me?

Can I convert docx from Buffer?

In the Readme it shows how to convert HTML by passing a string. Let's say I have the docx in a Buffer, can I use it to convert to PDF, instead of having to save it to the filesystem only to be able to post it to gotenberg?

Request body larger than maxBodyLength limit

I have very standard config and I get this error. With Postman my Cloud Run instance works just fine.

const document =  {
    name: '12345.docx',
    encoding: '7bit',
    mimetype: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    data: <Buffer numbers here bla bla ... 407437 more bytes>,
    size: 407487
}
   const {
      pipe,
      gotenberg,
      convert,
      office,
      to,
      landscape,
      set,
      filename,
      please,
    } = require('gotenberg-js-client')

    const toPDF = pipe(
      gotenberg(<CLOUD_RUN_INSTANCE>),
      convert,
      office,
      please
    )
    const pdf = await toPDF({ [`resultAsd.docx`]: document.data })

Option to add http/https agent of my own.

Hi,

What I want to be able to do is send my own HTTP/HTTPS agent - this is to be able to set keepAlive: true.

I tried looking through the library's code but couldn't find a way. (could barely understand what was going on - inexperienced with ts)

Does this option exist today?
Is it possible to add or make a workaround in my project to set it like this?

If its not possible I will have to "wrap" the gotenberg client myself which I really try to avoid.

Thanks :)
Update:
I just noticed you added "adjust" in your latest version.
It looks like it might be able to do what I need.
Can you let me know if this code does it ?

            const toPDF = pipe(
                gotenberg(getVariableValue("GOTENBERG_BASE_URL")),
                convert,
                html,
                // set({
                //     waitDelay: "1.5"
                // }),
                adjust({
                    httpsAgent: new https.Agent({
                        keepAlive: true,
                        maxSockets: 1
                    })
                }),
                to({
                    marginTop: margin.top,
                    marginBottom: margin.bot,
                    marginLeft: margin.left,
                    marginRight: margin.right,
                    landscape
                }),
                please
            )

passing tuples to office conversion doesn't work

On lib version 0.5.0 .

I use function like that :

const a = pipe(gotenberg(process.env.GOTENBERG), convert, office, please)

if I pass a tuples, for example :

a(['aaaa', <readableStream>]);

I got an error :

Error: There are duplicates in file names: index.html

the problem is :
here

the variable tuples contain an array :

[
  [
    "index.html",
    "aaaa"
  ],
  [
    "index.html",
    <readableStream>
  ]
]

so, here , we found some duplicates .


For informations, here,

request.source = [
  "aaaa",
  <readableStream>
  }
]

How to convert images

I can't figure out how to convert images to PDF, although other types are working well. All conversions are sent as a stream, and I thought I would be able to use a dataURI method to embed in an html conversion - something like

<html>
<body>
<img src="data:image/jpg;base64,iVBO ... etc" />
</body>
</html>

However, i always end up with an missing image type icon in the final pdf. I also tried writing a temporary file and specifying it as

'img.png': 'file://xyz.png'

and referencing 'img.png' in the html to be converted,but with the same result. Has anybody managed to convert an image stream to pdf ? Would really appreciate an example of how it's done as this is the cleanest pdf convertor I've found for other types of files and I'd love to use it.

word转pdf, typeError [ERR_INVALID_PROTOCOL]: Protocol "d:" not supported. Expected "https:"

async docx2pdf(wordConfigFilePath, pdfConfigFilePath, fileName) {
const toPDF = pipe(
gotenberg(path.resolve(pdfConfigFilePath)),
convert,
office,
to(landscape),
set(filename(fileName + '.pdf')),
please
);
const pdf = await toPDF({ 'fileName.docx': fs.readFileSync(path.resolve(wordConfigFilePath, fileName + '.docx')) });
},
我想通过docx转pdf 但是出现了这个报错 typeError [ERR_INVALID_PROTOCOL]: Protocol "d:" not supported. Expected "https:"

Files not found were they're not located on the root folder

It seems to have problems with the paths, I was passing the value file:///Users/myuser/file/to/my/project/file.docx

And it retrieves the error:

POST /convert/office 404 9.323 ms - 33
error: General error while uploading a document. 404 Not Found (undefined) {"stack":"Error: 404 Not Found (undefined)\n at IncomingMessage. (/Users/estebanhernandez/Documents/HD/sharedocview/server/node_modules/gotenberg-js-client/dist-node/index.js:44:18)\n at IncomingMessage.emit (events.js:327:22)\n at IncomingMessage.EventEmitter.emit (domain.js:483:12)\n at endReadableNT (_stream_readable.js:1220:12)\n at processTicksAndRejections (internal/process/task_queues.js:84:21)"}
error: 404 Not Found (undefined)

EPIPE Error when generating 10s pdf in parallel

I'm trying this library to call Gotenberg and it works great.

I'm generating around 300 pdf and this trying to call Gotenberg in batch of 10s.

When I do this, the calls start to fail with {"errno":-32,"code":"EPIPE","syscall":"write"}.

Do you have any idea why it might happen ?

Pointing docker url fails

I've mounted a dockerfile with all services needed on my server. But the link with gotenberg does not work. Is this the intended behavior ? Below, I'll share my actual code:

docker-compose.yml

services:
  gotenberg:
    image: thecodingmachine/gotenberg:6
    networks:
      - "mps"
    ports:
      - "4000:3000"
  redis:
    image: "redis"
    networks:
      - "mps"
    ports:
      - "6379:6379"
  server:
    image: node:12
    depends_on: 
      - redis
      - gotenberg
    env_file: ".env"
    volumes:
      - "C:\\Users\\allan\\Documents\\github\\mps\\backend\\:/usr/src/app"
    networks:
      - "mps"
    ports:
      - "3001:3001"
      - "9229:9229"
networks:
  mps:
    driver: bridge

And the script I used

        try {
            const convertToPdf = pipe(
                gotenberg("gotenberg"),
                convert,
                office,
                set(filename('result.pdf')),
                please
            )
            const buff = Buffer.from(file.buffer);
            const converted = await convertToPdf({
                [file.originalname]: buff
            });
            
            return converted
        } catch (err) {
            debugger
        }
    }

Am I doing something wrong ?

Add Merge function usage in documentation like Convert. (How use merge ?)

For two days I have been hard at work merging three files, but unfortunately it still does not work.
I do something like this:

const toMergedPDF = pipe(
            gotenberg('http://localhost:3000'),
            merge,
            please,
        )

const mPdf = await toMergedPDF(
                 [
                     ['file.pdf', 'file://file.pdf'],
                     ['file2.pdf', 'file://file2.pdf'],
                     ['file3.pdf', 'file://file3.pdf'],
                  ]
            )

mPdf.pipe(fs.createWriteStream('final.pdf'));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.