Create a new PDF document
masterYou can create a new PDF by defining PDFPage objects and then using PDFDocument.create(path) to write them to a file.
PDFPage.create() allows you to:
.setMediaBox(width, height): Set the page dimensions..drawText(text, options): Add text with specificx,y, andcolor..drawRectangle(options): Add rectangles withx,y,width,height, andcolor..drawImage(path, type, options): Add images (e.g., 'jpg', 'png').
Finally, use PDFDocument.create(path).addPages(...).write() to save the document. write() returns a Promise that resolves with the final PDF path.
import PDFLib, { PDFDocument, PDFPage } from 'react-native-pdf-lib';
const page1 = PDFPage
.create()
.setMediaBox(200, 200)
.drawText('You can add text and rectangles to the PDF!', {
x: 5,
y: 235,
color: '#007386',
})
.drawRectangle({
x: 25,
y: 25,
width: 150,
height: 150,
color: '#FF99CC',
});
const docsDir = await PDFLib.getDocumentsDirectory();
const pdfPath = `${docsDir}/sample.pdf`;
PDFDocument
.create(pdfPath)
.addPages(page1)
.write()
.then(path => {
console.log('PDF created at: ' + path);
});