Skip to content

How to download given url or html as pdf ? #1032

@collegeimprovements

Description

@collegeimprovements

I was trying to download the given url as pdf, but not able to do so with lightpanda.
Is there any recommended way to generate or download pdf with lightpanda ? Can we set header and footer of pdf as well somehow ?
Here is the code generated with ai:

// Get URL from command line arguments
const url = process.argv[2];

if (!url) {
  console.error('Please provide a URL as an argument');
  console.error('Usage: bun generate-pdf-minimal.js <url>');
  process.exit(1);
}

async function generatePDF() {
  try {
    console.log('Creating WebSocket connection to Lightpanda...');
    
    const WebSocket = (await import('ws')).default;
    const ws = new WebSocket('ws://0.0.0.0:9222/');
    
    let messageId = 1;
    const pending = new Map();
    
    // Helper to send CDP commands
    const send = (method, params = {}) => {
      return new Promise((resolve, reject) => {
        const id = messageId++;
        pending.set(id, { resolve, reject });
        ws.send(JSON.stringify({ id, method, params }));
      });
    };
    
    ws.on('message', (data) => {
      const message = JSON.parse(data);
      if (message.id && pending.has(message.id)) {
        const { resolve, reject } = pending.get(message.id);
        pending.delete(message.id);
        if (message.error) {
          reject(new Error(message.error.message));
        } else {
          resolve(message.result);
        }
      }
    });
    
    await new Promise((resolve) => ws.on('open', resolve));
    console.log('Connected!');
    
    // Create a new target (tab)
    console.log('Creating new tab...');
    const { targetId } = await send('Target.createTarget', { url: 'about:blank' });
    
    // Attach to the target
    const { sessionId } = await send('Target.attachToTarget', {
      targetId,
      flatten: true
    });
    
    // Helper to send commands to the page session
    const pageCommand = (method, params = {}) => {
      return send('Target.sendMessageToTarget', {
        sessionId,
        message: JSON.stringify({ id: messageId++, method, params })
      });
    };
    
    // Enable Page domain
    await pageCommand('Page.enable');
    
    console.log(`Navigating to ${url}...`);
    await pageCommand('Page.navigate', { url });
    
    // Wait for load
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    console.log('Generating PDF...');
    const pdfResult = await pageCommand('Page.printToPDF', {
      format: 'A4',
      printBackground: true
    });
    
    // The result is nested in the response
    const pdfData = JSON.parse(pdfResult).result.data;
    
    // Save PDF
    const fs = await import('fs/promises');
    const path = await import('path');
    const timestamp = Date.now();
    const pdfFileName = `output-${timestamp}.pdf`;
    const fullPath = path.resolve(process.cwd(), pdfFileName);
    
    const pdfBuffer = Buffer.from(pdfData, 'base64');
    await fs.writeFile(fullPath, pdfBuffer);
    
    console.log(`\n✅ PDF saved successfully!`);
    console.log(`   Path: ${fullPath}`);
    console.log(`   Size: ${(pdfBuffer.length / 1024).toFixed(2)} KB`);
    
    ws.close();
    
  } catch (error) {
    console.error('Error:', error);
    process.exit(1);
  }
}

generatePDF();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions