react-native-pdf-lib

repository·master·Indexed 42 days ago

https://github.com/hopding/react-native-pdf-lib

A React Native library for generating and editing PDF documents on Android and iOS. Version 1.0.0 provides a consistent API to create new documents via PDFDocument.create() or modify existing ones using PDFPage.modify(). Key features include drawing text, rectangles, and images, support for custom .ttf fonts, and text dimension measurement via PDFLib.measureText.

Tokens
1.8K
Snippets
6
Records
7
Agent score
3%

What's inside react-native-pdf-lib

  1. Create a new PDF document

    master

    You 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 specific x, y, and color.
    • .drawRectangle(options): Add rectangles with x, y, width, height, and color.
    • .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);
      });
  2. Use custom fonts in PDFs

    master

    The default font is Times New Roman. To use custom fonts:

    1. Create a font folder (e.g., ./assets/fonts).
    2. Add your .ttf files. Ensure the filename matches the font's internal "Full Name".
    3. Update package.json to include the assets folder:
      "rnpm": { "assets": ["./assets/fonts"] }
    4. Run react-native link to bundle the fonts.
    5. Use the fontName property in drawText options.
    const page1 = PDFPage.create()
      .setMediaBox(200, 200)
      .drawText("This text is using the font Franklin Gothic Medium!", {
        x: 5,
        y: 235,
        color: "#F62727",
        fontName: "Franklin Gothic Medium"
      });
  3. Manual installation for iOS and Android

    master

    If automatic linking fails, follow these manual steps:

    iOS

    1. In Xcode, right-click Libraries and select Add Files to [your project's name].
    2. Navigate to node_modules/react-native-pdf-lib and add RNPdfLib.xcodeproj.
    3. In Xcode, select your project, go to Build Phases -> Link Binary With Libraries, and add libRNPdfLib.a.

    Android

    1. In MainActivity.java, add import com.reactlibrary.PdfLibPackage; and add new PdfLibPackage() to the getPackages() method.
    2. In android/settings.gradle, add:
      include ':react-native-pdf-lib'
      project(':react-native-pdf-lib').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-pdf-lib/android')
    3. In android/app/build.gradle, add compile project(':react-native-pdf-lib') to the dependencies block.
    4. Ensure dexOptions { jumboMode = true } is set in android/app/build.gradle.
  4. Modify an existing PDF document

    master

    To edit an existing PDF, use PDFPage.modify(index) where index is the zero-based page number. You can then apply drawing operations to that page.

    To save the changes, use PDFDocument.modify(existingPath) and chain the following:

    • .modifyPages(page1, page2, ...): Applies modifications to existing pages.
    • .addPage(page3): Appends a newly created page to the document.
    • .write(): Saves the changes and returns a Promise resolving to the file path.

    When using drawImage on modified pages, you can specify the source in the options:

    • source: 'assets': Retrieves the image from Android assets.
    • source: 'path': Retrieves the image from the provided file path.
    import PDFLib, { PDFDocument, PDFPage } from 'react-native-pdf-lib';
    
    const page1 = PDFPage
      .modify(0)
      .drawText('This is a modification on the first page!', {
        x: 5,
        y: 235,
        color: '#F62727',
      });
    
    const existingPDF = 'path/to/existing.pdf';
    
    PDFDocument
      .modify(existingPDF)
      .modifyPages(page1)
      .write()
      .then(path => {
        console.log('PDF modified at: ' + path);
      });
  5. Install react-native-pdf-lib

    master

    To install the library, use the automatic installation method. Note that version compatibility depends on your React Native version:

    • For React Native >= 60: Use v1.0.0
    • For React Native <= 59: Use v0.2.1

    Steps:

    1. Install via npm.
    2. Link the library using the React Native CLI.
    3. For Android, you must enable jumboMode in your build.gradle file.
    $ npm install react-native-pdf-lib --save
    $ react-native link react-native-pdf-lib

    In android/app/build.gradle:

    android {
      ...
      dexOptions {
          jumboMode = true
      }
      ...
    }
  6. Measure text dimensions

    master

    Use PDFLib.measureText to calculate the size of a string. This is useful for layout tasks like centering text. It returns a Promise that resolves with the text size.

    Parameters:

    • text: The string to measure.
    • fontName: The name of the font to use.
    • fontSize: The font size.
    return PDFLib.measureText(
      "My Centered Title",
      "Franklin Gothic Medium",
      14
    ).then(result => {
      console.log("The text size is: ", result);
    });
  7. Use the react-native-pdf-lib API

    master

    The react-native-pdf-lib library provides a primary entrypoint for manipulating PDF documents in React Native. It exports three main components:

    • PDFLib: The default export, which serves as the main library interface.
    • PDFDocument: A class/component used to represent and manipulate a PDF document.
    • PDFPage: A class/component used to represent and manipulate individual pages within a PDF document.

    To use the library, import the default export for general operations, or import PDFDocument and PDFPage for specific document and page manipulations.

    import PDFLib, { PDFDocument, PDFPage } from 'react-native-pdf-lib';