mirror of
https://github.com/iib0011/omni-tools.git
synced 2025-12-29 16:16:02 +00:00
feat complete
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { tool as pdfRotatePdf } from './rotate-pdf/meta';
|
||||
import { meta as splitPdfMeta } from './split-pdf/meta';
|
||||
import { meta as mergePdf } from './merge-pdf/meta';
|
||||
import { DefinedTool } from '@tools/defineTool';
|
||||
|
||||
export const pdfTools: DefinedTool[] = [splitPdfMeta, pdfRotatePdf];
|
||||
export const pdfTools: DefinedTool[] = [splitPdfMeta, pdfRotatePdf, mergePdf];
|
||||
|
||||
67
src/pages/tools/pdf/merge-pdf/index.tsx
Normal file
67
src/pages/tools/pdf/merge-pdf/index.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react';
|
||||
import ToolFileResult from '@components/result/ToolFileResult';
|
||||
import ToolContent from '@components/ToolContent';
|
||||
import { ToolComponentProps } from '@tools/defineTool';
|
||||
import { mergePdf } from './service';
|
||||
import ToolMultiPdfInput, {
|
||||
MultiPdfInput
|
||||
} from '@components/input/ToolMultiplePdfInput';
|
||||
|
||||
export default function SplitPdf({ title }: ToolComponentProps) {
|
||||
const [input, setInput] = useState<MultiPdfInput[]>([]);
|
||||
const [result, setResult] = useState<File | null>(null);
|
||||
const [isProcessing, setIsProcessing] = useState<boolean>(false);
|
||||
|
||||
const compute = async (values: File[], input: MultiPdfInput[]) => {
|
||||
if (input.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsProcessing(true);
|
||||
const mergeResult = await mergePdf(input.map((i) => i.file));
|
||||
setResult(mergeResult);
|
||||
} catch (error) {
|
||||
throw new Error('Error merging PDF:' + error);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ToolContent
|
||||
title={title}
|
||||
input={input}
|
||||
setInput={setInput}
|
||||
initialValues={input.map((i) => i.file)}
|
||||
compute={compute}
|
||||
// exampleCards={exampleCards}
|
||||
inputComponent={
|
||||
<ToolMultiPdfInput
|
||||
value={input}
|
||||
onChange={(v) => {
|
||||
setInput(v);
|
||||
}}
|
||||
accept={['application/pdf']}
|
||||
title={'Input PDF'}
|
||||
type="pdf"
|
||||
/>
|
||||
}
|
||||
getGroups={({ values, updateField }) => []}
|
||||
resultComponent={
|
||||
<ToolFileResult
|
||||
title={'Output merged PDF'}
|
||||
value={result}
|
||||
extension={'pdf'}
|
||||
loading={isProcessing}
|
||||
loadingText={'Extracting pages'}
|
||||
/>
|
||||
}
|
||||
toolInfo={{
|
||||
title: 'How to Use the Merge PDF Tool?',
|
||||
description: `This tool allows you to merge multiple PDF files into a single document.
|
||||
To use the tool, simply upload the PDF files you want to merge. The tool will then combine all pages from the input files into a single PDF document.`
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
12
src/pages/tools/pdf/merge-pdf/meta.ts
Normal file
12
src/pages/tools/pdf/merge-pdf/meta.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { defineTool } from '@tools/defineTool';
|
||||
import { lazy } from 'react';
|
||||
|
||||
export const meta = defineTool('pdf', {
|
||||
name: 'Merge PDF',
|
||||
shortDescription: 'Merge multiple PDF files into a single document',
|
||||
description: 'Combine multiple PDF files into a single document.',
|
||||
icon: 'material-symbols-light:merge',
|
||||
component: lazy(() => import('./index')),
|
||||
keywords: ['pdf', 'merge', 'extract', 'pages', 'combine', 'document'],
|
||||
path: 'merge-pdf'
|
||||
});
|
||||
43
src/pages/tools/pdf/merge-pdf/service.test.ts
Normal file
43
src/pages/tools/pdf/merge-pdf/service.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { parsePageRanges } from './service';
|
||||
|
||||
describe('parsePageRanges', () => {
|
||||
test('should return all pages when input is empty', () => {
|
||||
expect(parsePageRanges('', 5)).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
test('should parse single page numbers', () => {
|
||||
expect(parsePageRanges('1,3,5', 5)).toEqual([1, 3, 5]);
|
||||
});
|
||||
|
||||
test('should parse page ranges', () => {
|
||||
expect(parsePageRanges('2-4', 5)).toEqual([2, 3, 4]);
|
||||
});
|
||||
|
||||
test('should parse mixed page numbers and ranges', () => {
|
||||
expect(parsePageRanges('1,3-5', 5)).toEqual([1, 3, 4, 5]);
|
||||
});
|
||||
|
||||
test('should handle whitespace', () => {
|
||||
expect(parsePageRanges(' 1, 3 - 5 ', 5)).toEqual([1, 3, 4, 5]);
|
||||
});
|
||||
|
||||
test('should ignore invalid page numbers', () => {
|
||||
expect(parsePageRanges('1,a,3', 5)).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
test('should ignore out-of-range page numbers', () => {
|
||||
expect(parsePageRanges('1,6,3', 5)).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
test('should limit ranges to valid pages', () => {
|
||||
expect(parsePageRanges('0-6', 5)).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
test('should handle reversed ranges', () => {
|
||||
expect(parsePageRanges('4-2', 5)).toEqual([2, 3, 4]);
|
||||
});
|
||||
|
||||
test('should remove duplicates', () => {
|
||||
expect(parsePageRanges('1,1,2,2-4,3', 5)).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
});
|
||||
95
src/pages/tools/pdf/merge-pdf/service.ts
Normal file
95
src/pages/tools/pdf/merge-pdf/service.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { PDFDocument } from 'pdf-lib';
|
||||
|
||||
/**
|
||||
* Parses a page range string and returns an array of page numbers
|
||||
* @param pageRangeStr String like "1,3-5,7" to extract pages 1, 3, 4, 5, and 7
|
||||
* @param totalPages Total number of pages in the PDF
|
||||
* @returns Array of page numbers to extract
|
||||
*/
|
||||
export function parsePageRanges(
|
||||
pageRangeStr: string,
|
||||
totalPages: number
|
||||
): number[] {
|
||||
if (!pageRangeStr.trim()) {
|
||||
return Array.from({ length: totalPages }, (_, i) => i + 1);
|
||||
}
|
||||
|
||||
const pageNumbers = new Set<number>();
|
||||
const ranges = pageRangeStr.split(',');
|
||||
|
||||
for (const range of ranges) {
|
||||
const trimmedRange = range.trim();
|
||||
|
||||
if (trimmedRange.includes('-')) {
|
||||
const [start, end] = trimmedRange.split('-').map(Number);
|
||||
if (!isNaN(start) && !isNaN(end)) {
|
||||
// Handle both forward and reversed ranges
|
||||
const normalizedStart = Math.min(start, end);
|
||||
const normalizedEnd = Math.max(start, end);
|
||||
|
||||
for (
|
||||
let i = Math.max(1, normalizedStart);
|
||||
i <= Math.min(totalPages, normalizedEnd);
|
||||
i++
|
||||
) {
|
||||
pageNumbers.add(i);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const pageNum = parseInt(trimmedRange, 10);
|
||||
if (!isNaN(pageNum) && pageNum >= 1 && pageNum <= totalPages) {
|
||||
pageNumbers.add(pageNum);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...pageNumbers].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a PDF file based on specified page ranges
|
||||
* @param pdfFile The input PDF file
|
||||
* @param pageRanges String specifying which pages to extract (e.g., "1,3-5,7")
|
||||
* @returns Promise resolving to a new PDF file with only the selected pages
|
||||
*/
|
||||
export async function splitPdf(
|
||||
pdfFile: File,
|
||||
pageRanges: string
|
||||
): Promise<File> {
|
||||
const arrayBuffer = await pdfFile.arrayBuffer();
|
||||
const sourcePdf = await PDFDocument.load(arrayBuffer);
|
||||
const totalPages = sourcePdf.getPageCount();
|
||||
const pagesToExtract = parsePageRanges(pageRanges, totalPages);
|
||||
|
||||
const newPdf = await PDFDocument.create();
|
||||
const copiedPages = await newPdf.copyPages(
|
||||
sourcePdf,
|
||||
pagesToExtract.map((pageNum) => pageNum - 1)
|
||||
);
|
||||
copiedPages.forEach((page) => newPdf.addPage(page));
|
||||
|
||||
const newPdfBytes = await newPdf.save();
|
||||
const newFileName = pdfFile.name.replace('.pdf', '-extracted.pdf');
|
||||
return new File([newPdfBytes], newFileName, { type: 'application/pdf' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges multiple PDF files into a single document
|
||||
* @param pdfFiles Array of PDF files to merge
|
||||
* @returns Promise resolving to a new PDF file with all pages combined
|
||||
*/
|
||||
export async function mergePdf(pdfFiles: File[]): Promise<File> {
|
||||
const mergedPdf = await PDFDocument.create();
|
||||
for (const pdfFile of pdfFiles) {
|
||||
const arrayBuffer = await pdfFile.arrayBuffer();
|
||||
const pdf = await PDFDocument.load(arrayBuffer);
|
||||
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
|
||||
copiedPages.forEach((page) => mergedPdf.addPage(page));
|
||||
}
|
||||
|
||||
const mergedPdfBytes = await mergedPdf.save();
|
||||
const mergedFileName = 'merged.pdf';
|
||||
return new File([mergedPdfBytes], mergedFileName, {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { InitialValuesType, RotationAngle } from './types';
|
||||
import { parsePageRanges, rotatePdf } from './service';
|
||||
import SimpleRadio from '@components/options/SimpleRadio';
|
||||
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
|
||||
import { isArray } from 'lodash';
|
||||
|
||||
const initialValues: InitialValuesType = {
|
||||
rotationAngle: 90,
|
||||
@@ -138,7 +139,9 @@ export default function RotatePdf({
|
||||
inputComponent={
|
||||
<ToolPdfInput
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
onChange={(v) => {
|
||||
setInput(isArray(v) ? v[0] : v);
|
||||
}}
|
||||
accept={['application/pdf']}
|
||||
title={'Input PDF'}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Box, Typography } from '@mui/material';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import ToolFileResult from '@components/result/ToolFileResult';
|
||||
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
|
||||
import ToolContent from '@components/ToolContent';
|
||||
@@ -8,6 +8,7 @@ import { parsePageRanges, splitPdf } from './service';
|
||||
import { CardExampleType } from '@components/examples/ToolExamples';
|
||||
import { PDFDocument } from 'pdf-lib';
|
||||
import ToolPdfInput from '@components/input/ToolPdfInput';
|
||||
import { isArray } from 'lodash';
|
||||
|
||||
type InitialValuesType = {
|
||||
pageRanges: string;
|
||||
@@ -116,7 +117,10 @@ export default function SplitPdf({ title }: ToolComponentProps) {
|
||||
inputComponent={
|
||||
<ToolPdfInput
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
onChange={(v) => {
|
||||
setInput(isArray(v) ? v[0] : v);
|
||||
}}
|
||||
multiple={false}
|
||||
accept={['application/pdf']}
|
||||
title={'Input PDF'}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user