### Package Installation and Basic Usage (React) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Demonstrates how users will install the 'react-pdf-annotator-v2' package using npm and provides a basic React component example to integrate the PdfViewer. It includes importing the component and its associated CSS. ```bash npm install react-pdf-annotator-v2 ``` ```tsx import React from 'react'; import { PdfViewer } from 'react-pdf-annotator-v2'; import 'react-pdf-annotator-v2/dist/style.css'; function App() { return (
); } ``` -------------------------------- ### Usage Example with External Storage (React/TSX) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Demonstrates integrating the PdfViewer component with external storage (backend/localStorage) for annotations. It shows how to pass initial annotation state via props and handle saving annotations using the onSave callback. Props take precedence over PDF metadata. ```tsx // Load annotations from your backend/localStorage const savedData = await fetchAnnotationsFromBackend(pdfId); saveToBackend(pdfId, data)} /> ``` -------------------------------- ### Test Local Package Installation Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Demonstrates how to create a local package archive using `npm pack` and then install it in a test project. This allows for thorough local testing before publishing to NPM. ```bash npm pack npm install /path/to/react-pdf-annotator-v2-1.0.0.tgz ``` -------------------------------- ### Install react-pdf-annotator-v2 using npm, yarn, or pnpm Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This snippet shows how to install the react-pdf-annotator-v2 package using different package managers. Ensure you have Node.js and a package manager installed. ```bash npm install react-pdf-annotator-v2 ``` ```bash yarn add react-pdf-annotator-v2 ``` ```bash pnpm add react-pdf-annotator-v2 ``` -------------------------------- ### Access PDF Annotator Ref Methods (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Demonstrates how to use a ref to access methods of the PdfViewer component. It shows how to programmatically retrieve annotation data and get the annotated PDF as a blob. ```typescript const pdfViewerRef = useRef(null); // Get annotation data programmatically const data = pdfViewerRef.current?.getAnnotationData(); // Get annotated PDF blob const blob = await pdfViewerRef.current?.getAnnotatedDocument(); ``` -------------------------------- ### Update package.json Homepage URL Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Guides on updating the 'homepage' field in package.json to the project's main page on GitHub. This provides a central link for users to find more information about the package. ```json { "homepage": "https://github.com/yourusername/your-repo#readme" } ``` -------------------------------- ### React PDF Annotator v2: Get Annotated Document and Data via Ref Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This example illustrates how to use a ref to programmatically interact with the PdfViewer component. It shows how to get the annotated PDF as a Blob or URL using `getAnnotatedDocument` and `getAnnotatedDocumentUrl`, and how to retrieve annotation data and history state using `getAnnotationData`. Remember to revoke object URLs when no longer needed. ```tsx import { useRef } from 'react'; import { PdfViewer, PdfViewerRef } from 'react-pdf-annotator-v2'; function App() { const pdfViewerRef = useRef(null); const handleSave = async () => { if (!pdfViewerRef.current) return; // Get as Blob const blob = await pdfViewerRef.current.getAnnotatedDocument(); if (blob) { // Upload to server const formData = new FormData(); formData.append('file', blob, 'annotated.pdf'); await fetch('/api/upload', { method: 'POST', body: formData }); } }; const handlePreview = async () => { if (!pdfViewerRef.current) return; // Get as URL for preview const url = await pdfViewerRef.current.getAnnotatedDocumentUrl(); if (url) { window.open(url, '_blank'); // Remember to revoke URL when done: URL.revokeObjectURL(url) } }; // Get annotation data separately (without generating PDF) const handleGetAnnotationData = () => { if (!pdfViewerRef.current) return; const data = pdfViewerRef.current.getAnnotationData(); console.log('Current annotations:', data.annotations); console.log('History state:', data.historyState); // Save to database, send to API, etc. fetch('/api/save-annotations', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); }; return ( <> ); } ``` -------------------------------- ### PdfViewer Ref Methods Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Methods available through the PdfViewer component's ref for programmatic access to annotation data and the annotated document. ```APIDOC ## PdfViewer Ref Methods ### Description Methods accessible via the PdfViewer component's ref to programmatically retrieve annotation data or the annotated PDF document. ### Method N/A (Ref Methods) ### Endpoint N/A (Ref Methods) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Ref Methods - **getAnnotationData()** - Returns the current annotation data as an object. - **getAnnotatedDocument()** - Returns a Promise that resolves to a Blob representing the PDF with annotations applied. ### Request Example ```javascript const pdfViewerRef = useRef(null); // Get annotation data programmatically const data = pdfViewerRef.current?.getAnnotationData(); // Get annotated PDF blob const blob = await pdfViewerRef.current?.getAnnotatedDocument(); ``` ### Response #### Success Response (200) - **getAnnotationData()**: Returns an object containing annotation data. - **getAnnotatedDocument()**: Returns a Blob object. #### Response Example ```json { "annotationData": { /* ... annotation details ... */ }, "annotatedDocumentBlob": "" } ``` ``` -------------------------------- ### Custom Integration Example (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/FIX_DOUBLE_ANNOTATIONS.md Shows how to integrate the `PdfViewer` component into a custom application. The `onSave` prop is triggered for metadata-only downloads, while the `onPrint` prop is triggered for visually rendered PDFs, allowing developers to handle these distinct outputs appropriately. ```typescript { // Download callback - metadata only saveToBackend(data); }} onPrint={(data) => { // Print callback - rendered version logPrintEvent(data); }} /> ``` -------------------------------- ### PdfViewer Component Props Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Props available for the PdfViewer component to configure its behavior and handle events. ```APIDOC ## PdfViewer Component Props ### Description Props to configure the PdfViewer component, including the file source, initial state, and save callbacks. ### Method N/A (Component Props) ### Endpoint N/A (Component Props) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Props - **fileUrl** (string) - Required - The URL of the PDF file to display. - **fileName** (string) - Required - The name of the PDF file. - **initialHistoryState** (HistoryState) - Optional - Overrides the initial history state, useful for loading saved annotations. - **onSave** (function) - Optional - A callback function that is invoked when the user triggers a save action, providing the annotation data. ### Request Example N/A ### Response #### Success Response (200) N/A (Component Props) #### Response Example N/A ``` -------------------------------- ### Define Annotation Types and Examples in TypeScript Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt This snippet defines various annotation types supported by the library, including Pen, Text, Rectangle, Stamp, and Signature annotations. It also shows example objects for each type and how they are structured within an Annotations collection. Dependencies include the 'react-pdf-annotator-v2' types. ```typescript import type { AnnotationTool, Annotation, PenAnnotation, HighlighterAnnotation, TextAnnotation, RectangleAnnotation, CircleAnnotation, UnderlineAnnotation, StrikeoutAnnotation, SquigglyAnnotation, StampAnnotation, ImageAnnotation, Point, Annotations } from 'react-pdf-annotator-v2'; // Available annotation tools type AnnotationTool = | 'SELECT' // Select and move annotations | 'PAN' // Pan/scroll the document | 'PEN' // Freehand drawing | 'HIGHLIGHTER' // Semi-transparent highlighting | 'TEXT' // Text boxes | 'RECTANGLE' // Rectangle shapes | 'CIRCLE' // Ellipse shapes | 'UNDERLINE' // Underline markup | 'STRIKETHROUGH'// Strikethrough markup | 'SQUIGGLY' // Squiggly underline | 'STAMP' // Pre-defined stamps | 'SIGNATURE' // Signature images | 'INITIALS'; // Initials images // Example annotation objects const penAnnotation: PenAnnotation = { id: 'unique-id-1', page: 1, type: 'PEN', points: [{ x: 100, y: 100 }, { x: 150, y: 120 }], color: '#000000', strokeWidth: 2 }; const textAnnotation: TextAnnotation = { id: 'unique-id-2', page: 1, type: 'TEXT', x: 50, y: 200, width: 200, height: 50, content: 'Comment text here', fontSize: 16, color: '#3b82f6', strokeWidth: 1 }; const rectangleAnnotation: RectangleAnnotation = { id: 'unique-id-3', page: 2, type: 'RECTANGLE', x: 100, y: 100, width: 200, height: 150, color: '#ef4444', strokeWidth: 2 }; const stampAnnotation: StampAnnotation = { id: 'unique-id-4', page: 1, type: 'STAMP', x: 300, y: 50, width: 140, height: 55, text: 'APPROVED', fontSize: 18, color: '#22c55e', strokeWidth: 2, timestamp: '1/15/2024, 10:30:00 AM' }; const signatureAnnotation: ImageAnnotation = { id: 'unique-id-5', page: 3, type: 'SIGNATURE', x: 100, y: 500, width: 150, height: 75, imageData: 'data:image/png;base64,...', // Base64 signature image color: '#000000', strokeWidth: 0 }; // Annotations collection structure const annotations: Annotations = { 1: [penAnnotation, textAnnotation, stampAnnotation], 2: [rectangleAnnotation], 3: [signatureAnnotation] }; ``` -------------------------------- ### Specify Peer Dependencies (JSON) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md Lists the required peer dependencies for the `react-pdf-annotator-v2-package`, specifically React and React DOM versions 18.0.0 or higher. Ensure these are installed in your project to avoid compatibility issues. ```json { "react": "^18.0.0", "react-dom": "^18.0.0" } ``` -------------------------------- ### PdfViewerRef Methods Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This section outlines the methods available when using a ref with the PdfViewer component, including getting the annotated document, its URL, and annotation data. ```APIDOC ## PdfViewerRef Methods ### Description Methods available when using a ref with the PdfViewer component. ### Method - **getAnnotatedDocument()** - Returns the current PDF with annotations as a Blob. - **getAnnotatedDocumentUrl()** - Returns an object URL of the annotated PDF (remember to revoke when done). - **getAnnotationData()** - Returns current annotations and history state without generating PDF. ### Parameters #### Path Parameters - **N/A** #### Query Parameters - **N/A** #### Request Body - **N/A** ### Request Example ```json { "example": "N/A" } ``` ### Response #### Success Response (200) - **getAnnotatedDocument()**: Promise - **getAnnotatedDocumentUrl()**: Promise - **getAnnotationData()**: AnnotationExportData #### Response Example ```json { "example": "Refer to method descriptions for return types." } ``` ``` -------------------------------- ### Use Default Configuration Constants in TypeScript Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt This snippet demonstrates how to import and use default configuration constants like colors, stroke widths, font sizes, and available stamps from the library. It also includes an example of a custom toolbar component that utilizes these constants for user input controls. Dependencies include the 'react-pdf-annotator-v2' package. ```typescript import { DEFAULT_COLOR, DEFAULT_STROKE_WIDTH, DEFAULT_FONT_SIZE, STAMPS, FONT_SIZES, STROKE_WIDTHS } from 'react-pdf-annotator-v2'; // Available stamps const STAMPS = [ 'APPROVED', 'CONFIDENTIAL', 'DRAFT', 'FINAL', 'FOR REVIEW', 'REVISED', 'ASAP', 'VOID' ]; // Example: Custom toolbar using constants function CustomToolbar({ onColorChange, onStrokeChange, onFontChange }) { return (
onColorChange(e.target.value)} />
); } ``` -------------------------------- ### Define PDF Viewer Component Props (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Defines the properties for the PdfViewer component. It includes the URL and filename of the PDF, an optional initial history state to override metadata, and a callback function for saving annotations. ```typescript interface PdfViewerProps { fileUrl: string; fileName: string; initialHistoryState?: HistoryState; // Override metadata onSave?: (data: AnnotationExportData) => void; // Callback on download } ``` -------------------------------- ### Load Annotations from PDF Metadata (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Loads annotations by checking the PDF's Subject metadata field for the 'PDF_ANNOTATOR_DATA::' prefix. If found, it parses the JSON string to restore the annotation history. This process is prioritized after checking for initial props. ```typescript const subject = pdfDoc.getSubject(); if (subject.startsWith('PDF_ANNOTATOR_DATA::')) { // Parse and load the annotations const historyState = JSON.parse(subject.substring(22)); setHistoryState(historyState); } ``` -------------------------------- ### Metadata Storage Format (JSON) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Illustrates the JSON structure used for storing annotation history within the PDF metadata. It includes an array for history entries, where each entry can contain annotations organized by page number, and an index to track the current state. ```json { "history": [ { "1": [/* page 1 annotations */], "2": [/* page 2 annotations */] } ], "index": 0 } ``` -------------------------------- ### Login to NPM Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PUBLISH.md Logs the user into their NPM account using provided credentials. This is a prerequisite for publishing packages. ```bash npm login ``` -------------------------------- ### Publish Package to NPM Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Commands for publishing your package to NPM. Includes the standard publish command and the command for publishing scoped packages with public access. ```bash # Build the package npm run build:lib # Publish to NPM npm publish # Or for scoped packages: npm publish --access public ``` -------------------------------- ### Local Testing and Building Commands Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Provides essential bash commands for local development and testing of the NPM package. 'npm pack' creates a distributable .tgz file, while 'npm run build:lib' compiles the library for distribution. ```bash # Test Locally npm pack # This creates a .tgz file you can install in another project # Build the Package npm run build:lib ``` -------------------------------- ### Test Package Locally with NPM Pack Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PUBLISH.md Creates a compressed tarball (.tgz) of the package for local testing. This allows verification of the package before publishing to the NPM registry. ```bash npm pack ``` ```bash npm install /path/to/react-pdf-annotator-v2-1.0.0.tgz ``` -------------------------------- ### Build Library with NPM Script Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PUBLISH.md Executes the build script defined in package.json, which compiles TypeScript, bundles the library using Vite, and generates declaration files, outputting to the 'dist/' folder. ```bash npm run build:lib ``` -------------------------------- ### Render PDF Viewer with Annotations in React Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt Demonstrates how to use the `PdfViewer` component to render a PDF with annotation capabilities. It includes event handlers for annotation changes, saving, and printing, as well as methods for programmatically interacting with the annotated document. Requires 'react-pdf-annotator-v2' and its CSS. ```tsx import React, { useRef } from 'react'; import { PdfViewer, PdfViewerRef, Annotations, AnnotationExportData } from 'react-pdf-annotator-v2'; import 'react-pdf-annotator-v2/dist/style.css'; function DocumentViewer() { const pdfRef = useRef(null); // Track annotation changes in real-time const handleAnnotationsChange = (annotations: Annotations) => { console.log('Annotations updated:', annotations); // annotations structure: { 1: [annotation1, annotation2], 2: [...] } // Keys are page numbers, values are arrays of annotations }; // Called when user downloads the PDF const handleSave = (data: AnnotationExportData) => { console.log('Document saved with annotations:', data.annotations); console.log('History state for restore:', data.historyState); // Save to backend, localStorage, etc. fetch('/api/save-annotations', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); }; // Called when user prints the PDF const handlePrint = (data: AnnotationExportData) => { console.log('Document printed'); }; // Programmatically get the annotated document const downloadAnnotated = async () => { if (!pdfRef.current) return; // Get as Blob for upload const blob = await pdfRef.current.getAnnotatedDocument(); if (blob) { const formData = new FormData(); formData.append('file', blob, 'annotated.pdf'); await fetch('/api/upload', { method: 'POST', body: formData }); } }; // Get as URL for preview const previewAnnotated = async () => { if (!pdfRef.current) return; const url = await pdfRef.current.getAnnotatedDocumentUrl(); if (url) { window.open(url, '_blank'); // Remember to revoke: URL.revokeObjectURL(url) } }; // Get annotation data without generating PDF const getAnnotationData = () => { if (!pdfRef.current) return; const data = pdfRef.current.getAnnotationData(); console.log('Current annotations:', data.annotations); console.log('History for undo/redo:', data.historyState); return data; }; return (
); } ``` -------------------------------- ### Import and Use React PDF Annotator Component Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Shows the basic import statements required to use the `PdfViewer` component and its associated CSS from the `react-pdf-annotator-v2` package in a React project. ```tsx import { PdfViewer } from 'react-pdf-annotator-v2'; import 'react-pdf-annotator-v2/dist/style.css'; ``` -------------------------------- ### Build Configuration (vite.config.ts) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Configures Vite for building the library, specifying the entry point, external dependencies, output formats (UMD and ES), and CSS bundling. It ensures that React and ReactDOM are treated as peer dependencies. ```typescript import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import dts from 'vite-plugin-dts'; import cssBundle from 'vite-plugin-css-bundle'; export default defineConfig({ plugins: [ react(), dts({ insertTypesEntry: true, }), cssBundle(), ], build: { lib: { entry: 'lib/index.ts', name: 'ReactPdfAnnotator', formats: ['es', 'umd'], fileName: (format) => `react-pdf-annotator.${format}.js`, }, rollupOptions: { external: ['react', 'react-dom', 'react-pdf', 'pdfjs-dist'], output: { globals: { react: 'React', 'react-dom': 'ReactDOM', 'react-pdf': 'ReactPdf', 'pdfjs-dist': 'PdfjsDist' }, }, }, sourcemap: true, }, css: { // Enable Tailwind CSS processing postcss: { plugins: [ require('tailwindcss'), require('autoprefixer'), ], }, }, }); ``` -------------------------------- ### React PDF Annotator v2: Read-only Mode Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This example shows how to render the PdfViewer component in a read-only mode, disabling all annotation tools. This is achieved by passing the `readonly` prop with a value of `true`. ```tsx ``` -------------------------------- ### Basic PDF Viewer Integration in React Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md Demonstrates how to integrate the PdfViewer component into a React application. It requires importing the component and its CSS, then rendering it with a file URL and file name. The viewer is typically wrapped in a div with a defined height for proper rendering. ```tsx import React from 'react'; import { PdfViewer } from 'react-pdf-annotator-v2'; import 'react-pdf-annotator-v2/dist/style.css'; function App() { return (
); } export default App; ``` -------------------------------- ### API Usage Example (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/FIX_DOUBLE_ANNOTATIONS.md Demonstrates how developers can use the updated `PdfViewer` component API. `getAnnotatedDocument()` retrieves an editable PDF with metadata only. The internal `generateAnnotatedPdf` function can be called with `renderAnnotations=true` to obtain a visually rendered PDF. ```typescript // Get editable PDF (metadata only) const blob = await pdfViewerRef.current?.getAnnotatedDocument(); // Get visual PDF (rendered) const generateAnnotatedPdf = async () => { // Internal: call with renderAnnotations=true }; ``` -------------------------------- ### Update LICENSE File Copyright Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Provides the format for updating the copyright notice in the LICENSE file, including the current year and your name. This is essential for legal compliance and clarity. ```text Copyright (c) 2025 [Your Name] ``` -------------------------------- ### Library Entry Point (lib/index.ts) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Defines the main export point for the NPM package, exposing the primary PdfViewer component, sub-components, hooks, types, and constants. It also imports and bundles the necessary CSS styles. ```typescript import './style.css'; export { PdfViewer } from './components/PdfViewer'; export { AnnotationToolbar } from './components/AnnotationToolbar'; export { AnnotationLayer } from './components/AnnotationLayer'; export { useAnnotationHistory } from './hooks/useAnnotationHistory'; export * from './types'; export * from './constants'; export * from './utils'; ``` -------------------------------- ### Package Configuration (package.json) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Configures the NPM package by setting metadata, entry points, dependencies, and build scripts. It enables publishing by removing the 'private' flag and specifies different module formats for compatibility. ```json { "name": "your-unique-package-name", "version": "1.0.0", "description": "A React component for annotating PDF documents.", "keywords": [ "react", "pdf", "annotation", "viewer" ], "author": "Your Name ", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/yourusername/your-repo.git" }, "main": "dist/react-pdf-annotator.umd.js", "module": "dist/react-pdf-annotator.es.js", "types": "dist/index.d.ts", "exports": { ".": { "import": "./dist/react-pdf-annotator.es.js", "require": "./dist/react-pdf-annotator.umd.js", "types": "./dist/index.d.ts" } }, "files": [ "dist", "README.md", "LICENSE" ], "scripts": { "build:lib": "vite build --config vite.config.ts", "prepublishOnly": "npm run build:lib" }, "peerDependencies": { "react": "^17.0.0 || ^18.0.0", "react-dom": "^17.0.0 || ^18.0.0" }, "devDependencies": { "@types/react": "^18.0.0", "@types/react-dom": "^18.0.0", "react": "^18.0.0", "react-dom": "^18.0.0", "vite": "^4.0.0", "vite-plugin-dts": "^1.0.0", "@vitejs/plugin-react": "^3.0.0", "typescript": "^4.9.0", "vite-plugin-css-bundle": "^1.0.0", "@types/node": "^18.0.0", "tailwindcss": "^3.0.0" }, "dependencies": { "react-pdf": "^7.0.0", "pdfjs-dist": "^3.0.0" } } ``` -------------------------------- ### Save Annotations to PDF Metadata (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/METADATA_GUIDE.md Saves annotations and undo/redo history to the PDF's Subject metadata field. The entire history is saved if metadata is under 32KB; otherwise, only current annotations are saved. This function is crucial for preserving annotation state within the PDF file. ```typescript pdfDoc.setSubject('PDF_ANNOTATOR_DATA::' + JSON.stringify(historyState)); ``` -------------------------------- ### Update package.json Repository URL Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Details the process of updating the 'repository.url' field in package.json to point to your GitHub repository. This helps users find the source code and contribute. ```json { "repository": { "type": "git", "url": "https://github.com/yourusername/your-repo.git" } } ``` -------------------------------- ### Publish Package to NPM Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PUBLISH.md Publishes the package to the NPM registry. For scoped packages (e.g., @username/package), the --access public flag is required. ```bash npm publish ``` ```bash npm publish --access public ``` -------------------------------- ### Available Exports Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md Lists the main components, types, sub-components, hooks, and constants that are exported from the react-pdf-annotator-v2 package. ```APIDOC ## Available Exports ### Description Lists the main components, types, sub-components, hooks, and constants exported from the package. ### Code ```tsx // Main Component and Types import { PdfViewer } from 'react-pdf-annotator-v2'; import type { PdfViewerRef, AnnotationExportData } from 'react-pdf-annotator-v2'; // Sub-components (for custom layouts) import { PdfPage, Toolbar, AnnotationLayer, SignatureModal } from 'react-pdf-annotator-v2'; // Hooks import { useAnnotationHistory } from 'react-pdf-annotator-v2'; import type { HistoryState } from 'react-pdf-annotator-v2'; // Types import type { AnnotationTool, Annotation, Annotations, PenAnnotation, TextAnnotation, // ... other types } from 'react-pdf-annotator-v2'; // Constants import { DEFAULT_COLOR, DEFAULT_STROKE_WIDTH, COLORS } from 'react-pdf-annotator-v2'; ``` ``` -------------------------------- ### Import Constants for Default Settings in React PDF Annotator Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This code demonstrates importing default constants such as colors and stroke widths from the react-pdf-annotator-v2 package. These constants can be used to configure the default appearance and behavior of annotation tools. ```tsx // Constants import { DEFAULT_COLOR, DEFAULT_STROKE_WIDTH, COLORS } from 'react-pdf-annotator-v2'; ``` -------------------------------- ### TypeScript Configuration (tsconfig.json) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Configures TypeScript for library compilation, enabling declaration file generation (`.d.ts`) and source mapping for better developer experience. It also specifies exclusions for build and configuration files. ```json { "compilerOptions": { "target": "ES2019", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "node", "jsx": "react-jsx", "declaration": true, "declarationMap": true, "sourceMap": true, "outDir": "./dist", "rootDir": "./lib", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "allowSyntheticDefaultImports": true }, "include": ["lib/**/*"], "exclude": ["node_modules", "dist", "vite.config.ts", "*.config.ts"] } ``` -------------------------------- ### Import Main Component and Types for React PDF Annotator Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This code demonstrates the primary imports required to use the PdfViewer component and its associated types from the react-pdf-annotator-v2 package. It includes the main component and reference types. ```tsx // Main Component and Types import { PdfViewer } from 'react-pdf-annotator-v2'; import type { PdfViewerRef, AnnotationExportData } from 'react-pdf-annotator-v2'; ``` -------------------------------- ### Load Initial Annotations with History State Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt Pre-populates the PDF viewer with existing annotations, preserving the undo/redo history. It fetches annotation data from an API endpoint and sets either the `historyState` for full history or `initialAnnotations` for basic annotation data. ```tsx import React, { useState, useEffect } from 'react'; import { PdfViewer, HistoryState, Annotation, Annotations } from 'react-pdf-annotator-v2'; import 'react-pdf-annotator-v2/dist/style.css'; function DocumentWithSavedAnnotations() { const [historyState, setHistoryState] = useState(); const [initialAnnotations, setInitialAnnotations] = useState(); // Load full history state (preserves undo/redo) const loadWithHistory = async () => { const response = await fetch('/api/annotations/doc123'); const data = await response.json(); // data.historyState = { history: [...], index: 0 } setHistoryState(data.historyState); }; // Load annotations only (no undo history) const loadAnnotationsOnly = async () => { const response = await fetch('/api/annotations/doc123/simple'); const annotations: Annotations = await response.json(); // annotations = { 1: [{type: 'PEN', ...}], 2: [{type: 'TEXT', ...}] } setInitialAnnotations(annotations); }; useEffect(() => { loadWithHistory(); }, []); return (
); } ``` -------------------------------- ### PdfViewerRef API for Programmatic Control Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt Defines the PdfViewerRef interface, providing methods to programmatically interact with the PDF viewer. It allows retrieval of the annotated document as a Blob or URL, and access to annotation data including history for undo/redo. This interface is crucial for external control and state synchronization. ```typescript interface PdfViewerRef { // Returns the annotated PDF as a Blob for upload/download getAnnotatedDocument: () => Promise; // Returns an object URL for previewing (remember to revoke) getAnnotatedDocumentUrl: () => Promise; // Returns current annotations and history without generating PDF getAnnotationData: () => AnnotationExportData; } interface AnnotationExportData { annotations: Record; // Keyed by page number historyState: HistoryState; // For undo/redo restoration } interface HistoryState { history: Record[]; // Array of annotation snapshots index: number; // Current position in history } ``` -------------------------------- ### Update package.json Bugs URL Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md Explains how to update the 'bugs.url' field in package.json to link to your project's issue tracker on GitHub. This allows users to report bugs and issues effectively. ```json { "bugs": { "url": "https://github.com/yourusername/your-repo/issues" } } ``` -------------------------------- ### Import Default Styles (TypeScript/JSX) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md Imports the pre-built CSS file for the react-pdf-annotator-v2 package. This import applies the default Tailwind CSS-based styles, enabling out-of-the-box styling without requiring Tailwind CSS in your project. ```tsx import 'react-pdf-annotator-v2/dist/style.css'; ``` -------------------------------- ### Manage Annotation State with Undo/Redo in React Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This snippet demonstrates how to manage annotation state in a React application using the react-pdf-annotator-v2 package. It includes saving annotations to local storage or a backend and loading previously saved states, supporting full undo/redo history. ```tsx import { useState, useCallback } from 'react'; import { PdfViewer, AnnotationExportData } from 'react-pdf-annotator-v2'; import type { HistoryState } from 'react-pdf-annotator-v2'; function App() { const [initialHistoryState, setInitialHistoryState] = useState(); // Called when user downloads or prints the PDF const handleSave = useCallback((data: AnnotationExportData) => { // Save to localStorage localStorage.setItem('annotations', JSON.stringify(data)); // Or save to backend fetch('/api/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); }, []); const handlePrint = useCallback((data: AnnotationExportData) => { // Optionally save on print as well console.log('Document printed with annotations:', data); }, []); // Load saved annotations const loadSavedAnnotations = () => { const saved = localStorage.getItem('annotations'); if (saved) { const data = JSON.parse(saved) as AnnotationExportData; setInitialHistoryState(data.historyState); } }; return ( <> ); } ``` -------------------------------- ### Automatic Annotation Loading from PDF Metadata Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt Enables automatic loading of annotations embedded within PDF metadata when a PDF is downloaded using the viewer. Re-opening such a PDF automatically restores all annotations without requiring additional code. ```tsx import React, { useState } from 'react'; import { PdfViewer } from 'react-pdf-annotator-v2'; import 'react-pdf-annotator-v2/dist/style.css'; function FileUploadViewer() { const [pdfUrl, setPdfUrl] = useState(''); const handleFileUpload = (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (file) { // Create object URL for the uploaded file const url = URL.createObjectURL(file); setPdfUrl(url); // Annotations are automatically extracted from PDF metadata // No additional code needed - they appear in the viewer } }; return (
{pdfUrl && ( )}
); } ``` -------------------------------- ### Tailwind Configuration (tailwind.config.js) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/NPM_CONVERSION_SUMMARY.md Configures Tailwind CSS to optimize build performance by specifying content paths that exclude the node_modules directory. This ensures that only relevant source files are scanned for Tailwind classes. ```javascript /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./index.html", "./lib/**/*.{js,ts,jsx,tsx}", "./EXAMPLES.tsx" ], theme: { extend: {}, }, plugins: [], } ``` -------------------------------- ### Signature Capture Component using SignatureModal Source: https://context7.com/sandeepmvn/react-pdf-annotator-v2-package/llms.txt Demonstrates how to use the SignatureModal sub-component to capture a user's signature. It manages the modal's visibility and stores the captured signature as a data URL. The component requires React and the SignatureModal from 'react-pdf-annotator-v2'. ```tsx import React from 'react'; import { PdfPage, Toolbar, AnnotationLayer, SignatureModal } from 'react-pdf-annotator-v2'; // SignatureModal - Canvas-based signature capture function SignatureCapture() { const [showModal, setShowModal] = React.useState(false); const [signature, setSignature] = React.useState(null); const handleSave = (dataUrl: string) => { setSignature(dataUrl); // dataUrl is a base64 PNG: 'data:image/png;base64,...' console.log('Signature captured:', dataUrl.substring(0, 50) + '...'); }; return (
{signature && (

Your Signature:

Signature
)} {showModal && ( setShowModal(false)} onSave={handleSave} /> )}
); } ``` -------------------------------- ### Import Annotation Types (TypeScript) Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md Shows how to import various TypeScript types related to annotations, such as `AnnotationTool`, `Annotation`, and `PenAnnotation`, from the `react-pdf-annotator-v2` package. These types enhance code safety and developer experience. ```typescript import type { AnnotationTool, Annotation, PenAnnotation } from 'react-pdf-annotator-v2'; const tool: AnnotationTool = 'PEN'; const annotation: Annotation = { // ... }; ``` -------------------------------- ### Import Hooks for Annotation History Management in React Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This code shows the import statement for the useAnnotationHistory hook and related types from the react-pdf-annotator-v2 package. This hook is essential for managing the undo/redo functionality of annotations. ```tsx // Hooks import { useAnnotationHistory } from 'react-pdf-annotator-v2'; import type { HistoryState } from 'react-pdf-annotator-v2'; ``` -------------------------------- ### React PDF Annotator v2: Tracking Annotation Changes Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/README.md This code demonstrates how to track changes in annotations using the `onAnnotationsChange` prop. The provided callback function receives the current annotations object, allowing for real-time updates, saving to a database, or state management. The `annotations` parameter is a page-keyed object of annotation arrays. ```tsx import { Annotations } from 'react-pdf-annotator-v2'; function App() { const handleAnnotationsChange = (annotations: Annotations) => { console.log('Annotations updated:', annotations); // Save to database, update state, etc. }; return ( ); } ``` ```typescript { 1: [{ id: '...', type: 'PEN', points: [...], color: '#000000', ... }], 2: [{ id: '...', type: 'TEXT', content: 'Hello', x: 100, y: 200, ... }], // ... } ``` -------------------------------- ### External Module Imports for React PDF Annotator Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/index.html This JSON object specifies the external modules required by the React PDF Annotator v2 package and their corresponding CDN URLs. It includes 'react', 'react-dom/client', and 'pdf-lib'. ```json { "imports": { "react": "https://esm.sh/react@18.2.0", "react-dom/client": "https://esm.sh/react-dom@18.2.0/client", "pdf-lib": "https://esm.sh/pdf-lib@1.17.1" } } ``` -------------------------------- ### Deprecate Package on NPM Source: https://github.com/sandeepmvn/react-pdf-annotator-v2-package/blob/main/PRE_PUBLISH_CHECKLIST.md The command to deprecate a package version on NPM after the 72-hour unpublish window. This marks the version as outdated and provides a reason to users. ```bash npm deprecate PACKAGE@VERSION "reason" ```