Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Created September 4, 2022 15:13
Show Gist options
  • Save neharkarvishal/d78d7cb946c45574dfb28fe526e719fc to your computer and use it in GitHub Desktop.
Save neharkarvishal/d78d7cb946c45574dfb28fe526e719fc to your computer and use it in GitHub Desktop.
/**
* Generate html string suitable for rendering in PDF
*/
export const generateReportPdfHTML = async (options: GenerateReportPdfOptions): Promise<string> => {
const pages = CustomReportTemplate({ ...options, ssr: true });
const pagesContent = _.map(pages, ({ name, content }) => (
<Flex key={`box-${name}`} flexDir="column" h="100vh" style={{ pageBreakBefore: 'always' }}>
{content}
</Flex>
));
const body = ReactDOMServer.renderToString(
<ChakraProvider theme={theme}>
<>{pagesContent}</>
</ChakraProvider>,
);
const styles = `
<style>
html,
body,
#app {
font-size: 14px;
font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
overflow-x: inherit !important;
overflow-y: inherit !important;
}
*, *::before, *::after {
color: black !important;
}
</style>
`;
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charSet="UTF-8" />
${styles}
</head>
<body>
${body}
</body>
</html>
`;
return html;
};
export class PdfService {
constructor(private configService: ConfigService) {}
async generatePdfWithPuppeteer(html: string): Promise<Buffer> {
const options: puppeteer.PDFOptions = {
format: 'a4',
printBackground: true,
scale: Page.serverScale,
};
const browser = await puppeteer.launch({
executablePath: this.configService.config.pdf.chromiumPath,
args: [
'--headless',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-gpu',
'--disable-software-rasterize',
'--disable-dev-shm-usage',
'--single-process',
'--no-zygote',
],
});
try {
const page = await browser.newPage();
await page.setContent(html, {
waitUntil: 'domcontentloaded',
});
const pdf = await page.pdf(options);
await page.close();
await browser.close();
return pdf;
} finally {
await browser.close();
}
}
generatePDF(html: string): Promise<Buffer> {
return this.generatePdfWithPuppeteer(html);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment