fix pdf building

This commit is contained in:
Joakim Repomaa
2026-02-19 13:13:52 +02:00
parent 209770e8aa
commit 50af9cae3e
14 changed files with 493 additions and 278 deletions

View File

@@ -1,9 +1,14 @@
import type { RequestHandler } from './$types.js';
import type { LaunchOptions } from 'puppeteer';
import puppeteer from 'puppeteer';
import * as cheerio from 'cheerio';
import path from 'path';
import { opendir, writeFile, mkdtemp, copyFile } from 'fs/promises';
import { tmpdir } from 'os';
// This is a dynamic endpoint - not prerenderable
export const prerender = false;
export const prerender = true;
const cwd = process.cwd();
// PDF generation configuration
const PDF_CONFIG = {
@@ -23,13 +28,6 @@ const getLaunchOptions = (): LaunchOptions => {
const chromePath = process.env.PUPPETEER_EXECUTABLE_PATH;
const options: LaunchOptions = {
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--disable-gpu',
],
};
if (chromePath) {
options.executablePath = chromePath;
@@ -37,43 +35,71 @@ const getLaunchOptions = (): LaunchOptions => {
return options;
};
export const GET: RequestHandler = async ({ url }: { url: URL }) => {
// Check if Chrome/Puppeteer is available
const chromePath = process.env.PUPPETEER_EXECUTABLE_PATH;
const isCI = process.env.CI || process.env.CONTINUOUS_INTEGRATION;
if (!chromePath && !isCI) {
// Return 503 if Chrome is not available
return new Response(
JSON.stringify({
error: 'PDF generation not available',
message:
'Chrome/Chromium is not configured. Set PUPPETEER_EXECUTABLE_PATH environment variable.',
}),
{
status: 503,
headers: { 'Content-Type': 'application/json' },
}
);
}
export const GET: RequestHandler = async ({ url, fetch }) => {
const tmpDir = await mkdtemp(path.join(tmpdir(), 'cv-pdf-genration-'));
const tmpFile = (url: string) => {
const filename = path.basename(url);
const tempFile = path.join(tmpDir, filename);
return tempFile;
};
try {
// Get the base URL for the current request
const baseUrl = `${url.protocol}//${url.host}`;
const pdfUrl = `${baseUrl}/print/`;
// Launch browser
const browser = await puppeteer.launch(getLaunchOptions());
const page = await browser.newPage();
const printResponse = await fetch('/print/');
const html = await printResponse.text();
const $ = cheerio.load(html);
const fileDownloads: Record<string, string> = {};
$('script[src], link[rel="stylesheet"], img[src]').each((i, el) => {
if (el.tagName === 'link') {
const href = $(el).attr('href');
if (href) {
const tempFile = (fileDownloads[href] ||= tmpFile(href));
$(el).attr('href', `file://${tempFile}`);
}
} else {
const src = $(el).attr('src');
if (src) {
const tempFile = (fileDownloads[src] ||= tmpFile(src));
$(el).attr('src', `file://${tempFile}`);
}
}
});
$('style[src]').each((i, el) => {
const src = $(el).attr('src');
if (src) {
const tempFile = (fileDownloads[src] ||= tmpFile(src));
$(el).attr('src', `file://${tempFile}`);
}
});
$('style:not([src])').each((i, el) => {
const content = $(el).text();
$(el).text(
content.replaceAll(/(?<=url\(".+?)(?=")/g, (match) => {
const url = match[0];
const tempFile = (fileDownloads[url] ||= tmpFile(url));
return `file://${tempFile}`;
})
);
});
const dir = await opendir('.svelte-kit/output/client/_app/immutable/assets');
for await (const file of dir) {
await copyFile(path.join(file.parentPath, file.name), tmpFile(file.name));
}
const htmlFile = path.join(tmpDir, 'index.html');
await writeFile(htmlFile, $.root().html() ?? '');
// Navigate to the PDF page with increased timeout
// waitUntil: 'networkidle2' waits for 2 network connections to be idle
// This is more lenient than 'networkidle0' which waits for 0 connections
await page.goto(pdfUrl, {
waitUntil: 'networkidle2',
timeout: 120000, // Increased from 30s to 120s to handle slow GitHub API calls
});
await page.goto(`file://${htmlFile}`, { waitUntil: 'networkidle2' });
// Wait for fonts to load
await page.evaluateHandle('document.fonts.ready');
@@ -84,7 +110,7 @@ export const GET: RequestHandler = async ({ url }: { url: URL }) => {
await browser.close();
// Create Blob from buffer for Response
const pdfBlob = new Blob([pdfBuffer as unknown as ArrayBuffer], { type: 'application/pdf' });
const pdfBlob = new Blob([Buffer.from(pdfBuffer).buffer], { type: 'application/pdf' });
// Return PDF with appropriate headers
return new Response(pdfBlob, {