### Convert PDF to Images (Default Output)
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This example demonstrates converting PDF files from both external URLs and local file paths. The output is an array of Uint8Array objects, representing PNG images. It includes a function to save these images to the file system.
```javascript
import fs from 'fs';
import path from 'path';
async function processPDFs() {
const pdf2img = await import("pdf-img-convert");
// Both HTTP, HTTPS, and local paths are supported
const outputWithExternalLink = await pdf2img.convert('https://sedl.org/afterschool/toolkits/science/pdf/ast_sci_data_tables_sample.pdf');
const outputWithLocalSample = await pdf2img.convert('./test_pdfs/sample.pdf');
// OUTPUT OPTIONS ARRAY
const outputs = [outputWithExternalLink, outputWithLocalSample];
const pdfArray = outputs[0]; // Change the index to select different outputs
function saveImages(pdfArray) {
pdfArray.forEach((image, index) => {
const outputPath = path.join('./outputImages', `saveImages_${index}.png`);
fs.writeFile(outputPath, image, (error) => {
if (error) {
console.error(`Error saving image ${index + 1}:`, error);
} else {
console.log(`Image ${index + 1} saved successfully`);
}
});
});
}
// Call the function to save images
saveImages(pdfArray);
}
// Call the async function
processPDFs();
```
--------------------------------
### Convert PDF to Base64 Images with Configuration
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This example shows how to convert a PDF file to Base64 encoded image strings. It utilizes a configuration object to enable 'base64' output and set a 'scale' factor. The resulting Base64 strings are then decoded and saved as PNG files.
```javascript
import fs from 'fs';
import path from 'path';
let config = {
base64: true,
scale: 2
};
async function processPDF() {
const pdf2img = await import("pdf-img-convert");
const outputWithLocalSampleAndConfig = await pdf2img.convert('./examples/example.pdf', config);
const pdfArray = outputWithLocalSampleAndConfig;
function saveBase64Images(pdfArray) {
console.log('Processing base64Images...');
pdfArray.forEach((base64Data, index) => {
// Convert Base64 string to binary buffer
const buffer = Buffer.from(base64Data, 'base64');
// Define an output path
const outputPath = path.join('./outputImages', `saveBase64Image_${index}.png`);
// Write the buffer to a PNG file
fs.writeFile(outputPath, buffer, (error) => {
if (error) {
console.error(`Error saving image ${index + 1} (base64):`, error);
} else {
console.log(`Image ${index + 1} (base64) saved successfully`);
}
});
});
}
// Example usage: call this function with the Base64 array
saveBase64Images(pdfArray);
}
// Call the async function
processPDF();
```
--------------------------------
### Control PDF Image Dimensions with pdf-img-convert.js
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
Illustrates how to control the output image dimensions using 'width', 'height', and 'scale' options within the 'convert' function. Examples cover fixed width, fixed height, scaling for resolution, and applying multiple configurations. Note that 'width' takes precedence if both 'width' and 'height' are specified. Dependencies include 'pdf-img-convert'.
```javascript
import { convert } from 'pdf-img-convert';
// Example 1: Fixed width (height auto-calculated to maintain aspect ratio)
const thumbnails = await convert('./document.pdf', {
width: 200,
base64: true
});
// Example 2: Fixed height (width auto-calculated)
const banners = await convert('./document.pdf', {
height: 400
});
// Example 3: Scale multiplier for high-resolution output
const highRes = await convert('./document.pdf', {
scale: 3.0 // 3x original resolution
});
// Example 4: Multiple configurations for different outputs
const configs = [
{ width: 150, base64: true }, // Thumbnail
{ width: 800 }, // Medium
{ scale: 2.5 } // High-res
];
for (const cfg of configs) {
const images = await convert('./document.pdf', cfg);
console.log(`Generated ${images.length} images with config:`, cfg);
}
// Note: If both width and height are provided, width takes precedence
const imagesByWidth = await convert('./document.pdf', {
width: 1000,
height: 500 // This will be ignored
});
```
--------------------------------
### Import pdf-img-convert Package
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This snippet shows how to import the pdf-img-convert module using dynamic import, which is necessary for using it in an asynchronous context.
```javascript
const pdf2img = await import("pdf-img-convert");
```
--------------------------------
### PDF Conversion Configuration Options (JavaScript)
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This JavaScript object illustrates optional configuration parameters for PDF to image conversion. It allows specifying image dimensions (width, height), scale ratio, rendering specific page numbers, and choosing the output format (Base64 or Uint8Array). Note that if both 'width' and 'height' are provided, 'width' takes precedence.
```javascript
{
width: 100 //Number in px
height: 100 // Number in px
scale: 2
page_numbers: [1, 2, 3] // A list of pages to render instead of all of them
base64: true
}
```
--------------------------------
### Convert PDF to Images with pdf-img-convert.js
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
Demonstrates the primary 'convert' function for PDF to image conversion. It shows how to handle PDFs from URLs and local files, apply configuration options for output format and page selection, and save the resulting image buffers to disk. Dependencies include 'pdf-img-convert', 'fs', and 'path'.
```javascript
import { convert } from 'pdf-img-convert';
import fs from 'fs';
import path from 'path';
// Convert from URL with default settings (returns Uint8Array[])
const images = await convert('https://example.com/document.pdf');
// Convert from local file path
const localImages = await convert('./documents/sample.pdf');
// Convert with configuration options
const config = {
width: 800, // Output width in pixels (height auto-calculated)
scale: 2, // Viewport scale multiplier (default: 1)
page_numbers: [1, 3, 5], // Only convert specific pages (1-indexed)
base64: true // Output as base64 strings instead of Uint8Array
};
const base64Images = await convert('./documents/multi-page.pdf', config);
// Save Uint8Array images to disk
images.forEach((imageBuffer, index) => {
fs.writeFile(
path.join('./output', `page_${index + 1}.png`),
imageBuffer,
(error) => {
if (error) {
console.error(`Error saving page ${index + 1}:`, error);
} else {
console.log(`Page ${index + 1} saved successfully`);
}
}
);
});
// Save base64 images to disk
base64Images.forEach((base64String, index) => {
const buffer = Buffer.from(base64String, 'base64');
fs.writeFileSync(
path.join('./output', `base64_page_${index + 1}.png`),
buffer
);
});
```
--------------------------------
### Convert PDF from Buffer or Uint8Array with pdf-img-convert.js
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
Shows how to use the 'convert' function with in-memory PDF data, such as Buffers or Uint8Arrays. This is useful for handling file uploads or data fetched programmatically. It demonstrates processing these data types and saving the output images. Dependencies include 'pdf-img-convert', 'node-fetch', and 'fs'.
```javascript
import { convert } from 'pdf-img-convert';
import fetch from 'node-fetch';
// Example 1: Convert from Buffer
const pdfBuffer = Buffer.from(await fs.promises.readFile('./document.pdf'));
const imagesFromBuffer = await convert(pdfBuffer, { scale: 1.5 });
// Example 2: Convert from Uint8Array (fetched from URL)
const response = await fetch('https://example.com/document.pdf');
const arrayBuffer = await response.arrayBuffer();
const pdfData = new Uint8Array(arrayBuffer);
const config = {
base64: false, // Output as Uint8Array (default)
page_numbers: [1, 2, 3] // Only first 3 pages
};
const imagesFromUint8 = await convert(pdfData, config);
// Process the images
for (let i = 0; i < imagesFromUint8.length; i++) {
const outputPath = `./output/page_${i + 1}.png`;
await fs.promises.writeFile(outputPath, imagesFromUint8[i]);
console.log(`Saved: ${outputPath}`);
}
```
--------------------------------
### Selective PDF Page Conversion with pdf-img-convert
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
Demonstrates how to use the 'pdf-img-convert' library in Node.js to convert specific pages from PDF documents into images. Covers converting single pages, a defined list of pages, and handling potential errors with invalid page numbers. Dependencies include 'pdf-img-convert' and Node.js 'fs' module.
```javascript
import { convert } from 'pdf-img-convert';
import fs from 'fs';
// Example 1: Convert only first page (thumbnail generation)
const firstPage = await convert('./large-document.pdf', {
page_numbers: [1],
width: 300,
base64: true
});
console.log('Thumbnail generated:', firstPage[0].substring(0, 50) + '...');
// Example 2: Convert specific pages (e.g., summary pages)
const summaryPages = await convert('./report.pdf', {
page_numbers: [1, 2, 10], // Cover, TOC, and conclusion
scale: 1.5
});
summaryPages.forEach((image, index) => {
const pageNumbers = [1, 2, 10];
fs.writeFileSync(`./summary/page_${pageNumbers[index]}.png`, image);
});
// Example 3: Convert every other page
const oddPages = [1, 3, 5, 7, 9];
const oddPageImages = await convert('./presentation.pdf', {
page_numbers: oddPages,
height: 600
});
// Example 4: Error handling for invalid page numbers
try {
// Invalid page numbers are logged but don't throw errors
const images = await convert('./3-page-doc.pdf', {
page_numbers: [1, 5, 10] // Pages 5 and 10 don't exist
});
// Only valid page (1) will be in the output array
console.log(`Converted ${images.length} valid pages`);
} catch (error) {
console.error('Conversion error:', error);
}
```
--------------------------------
### Client-Side PDF Uploader Component (React/Next.js)
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This React component, designed for a client-side environment (e.g., Next.js with 'use client'), allows users to upload multiple PDF files. It handles file selection, validation (limiting to 4 files and ensuring they are PDFs), and form submission. The selected files are appended to a FormData object and sent via a POST request to the '/api/pdf2img' endpoint.
```jsx
"use client";
import React, { useRef, useState } from "react";
export default function PDFUploader() {
const MAX_FILES = 4;
const [fileNames, setFileNames] = useState([]);
const [pdfFiles, setPdfFiles] = useState([]);
const [errorMessage, setErrorMessage] = useState("");
const fileInputRef = useRef(null);
const handleFileChange = (e) => {
const files = Array.from(e.target.files);
if (files.length > MAX_FILES) {
setErrorMessage(`You can only upload a maximum of ${MAX_FILES} files.`);
clearStates();
} else {
const names = files.map((file) => file.name);
const pdfs = files.filter(file => file.type === "application/pdf");
setStates(pdfs, names);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (pdfFiles.length === 0) {
setErrorMessage("No PDF files selected.");
return;
}
try {
const formData = new FormData();
pdfFiles.forEach((file) => {
formData.append("pdfFiles", file); // Key is "pdfFiles"
});
const response = await fetch("/api/pdf2img", {
method: "POST",
body: formData
});
const result = await response.json();
if (result.success) {
clearStates();
alert(`Upload successful: ${result.message}`);
} else {
alert(`Upload failed: ${result.message}`);
}
} catch (error) {
console.error("Upload error:", error);
alert("An error occurred during upload.");
}
};
const clearStates = () => {
setFileNames([]);
setPdfFiles([]);
if (fileInputRef.current) {
fileInputRef.current.value = ""; // Reset the file input via ref
}
};
const setStates = (pdfs, names) => {
setPdfFiles(pdfs);
setFileNames(names);
};
return (
{errorMessage && (
)}
);
}
```
--------------------------------
### POST /api/pdf2img
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
Handles the upload of PDF files and converts each page into a PNG image, saving them to a designated upload directory.
```APIDOC
## POST /api/pdf2img
### Description
This endpoint accepts PDF files via multipart/form-data and converts each page into a PNG image. The converted images are saved to the `public/uploads` directory and their details are returned.
### Method
POST
### Endpoint
/api/pdf2img
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **pdfFiles** (File) - Required - A PDF file to be converted.
### Request Example
```
--boundary
Content-Disposition: form-data; name="pdfFiles"; filename="example.pdf"
Content-Type: application/pdf
[PDF file content]
--boundary--
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **message** (string) - A message describing the outcome of the operation.
- **images** (array) - An array of objects, where each object contains details of a converted image.
- **fileName** (string) - The name of the saved image file.
- **filePath** (string) - The full path to the saved image file.
#### Response Example
```json
{
"success": true,
"message": "Files uploaded successfully",
"images": [
{
"fileName": "example_page_1.png",
"filePath": "/path/to/your/project/public/uploads/example_page_1.png"
}
]
}
```
#### Error Response (400)
- **success** (boolean) - Indicates if the operation was successful.
- **message** (string) - A message describing the error.
#### Error Response Example (400)
```json
{
"success": false,
"message": "No files uploaded"
}
```
#### Error Response (500)
- **success** (boolean) - Indicates if the operation was successful.
- **message** (string) - A message describing the error.
#### Error Response Example (500)
```json
{
"success": false,
"message": "Upload failed"
}
```
```
--------------------------------
### Next.js API Route: Upload and Convert PDF to Images
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This snippet illustrates how to handle PDF file uploads within a Next.js API route. It processes form data, extracts PDF files, and prepares for conversion. It assumes the use of environment variables for path configuration and a 'public/uploads' directory.
```dotenv
ROOT_PATH=./
```
```javascript
import path from "path";
import fs from "fs";
const UPLOAD_DIR = path.resolve(process.env.ROOT_PATH ?? "", "public/uploads");
/*SHARP ENHANCEMENT*/
const writeToDir = async (imageData, fileName, filePath) => {
try {
await fs.promises.writeFile(filePath, imageData);
console.log(`Image processed and saved successfully: ${filePath}`);
return {
fileName: fileName,
filePath: filePath
};
} catch (error) {
console.error("Error processing the image:", error);
return null;
}
};
export const POST = async (req: NextRequest) => {
const pdf2img = await import("pdf-img-convert");
const formData = await req.formData();
const pdfFiles = []
const convertedImages = []
// Loop over the FormData content
for (const [key, value] of formData.entries()) {
if (value instanceof Blob) {
if (key === "pdfFiles") {
pdfFiles.push(value);
}
}
}
// check for file uploads
if (pdfFiles.length === 0) {
return NextResponse.json({
success: false,
message: "No files uploaded"
});
}
}
```
--------------------------------
### Convert PDF Buffer to PNG Images (Node.js)
Source: https://github.com/ol-th/pdf-img-convert.js/blob/master/README.md
This Node.js snippet processes an array of PDF files, converting each page into a PNG image. It reads PDF files as buffers, uses a library to convert them to Base64 encoded images, and then saves these images to a specified directory. The output image file names include the original PDF name and page number. It depends on the `pdf2img` and `fs` modules.
```javascript
for (const file of pdfFiles) {
const pdfBuffer = Buffer.from(await file.arrayBuffer());
const imagePages = await pdf2img.convert(pdfBuffer, { base64: true }); // Ensure base64 is true to get Base64 data
for (let i = 0; i < imagePages.length; i++) {
const imageData = imagePages[i];
const base64Data = imageData.replace(/^data:image\/\w+;base64,/, ""); // Remove Base64 header
const imageBuffer = Buffer.from(base64Data, "base64"); // Convert Base64 to Buffer
const fileName = `${path.basename(file.name, path.extname(file.name))}_page_${i + 1}.png`;
const filePath = path.join(UPLOAD_DIR, fileName);
const writeFile = await writeToDir(imageBuffer, fileName, filePath);
if (writeFile) {
convertedImages.push(writeFile);
}
}
}
// if successfully
return NextResponse.json({
success: true,
message: "Files uploaded successfully",
});
```
--------------------------------
### PDF Preview API Endpoint
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
An Express.js API endpoint that generates a base64-encoded image of the first page of a PDF file. This is suitable for creating previews or thumbnails for web applications.
```APIDOC
## PDF Preview API Endpoint
### Description
Generates a base64-encoded image of the first page of a PDF file for previews.
### Method
GET
### Endpoint
`/api/pdf-preview/:filename`
### Parameters
#### Path Parameters
- **filename** (string) - Required - The name of the PDF file located in the `./pdfs/` directory.
#### Query Parameters
None
#### Request Body
None
### Request Example
`GET /api/pdf-preview/mydocument.pdf`
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **image** (string) - A data URL containing the base64-encoded PNG image of the first page.
- **pageCount** (number) - The number of pages processed (always 1 for this endpoint).
#### Response Example
```json
{
"success": true,
"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
"pageCount": 1
}
```
#### Error Response (500)
- **success** (boolean) - Always false.
- **error** (string) - An error message describing the issue.
#### Error Response Example
```json
{
"success": false,
"error": "File not found."
}
```
```
--------------------------------
### Next.js API Route: PDF to Image Conversion with File Upload
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
This snippet implements a Next.js API route (`/api/pdf2img/route.js`) that handles POST requests. It accepts multiple PDF files, converts each page to a PNG image using base64 encoding, saves these images to the public uploads directory, and returns the details of the saved images. It depends on `pdf-img-convert`, `next/server`, `path`, and `fs`.
```javascript
import { convert } from 'pdf-img-convert';
import { NextRequest, NextResponse } from 'next/server';
import path from 'path';
import fs from 'fs';
const UPLOAD_DIR = path.resolve(process.env.ROOT_PATH ?? '', 'public/uploads');
async function writeToDir(imageData, fileName, filePath) {
try {
await fs.promises.writeFile(filePath, imageData);
console.log(`Image saved: ${filePath}`);
return { fileName, filePath };
} catch (error) {
console.error('Error saving image:', error);
return null;
}
}
export async function POST(req) {
try {
const formData = await req.formData();
const pdfFiles = [];
const convertedImages = [];
// Extract PDF files from form data
for (const [key, value] of formData.entries()) {
if (value instanceof Blob && key === 'pdfFiles') {
pdfFiles.push(value);
}
}
if (pdfFiles.length === 0) {
return NextResponse.json({
success: false,
message: 'No files uploaded'
}, { status: 400 });
}
// Process each PDF file
for (const file of pdfFiles) {
const pdfBuffer = Buffer.from(await file.arrayBuffer());
const imagePages = await convert(pdfBuffer, { base64: true });
for (let i = 0; i < imagePages.length; i++) {
const base64Data = imagePages[i].replace(/^data:image\/\w+;base64,/, '');
const imageBuffer = Buffer.from(base64Data, 'base64');
const fileName = `${path.basename(file.name, '.pdf')}_page_${i + 1}.png`;
const filePath = path.join(UPLOAD_DIR, fileName);
const result = await writeToDir(imageBuffer, fileName, filePath);
if (result) {
convertedImages.push(result);
}
}
}
return NextResponse.json({
success: true,
message: 'Files uploaded successfully',
images: convertedImages
});
} catch (error) {
console.error('Upload error:', error);
return NextResponse.json({
success: false,
message: 'Upload failed'
}, { status: 500 });
}
}
```
--------------------------------
### Batch Convert Multiple PDFs to Images
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
This function processes an array of PDF file paths concurrently, converting each to a series of PNG images. It organizes the output images into subdirectories named after the original PDF files within a specified output directory. The function handles directory creation and provides feedback on the success or failure of each conversion. It requires Node.js with 'fs', 'path', and 'pdf-img-convert' modules.
```javascript
import { convert } from 'pdf-img-convert';
import fs from 'fs';
import path from 'path';
async function batchConvertPDFs(pdfPaths, outputDir) {
// Ensure output directory exists
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const conversions = pdfPaths.map(async (pdfPath) => {
try {
const images = await convert(pdfPath, {
scale: 1.5,
base64: false
});
const baseName = path.basename(pdfPath, '.pdf');
const pdfOutputDir = path.join(outputDir, baseName);
if (!fs.existsSync(pdfOutputDir)) {
fs.mkdirSync(pdfOutputDir, { recursive: true });
}
for (let i = 0; i < images.length; i++) {
const outputPath = path.join(pdfOutputDir, `page_${i + 1}.png`);
await fs.promises.writeFile(outputPath, images[i]);
}
return {
pdf: pdfPath,
success: true,
pageCount: images.length
};
} catch (error) {
return {
pdf: pdfPath,
success: false,
error: error.message
};
}
});
const results = await Promise.all(conversions);
console.log('Batch conversion complete:');
results.forEach(result => {
if (result.success) {
console.log(`✓ ${result.pdf}: ${result.pageCount} pages`);
} else {
console.log(`✗ ${result.pdf}: ${result.error}`);
}
});
return results;
}
// Usage example
const pdfFiles = [
'./documents/report1.pdf',
'./documents/report2.pdf',
'./documents/presentation.pdf'
];
await batchConvertPDFs(pdfFiles, './batch_output');
```
--------------------------------
### Batch Processing Multiple PDFs
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
Process multiple PDF files concurrently with different configurations and organized output. This function takes an array of PDF paths and an output directory, converting each PDF into a set of images saved in a subdirectory named after the original PDF.
```APIDOC
## Batch Processing Multiple PDFs
### Description
Process multiple PDF files concurrently with different configurations and organized output.
### Method
`batchConvertPDFs` (Asynchronous Function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Function Parameters
- **pdfPaths** (Array) - Required - An array of paths to the PDF files to be converted.
- **outputDir** (string) - Required - The directory where the converted images will be saved.
### Request Example
```javascript
const pdfFiles = [
'./documents/report1.pdf',
'./documents/report2.pdf',
'./documents/presentation.pdf'
];
await batchConvertPDFs(pdfFiles, './batch_output');
```
### Response
#### Success Response
The function returns an array of objects, each representing the result of a single PDF conversion.
- **pdf** (string) - The path of the processed PDF file.
- **success** (boolean) - Indicates if the conversion was successful.
- **pageCount** (number) - The number of pages converted (if successful).
- **error** (string) - The error message if the conversion failed.
#### Response Example
```json
[
{
"pdf": "./documents/report1.pdf",
"success": true,
"pageCount": 3
},
{
"pdf": "./documents/report2.pdf",
"success": false,
"error": "File not found."
}
]
```
```
--------------------------------
### Next.js Client-Side PDF File Uploader Component
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
A React component for Next.js applications that allows users to upload PDF files with client-side validation for file type and quantity. It handles file selection, displays selected file names, and submits files to a server API endpoint (/api/pdf2img). Includes error handling and upload state management.
```jsx
// app/components/PDFUploader.jsx
'use client';
import React, { useRef, useState } from 'react';
export default function PDFUploader() {
const MAX_FILES = 4;
const [fileNames, setFileNames] = useState([]);
const [pdfFiles, setPdfFiles] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef(null);
const handleFileChange = (e) => {
const files = Array.from(e.target.files);
if (files.length > MAX_FILES) {
setErrorMessage(`Maximum ${MAX_FILES} files allowed`);
clearStates();
return;
}
const pdfs = files.filter(file => file.type === 'application/pdf');
if (pdfs.length !== files.length) {
setErrorMessage('Only PDF files are allowed');
clearStates();
return;
}
const names = pdfs.map(file => file.name);
setPdfFiles(pdfs);
setFileNames(names);
setErrorMessage('');
};
const handleSubmit = async (e) => {
e.preventDefault();
if (pdfFiles.length === 0) {
setErrorMessage('No PDF files selected');
return;
}
setUploading(true);
setErrorMessage('');
try {
const formData = new FormData();
pdfFiles.forEach(file => {
formData.append('pdfFiles', file);
});
const response = await fetch('/api/pdf2img', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
alert(`Success: ${result.images.length} images created`);
clearStates();
} else {
setErrorMessage(result.message || 'Upload failed');
}
} catch (error) {
console.error('Upload error:', error);
setErrorMessage('Network error occurred');
} finally {
setUploading(false);
}
};
const clearStates = () => {
setFileNames([]);
setPdfFiles([]);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
return (
{fileNames.length > 0 && (
Selected files:
{fileNames.map((name, idx) => (
- {name}
))}
)}
{errorMessage && (
{errorMessage}
)}
);
}
```
--------------------------------
### Generate Base64 Encoded Images from PDFs for Web
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
This code snippet demonstrates how to use pdf-img-convert to generate base64 encoded images from PDF files, making them suitable for embedding in web applications or sending via APIs. It includes two Express.js API endpoints: one for generating a preview of the first page and another for converting an entire PDF (or specific pages based on config) into an array of base64 data URLs. Dependencies include 'pdf-img-convert' and 'express'.
```javascript
import { convert } from 'pdf-img-convert';
import express from 'express';
const app = express();
// API endpoint that returns base64 images
app.get('/api/pdf-preview/:filename', async (req, res) => {
try {
const pdfPath = `./pdfs/${req.params.filename}`;
const base64Images = await convert(pdfPath, {
page_numbers: [1], // First page only for preview
width: 400,
base64: true
});
res.json({
success: true,
image: `data:image/png;base64,${base64Images[0]}`,
pageCount: 1
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Endpoint that returns all pages as base64
app.post('/api/convert-pdf', express.json(), async (req, res) => {
try {
const { pdfUrl, config = {} } = req.body;
const images = await convert(pdfUrl, {
...config,
base64: true
});
const dataUrls = images.map(img => `data:image/png;base64,${img}`);
res.json({
success: true,
images: dataUrls,
count: images.length
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.listen(3000, () => {
console.log('PDF conversion API running on port 3000');
});
```
--------------------------------
### Convert PDF to Base64 Images API Endpoint
Source: https://context7.com/ol-th/pdf-img-convert.js/llms.txt
An Express.js API endpoint that accepts a PDF file (via URL or upload) and converts all its pages into base64-encoded images. It allows for custom conversion configurations.
```APIDOC
## Convert PDF to Base64 Images API Endpoint
### Description
Converts a PDF file to an array of base64-encoded images, with support for custom configurations.
### Method
POST
### Endpoint
`/api/convert-pdf`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **pdfUrl** (string) - Required - The URL or path to the PDF file to convert.
- **config** (object) - Optional - An object containing conversion configuration options (e.g., `scale`, `width`, `page_numbers`).
### Request Example
```json
{
"pdfUrl": "http://example.com/documents/sample.pdf",
"config": {
"width": 800,
"page_numbers": [1, 3, 5]
}
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **images** (Array) - An array of data URLs, each containing a base64-encoded PNG image for each converted page.
- **count** (number) - The total number of images generated.
#### Response Example
```json
{
"success": true,
"images": [
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
],
"count": 2
}
```
#### Error Response (500)
- **success** (boolean) - Always false.
- **error** (string) - An error message describing the issue.
#### Error Response Example
```json
{
"success": false,
"error": "Invalid PDF file."
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.