Appearance
Adding text to a Pdf Document - React
In this example we add text to a pdf document. We start with creating an empty document of size a5 in portrait mode.
tsx
const emptyA5PortraitDocument = await _app.createDocument(null, [
{
operation: "create-page",
data: {
orientation: "portrait",
size: "a5",
},
},
]);
Then we call the addText
method on the PdfPages component to add the text to the first page (index 0), on a the specified position in the specified font and color:
tsx
await _pages.addText(0, y, x, `UnoPdf`, 'Helvetica', 12, color);
When we wrap that in a loop and do some math we can create a circle of text. See below for a full example.
Screenshot
Code
tsx
import {
PdfApplication,
PdfDocument,
PdfPages,
defineCustomElements,
} from "@tallcomponents/unopdf-react";
import { useEffect, useRef } from "react";
defineCustomElements();
// Note: this example uses Vite and retrieves the keys from the environment.
// This should not be used in production.
// See the authentication section in the usage guide for more information.
const publickey = import.meta.env.VITE_PUBLIC_KEY;
const privatekey = import.meta.env.VITE_PRIVATE_KEY;
function App() {
const pdfApplication = useRef<HTMLPdfApplicationElement>(null);
const pdfDocument = useRef<HTMLPdfDocumentElement>(null);
const pdfPages = useRef<HTMLPdfPagesElement>(null);
useEffect(() => {
const addImageToPage = async () => {
if (pdfApplication.current) {
const _app = pdfApplication.current;
if (pdfDocument.current) {
const _document = pdfDocument.current;
if (pdfPages.current) {
const _pages = pdfPages.current;
//#region create_document
const emptyA5PortraitDocument = await _app.createDocument(null, [
{
operation: "create-page",
data: {
orientation: "portrait",
size: "a5",
},
},
]);
//#endregion create_document
_document.addEventListener('loaded', async () => {
for (let α = 0; α < 360; α += 360 / 12) {
const x = 180 - 125 * Math.sin(α * Math.PI / 180);
const y = 300 + 100 * Math.cos(α * Math.PI / 180);
const [r, g, b] = [α, 128, 0];
const color = `rgb(${r} ${g} ${b})`;
//#region add_text
await _pages.addText(0, y, x, `UnoPdf`, 'Helvetica', 12, color);
//#endregion add_text
}
});
await _document.open(emptyA5PortraitDocument?.id ?? "");
}
}
}
};
addImageToPage();
}, []);
return (
<>
<h1>UnoPdf Example: Adding Text in React</h1>
<PdfApplication
ref={pdfApplication}
publickey={publickey}
privatekey={privatekey}
/>
<PdfDocument ref={pdfDocument} />
<PdfPages ref={pdfPages} />
</>
);
}
export default App;
Running the example
- Download the react - Adding text to a Pdf Document project
- Unzip the file to a directory
react-add-text
.shellunzip react-add-text.zip -d react-add-text
- Open a terminal and go to that directoryshell
cd react-add-text
- Install dependenciesshell
npm install
shellyarn
- Start the projectshell
npm run start
shellyarn start