My Docker file
FROM node:18-slim as builder
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json .
COPY yarn.lock .
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
RUN yarn install
COPY . .
RUN yarn run build
FROM node:18-slim
RUN apt-get update && apt-get install -y fonts-liberation
RUN apt-get update && apt-get install -y \
gconf-service \
libasound2 \
libatk1.0-0 \
libc6 \
libcairo2 \
libcups2 \
libdbus-1-3 \
libexpat1 \
libfontconfig1 \
libgcc1 \
libgconf-2-4 \
libgdk-pixbuf2.0-0 \
libglib2.0-0 \
libgtk-3-0 \
libnspr4 \
libpango-1.0-0 \
libx11-xcb1 \
libxcomposite1 \
libxcursor1 \
libxdamage1 \
libxi6 \
libxtst6 \
ca-certificates \
fonts-liberation \
libappindicator1 \
libnss3 \
lsb-release \
xdg-utils \
wget \
--no-install-recommends \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y chromium \
&& rm -rf /var/lib/apt/lists/*
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY --from=builder /usr/src/app/package.json ./package.json
COPY --from=builder /usr/src/app/node_modules ./node_modules
COPY --from=builder /usr/src/app/templates ./templates
COPY --from=builder /usr/src/app/dist ./dist
EXPOSE 80
CMD [ "node", "dist/main.js"]
My Code
static async generatePDFFromNunjucksTemplate(
template: string,
data: Record<string, unknown>,
pdfOptions?: PDFOptions,
logger?: Logger,
): Promise<string> {
const templatePath = Path.join(__dirname, '../../templates');
const engine = nunjucks.configure(templatePath);
const html = engine.render(template, data);
logger?.info('before browser launch');
const browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--disable-gpu',
'--no-zygote',
'--single-process',
],
});
logger?.info('after browser launch');
const page = await browser.newPage();
logger?.info('after page launch');
await page.setContent(html, { waitUntil: 'networkidle0' });
logger?.info('after load content launch');
const pdfBuffer = await page.pdf(
merge(
{
format: 'A4',
printBackground: true,
},
pdfOptions,
),
);
logger?.info('after to pdf');
await browser.close();
logger?.info('after browser close');
return Buffer.from(pdfBuffer).toString('base64');
}
The log after the browser open works fine, it breaks at the newPage
command.
Error
Network.enable timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.