|
| 1 | +const axios = require("axios"); |
| 2 | +const fs = require("fs"); |
| 3 | +const path = require("path"); |
| 4 | +require("dotenv").config(); |
| 5 | + |
| 6 | +// ScreenshotOne API credentials |
| 7 | +const accessKey = process.env.SCREENSHOTONE_ACCESS_KEY; |
| 8 | + |
| 9 | +if (!accessKey) { |
| 10 | + console.error( |
| 11 | + "Error: ScreenshotOne API access key is missing. Please check your .env file." |
| 12 | + ); |
| 13 | + process.exit(1); |
| 14 | +} |
| 15 | + |
| 16 | +// Sleep function for retries |
| 17 | +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 18 | + |
| 19 | +// Function to convert URL to PDF with retries |
| 20 | +async function urlToPdf( |
| 21 | + url, |
| 22 | + outputPath, |
| 23 | + options = {}, |
| 24 | + maxRetries = 3, |
| 25 | + retryDelay = 2000 |
| 26 | +) { |
| 27 | + let retries = 0; |
| 28 | + |
| 29 | + while (retries <= maxRetries) { |
| 30 | + try { |
| 31 | + // Default options for PDF generation |
| 32 | + const defaultOptions = { |
| 33 | + url, |
| 34 | + access_key: accessKey, |
| 35 | + format: "pdf", |
| 36 | + pdf_fit_one_page: "true", |
| 37 | + full_page: "true", |
| 38 | + wait_until: "networkidle0", |
| 39 | + pdf_print_background: "true", |
| 40 | + }; |
| 41 | + |
| 42 | + // Merge default options with custom options |
| 43 | + const mergedOptions = { ...defaultOptions, ...options }; |
| 44 | + |
| 45 | + // Build query string |
| 46 | + const queryString = new URLSearchParams(mergedOptions).toString(); |
| 47 | + |
| 48 | + // ScreenshotOne API endpoint |
| 49 | + const apiUrl = `https://api.screenshotone.com/take?${queryString}`; |
| 50 | + |
| 51 | + console.log( |
| 52 | + `Generating PDF for ${url}... (Attempt ${retries + 1}/${ |
| 53 | + maxRetries + 1 |
| 54 | + })` |
| 55 | + ); |
| 56 | + |
| 57 | + // Make request to ScreenshotOne API |
| 58 | + const response = await axios({ |
| 59 | + method: "get", |
| 60 | + url: apiUrl, |
| 61 | + responseType: "stream", |
| 62 | + timeout: 30000, // 30 seconds timeout |
| 63 | + }); |
| 64 | + |
| 65 | + // Create write stream for output file |
| 66 | + const writer = fs.createWriteStream(outputPath); |
| 67 | + |
| 68 | + // Pipe response data to file |
| 69 | + response.data.pipe(writer); |
| 70 | + |
| 71 | + return new Promise((resolve, reject) => { |
| 72 | + writer.on("finish", () => { |
| 73 | + console.log(`PDF saved to ${outputPath}`); |
| 74 | + resolve(outputPath); |
| 75 | + }); |
| 76 | + writer.on("error", reject); |
| 77 | + }); |
| 78 | + } catch (error) { |
| 79 | + retries++; |
| 80 | + |
| 81 | + if (retries > maxRetries) { |
| 82 | + console.error( |
| 83 | + `Error generating PDF after ${maxRetries + 1} attempts:`, |
| 84 | + error.message |
| 85 | + ); |
| 86 | + if (error.response) { |
| 87 | + console.error( |
| 88 | + "API response status:", |
| 89 | + error.response.status |
| 90 | + ); |
| 91 | + } |
| 92 | + throw new Error( |
| 93 | + `Failed to generate PDF after ${maxRetries + 1} attempts: ${ |
| 94 | + error.message |
| 95 | + }` |
| 96 | + ); |
| 97 | + } |
| 98 | + |
| 99 | + console.warn( |
| 100 | + `Attempt ${retries}/${ |
| 101 | + maxRetries + 1 |
| 102 | + } failed. Retrying in ${retryDelay}ms...` |
| 103 | + ); |
| 104 | + console.error("Error:", error.message); |
| 105 | + |
| 106 | + // Wait before retrying |
| 107 | + await sleep(retryDelay); |
| 108 | + |
| 109 | + // Increase retry delay for next attempt (exponential backoff) |
| 110 | + retryDelay *= 1.5; |
| 111 | + } |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +// Example usage |
| 116 | +async function main() { |
| 117 | + const url = process.argv[2] || "https://www.example.com"; |
| 118 | + const outputPath = process.argv[3] || path.join(__dirname, "output.pdf"); |
| 119 | + |
| 120 | + try { |
| 121 | + // Additional options (optional) |
| 122 | + const options = { |
| 123 | + // Add any custom options here |
| 124 | + // delay: 2000, |
| 125 | + // device_scale_factor: 1, |
| 126 | + // block_ads: 'true', |
| 127 | + // pdf_print_background: 'true', |
| 128 | + // pdf_fit_one_page: 'true', |
| 129 | + }; |
| 130 | + |
| 131 | + // Set retry parameters |
| 132 | + const maxRetries = 3; // Maximum number of retry attempts |
| 133 | + const retryDelay = 2000; // Initial delay between retries in milliseconds |
| 134 | + |
| 135 | + await urlToPdf(url, outputPath, options, maxRetries, retryDelay); |
| 136 | + console.log("PDF generation completed successfully!"); |
| 137 | + } catch (error) { |
| 138 | + console.error("PDF generation failed:", error.message); |
| 139 | + process.exit(1); |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +// Run the main function |
| 144 | +main(); |
0 commit comments