import { useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { DocumentMetadata, OpenInput } from '@embedpdf/react/runtime';
import {
metadataPlugin,
useMetadata,
useMetadataEvent,
useMetadataState,
} from '@embedpdf/react/metadata';
import { localEngine } from '@embedpdf/engine';
import './edit.css';
const engine = localEngine();
const plugins = [metadataPlugin()];
const welcome = async (): Promise => {
const response = await fetch('https://www.embedpdf.com/pdfs/welcome.pdf');
return { kind: 'bytes', id: 'welcome', bytes: new Uint8Array(await response.arrayBuffer()) };
};
const EDITABLE = ['title', 'author', 'subject', 'keywords'] as const;
type Draft = Record<(typeof EDITABLE)[number], string>;
// A properties form: the inputs start with what the file says, and Save writes them back.
function PropertiesForm({ initial }: { initial: DocumentMetadata }) {
const metadata = useMetadata();
const modifiedAt = useMetadataState((state) => state.metadata?.modifiedAt ?? null);
const [draft, setDraft] = useState({
title: initial.title ?? '',
author: initial.author ?? '',
subject: initial.subject ?? '',
keywords: initial.keywords ?? '',
});
const [changes, setChanges] = useState([]);
// Every change to the standard fields, by you or anyone else.
useMetadataEvent(
(capability) => capability.onUpdated,
({ changedKeys, origin }) =>
setChanges((list) => [
`${changedKeys.join(', ')} changed ${origin.kind === 'local' ? 'here' : 'elsewhere'}`,
...list,
]),
);
const canUpdate = metadata.canUpdate();
// An empty field removes it: null, not ''.
const save = () =>
metadata.update({
title: draft.title.trim() || null,
author: draft.author.trim() || null,
subject: draft.subject.trim() || null,
keywords: draft.keywords.trim() || null,
});
return (
Changes
Last changed: {modifiedAt ? new Date(modifiedAt).toLocaleString() : 'not set'}
{changes.length === 0 ? (
Edit a field and save.
) : (
{changes.map((change, index) => (
- {change}
))}
)}
);
}
// The form starts once the properties have been read from the file.
function PropertiesEditor() {
const fields = useMetadataState((state) => state.metadata);
return fields ? : Reading…
;
}
export default function App() {
return (
Loading…
}>
);
}