### Install react-pdf-cropper using npm or yarn
Source: https://github.com/shivam27k/react-pdf-cropper/blob/main/README.md
This snippet shows how to install the react-pdf-cropper package using either npm or yarn. These commands are essential for adding the library to your project's dependencies.
```bash
npm install react-pdf-cropper
# or
yarn add react-pdf-cropper
```
--------------------------------
### React PDF Cropper Quick Example with react-pdf-viewer
Source: https://github.com/shivam27k/react-pdf-cropper/blob/main/README.md
Demonstrates integrating react-pdf-cropper with react-pdf-viewer to allow users to crop regions of a PDF. It shows how to manage cropping state, handle crop results, and use custom buttons for controlling the cropping process.
```javascript
import React, { useRef, useState, useCallback } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import { defaultLayoutPlugin } from "@react-pdf-viewer/default-layout";
import PDFCropperOverlay, { handleDownload, CropPreviewButton, CancelCropButton } from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
import "@react-pdf-viewer/default-layout/lib/styles/index.css";
function App() {
const containerRef = useRef();
const [pdfFile, setPdfFile] = useState("/sample.pdf");
const [croppedImage, setCroppedImage] = useState(null);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const [handlers, setHandlers] = useState({});
// Cropper overlay gives you crop/cancel handlers for your own buttons
const getHandlers = useCallback((handlers) => setHandlers(handlers), []);
return (
{isCropping && (
<>
>
)}
setPage(e.currentPage + 1)}
/>
{croppedImage && (
<>
>
)}
);
}
export default App;
```
--------------------------------
### PDFCropperOverlay Component API
Source: https://github.com/shivam27k/react-pdf-cropper/blob/main/README.md
Details the props available for the PDFCropperOverlay component, which is the core component for enabling PDF cropping functionality.
```APIDOC
## PDFCropperOverlay Component API
### Description
This component provides the UI and functionality for cropping regions of a PDF displayed within a React application. It integrates with PDF rendering libraries and allows for customization of the cropping experience.
### Props
#### `containerRef`
- **Type**: `ref`
- **Required**: Yes
- **Description**: A ref to the DOM element that contains the PDF page canvas where cropping will occur.
#### `isCropping`
- **Type**: `boolean`
- **Required**: Yes
- **Description**: Controls whether the cropping overlay is active. This is a controlled prop managed by the parent component.
#### `setIsCropping`
- **Type**: `function`
- **Required**: Yes
- **Description**: A function provided by the parent component to update the `isCropping` state, typically used to close the cropping overlay after an action (e.g., after cropping or canceling).
#### `currentPage`
- **Type**: `number`
- **Required**: Yes
- **Description**: The current page number being displayed and cropped (1-based index).
#### `onCrop`
- **Type**: `function`
- **Required**: No
- **Description**: A callback function that is invoked with the cropped image data URL when a crop operation is completed. The function receives the data URL as its argument: `(dataUrl) => {}`.
#### `getHandlers`
- **Type**: `function`
- **Required**: No
- **Description**: A callback function that provides access to internal handlers for managing the cropping process. It receives an object containing `handleSaveClick` and `stopCropping` functions: `({ handleSaveClick, stopCropping }) => {}`.
#### `watermarkImage`
- **Type**: `string`
- **Required**: No
- **Description**: An optional URL or data URL of an image to be used as a watermark on the cropped output.
#### `watermarkProps`
- **Type**: `object`
- **Required**: No
- **Description**: Optional properties to configure the watermark's appearance, such as `{ opacity, tileWidth, tileHeight }` for tiling effects.
#### `showDefaultButtons`
- **Type**: `boolean`
- **Required**: No
- **Default**: `true`
- **Description**: Determines whether the default crop and cancel buttons are displayed within the cropping UI. Set to `false` to use custom buttons via `getHandlers`.
```
--------------------------------
### PDFCropperOverlay Component Integration with React PDF Viewer
Source: https://context7.com/shivam27k/react-pdf-cropper/llms.txt
Demonstrates how to integrate the PDFCropperOverlay component to enable cropping on a PDF rendered by @react-pdf-viewer. It sets up the viewer, manages cropping state, and displays the cropped image. Requires @react-pdf-viewer and pdf.js.
```jsx
import React, { useRef, useState, useCallback } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import { defaultLayoutPlugin } from "@react-pdf-viewer/default-layout";
import PDFCropperOverlay from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
import "@react-pdf-viewer/default-layout/lib/styles/index.css";
function PDFEditor() {
const containerRef = useRef();
const [pdfFile, setPdfFile] = useState("/sample.pdf");
const [croppedImage, setCroppedImage] = useState(null);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const defaultLayoutPluginInstance = defaultLayoutPlugin();
return (
setPage(e.currentPage + 1)}
/>
{croppedImage && (
)}
);
}
export default PDFEditor;
```
--------------------------------
### Advanced PDF Cropping Control with Callbacks (React)
Source: https://context7.com/shivam27k/react-pdf-cropper/llms.txt
This React component demonstrates how to programmatically control PDF cropping using the react-pdf-cropper library. It manages cropping state, handles crop completion callbacks, saves cropped images, and displays a gallery of cropped images. Dependencies include React, @react-pdf-viewer/core, and react-pdf-cropper. It takes a PDF file as input and outputs cropped image data URLs.
```jsx
import React, { useState, useRef, useCallback, useEffect } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import PDFCropperOverlay from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
function AdvancedCropControl() {
const containerRef = useRef();
const [pdfFile] = useState("/report.pdf");
const [croppedImages, setCroppedImages] = useState([]);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const [cropHistory, setCropHistory] = useState([]);
const handleCrop = useCallback((dataUrl) => {
const timestamp = new Date().toISOString();
const cropData = {
id: Date.now(),
dataUrl,
page,
timestamp,
filename: `crop-page${page}-${Date.now()}.png`
};
setCroppedImages(prev => [...prev, cropData]);
setCropHistory(prev => [...prev, {
action: "crop",
page,
timestamp
}]);
console.log("Crop completed:", cropData);
// Auto-save to backend
saveCropToServer(cropData);
}, [page]);
const saveCropToServer = async (cropData) => {
try {
const response = await fetch("/api/crops", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
page: cropData.page,
image: cropData.dataUrl,
filename: cropData.filename
})
});
if (response.ok) {
console.log("Saved to server successfully");
}
} catch (error) {
console.error("Failed to save:", error);
}
};
const deleteCrop = (id) => {
setCroppedImages(prev => prev.filter(crop => crop.id !== id));
};
useEffect(() => {
// Auto-enable cropping when navigating to specific pages
if (page === 3 || page === 5) {
setIsCropping(true);
}
}, [page]);
return (
Current Page: {page} | Crops: {croppedImages.length}
);
}
export default AdvancedCropControl;
```
--------------------------------
### Downloading Cropped Images with handleDownload
Source: https://github.com/shivam27k/react-pdf-cropper/blob/main/README.md
The handleDownload utility function allows for immediate download of the cropped PDF image. It takes the image data URL and an optional filename as arguments. The default filename is 'cropped-image.png'.
```javascript
import { handleDownload } from 'react-pdf-cropper';
// Assuming imageDataUrl is obtained after cropping
const imageDataUrl = 'data:image/png;base64,...';
handleDownload(imageDataUrl, 'my-custom-filename.png');
// Or using the default filename:
handleDownload(imageDataUrl);
```
--------------------------------
### Customizing Cropper with External UI and Watermarks in React
Source: https://github.com/shivam27k/react-pdf-cropper/blob/main/README.md
Hide default buttons by passing showDefaultButtons={false} and utilize external UI components. Add watermarks by providing a watermarkImage prop and optionally configuring watermarkProps for opacity and tiling.
```javascript
import { PDFCropper } from 'react-pdf-cropper';
function CustomCropper() {
return (
);
}
```
--------------------------------
### React Touch-Enabled Mobile PDF Cropper
Source: https://context7.com/shivam27k/react-pdf-cropper/llms.txt
This React component enables touch-based PDF cropping for mobile devices. It integrates with `@react-pdf-viewer/core` and `react-pdf-cropper` to provide a seamless cropping experience. Dependencies include React, PDF.js, and the react-pdf-cropper library. It takes a PDF file URL as input and outputs a cropped image data URL.
```jsx
import React, { useState, useRef } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import PDFCropperOverlay, { handleDownload } from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
function MobilePDFCropper() {
const containerRef = useRef();
const [pdfFile] = useState("/mobile-document.pdf");
const [croppedImage, setCroppedImage] = useState(null);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const handleCrop = (dataUrl) => {
setCroppedImage(dataUrl);
// Haptic feedback on mobile devices
if (navigator.vibrate) {
navigator.vibrate(50);
}
};
return (
Page {page}
setPage(e.currentPage + 1)}
/>
{croppedImage && (
)}
);
}
export default MobilePDFCropper;
```
--------------------------------
### Using Exported Buttons for Cropping in React
Source: https://github.com/shivam27k/react-pdf-cropper/blob/main/README.md
Integrate CropPreviewButton and CancelCropButton into your custom UI to manage the PDF cropping and preview process. These components require onClick handlers obtained from the getHandlers function.
```javascript
import { CropPreviewButton, CancelCropButton, getHandlers } from 'react-pdf-cropper';
function MyCropperComponent() {
const { handleCrop, handleCancel } = getHandlers();
return (
{/* Your PDF viewer and cropper canvas here */}
);
}
```
--------------------------------
### Download Cropped PDF Images with Custom Filenames (React)
Source: https://context7.com/shivam27k/react-pdf-cropper/llms.txt
This React component demonstrates how to download cropped PDF regions. It utilizes the `handleDownload` function from `react-pdf-cropper` to save the image data URL with a user-specified filename. It supports both single and multiple downloads, with options for processing the image data before saving.
```jsx
import React, { useState, useRef } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import PDFCropperOverlay, { handleDownload } from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
function DownloadableEditor() {
const containerRef = useRef();
const [pdfFile] = useState("/invoice-2024.pdf");
const [croppedImage, setCroppedImage] = useState(null);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const [filename, setFilename] = useState("cropped-invoice");
const handleDownloadClick = () => {
if (croppedImage) {
handleDownload(croppedImage, `${filename}.png`);
}
};
const handleMultipleDownloads = () => {
if (croppedImage) {
// Download in different formats
handleDownload(croppedImage, `${filename}-original.png`);
// You can also process the dataURL before downloading
const processedDataUrl = croppedImage; // Apply filters if needed
handleDownload(processedDataUrl, `${filename}-processed.png`);
}
};
return (
);
}
export default DownloadableEditor;
```
--------------------------------
### Watermarking PDF Cropper Output with Custom Logo
Source: https://context7.com/shivam27k/react-pdf-cropper/llms.txt
Applies a watermark logo to cropped PDF images with options for opacity and tiling. This feature enhances document security or branding. It requires a watermark image path and configurable properties for its appearance. Outputs a watermarked image.
```jsx
import React, { useRef, useState } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import PDFCropperOverlay from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
function WatermarkedCropper() {
const containerRef = useRef();
const [pdfFile] = useState("/confidential-document.pdf");
const [croppedImage, setCroppedImage] = useState(null);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const watermarkProps = {
opacity: 0.15, // 15% opacity for subtle watermark
tileWidth: 100, // Width of each tiled watermark instance
tileHeight: 100 // Height of each tiled watermark instance
};
const handleCrop = (dataUrl) => {
setCroppedImage(dataUrl);
console.log("Cropped image with watermark ready");
// Send to backend or process further
};
return (
setPage(e.currentPage + 1)}
/>
{croppedImage && (
Watermarked image with logo on white strip and tiled pattern:
)}
);
}
export default WatermarkedCropper;
```
--------------------------------
### Custom Button Integration with React PDF Cropper
Source: https://context7.com/shivam27k/react-pdf-cropper/llms.txt
Enables the use of external buttons to control crop and cancel actions, allowing for custom UI and positioning. It requires state management for cropping status and handlers for UI interactions. Outputs a cropped image or cancels the cropping process.
```jsx
import React, { useRef, useState, useCallback } from "react";
import { Worker, Viewer } from "@react-pdf-viewer/core";
import PDFCropperOverlay, {
CropPreviewButton,
CancelCropButton
} from "react-pdf-cropper";
import "@react-pdf-viewer/core/lib/styles/index.css";
function CustomUIExample() {
const containerRef = useRef();
const [pdfFile] = useState("/document.pdf");
const [croppedImage, setCroppedImage] = useState(null);
const [page, setPage] = useState(1);
const [isCropping, setIsCropping] = useState(false);
const [handlers, setHandlers] = useState({});
const getHandlers = useCallback((handlers) => {
setHandlers(handlers);
}, []);
return (
{/* Custom toolbar with external buttons */}
{isCropping && (
<>
💾 Save Crop
❌ Cancel
>
)}
setPage(e.currentPage + 1)}
/>
{croppedImage && (
Cropped Result:
)}
);
}
export default CustomUIExample;
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.