What is causing this page to remain empty?

Currently, I am working on developing an spfx web part that has the functionality to merge selected documents into one. By utilizing the pdf-lib and @pnp/sp libraries, I have been able to work on the following code:

const mergedFile = await PDFDocument.create();

// Iterating through each selected item
this.context.listView.selectedRows.forEach(async (row: RowAccessor) => {
   // Accessing the file array buffer
   const file = sp.web.getFileByServerRelativePath(row.getValueByName('FileRef'));
   const fileBytes: ArrayBuffer = await file.getBuffer();
   const fileToMerge = await PDFDocument.load(fileBytes);

   const copyPages = await mergedFile.copyPages(fileToMerge, fileToMerge.getPageIndices());
   copyPages.forEach((page) => {
     mergedFile.addPage(page);
   });
});


const savedMergedFile = await Promise.resolve(mergedFile.save());
const newFileAsBlob = new Blob([savedMergedFile]);
const newFile = await sp.web.getFolderByServerRelativePath(path).files.addChunked(encodeURI("newFile.pdf"), newFileAsBlob,  undefined, true);

For creating this web part, I referred to this link and this link. However, upon testing the functionality, I noticed that the resulting document only contains a blank page. Can anyone help me understand what might be causing this issue?

Answer №1

After some persistence, I finally discovered that the issue wasn't with 'typecasting' to blob as initially thought. It turns out that the for loop was running asynchronously from the rest of the function, causing a timing problem. This led to mergedFile.save() executing before the for loop could properly copy the pages to the PDFDocument. Sharing this solution in case it may prove useful to others.

const savedMergedFile = await this.generateByteArray();
const fileAsBlob = new Blob([savedMergedFile])
const newFile = await sp.web.getFolderByServerRelativePath(path).files.addChunked(encodeURI(fileName), fileAsBlob, undefined, true)

private async generateByteArray(): Promise<Uint8Array> {
    const mergedFile = await PDFDocument.create();

    for(const row of this.context.listView.selectedRows){
      const file = sp.web.getFileByServerRelativePath(row.getValueByName('FileRef'));
      const fileBytes: ArrayBuffer = await file.getBuffer();
      const fileToMerge = await PDFDocument.load(fileBytes);

      const copyPages = await mergedFile.copyPages(fileToMerge, fileToMerge.getPageIndices());
      copyPages.forEach((page) => {
        mergedFile.addPage(page);
      });
    }
    return mergedFile.save();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

Transferring information through parent-child components via onChange

I have a question regarding data binding. In my project, I have a parent component and two child components: Parent: directives: [firstChild,secondChild], template:' <first-child [showList]="showList" (emitShowList)="getShowList($event)"& ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

Exploring the ideal workspace for maximizing the potential of Ionic framework development

For my iOS and Android app built with Ionic and Angular, I typically use ionic serve in Chrome for easy and fast development. However, when it comes to utilizing the native HTTP API for essential tasks like communicating with a REST server, I've foun ...

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

Rollup faces challenges when trying to bundle source code alongside Bazel and Typescript

I am attempting to create a bundle using rollup, typescript, and bazel environment. I am having trouble importing relative paths. Typescript builds correctly but rollup is unable to bundle the source. WORKSPACE # WORKSPACE workspace( name = "WORK ...

Leveraging the 'styled()' utility from the MUI System while incorporating extra properties (Typescript)

I'm currently tackling a project using MUI System v5. I've opted to use the styled() utility (not styled-components) for styling and creating basic UI components. TypeScript is being used in this project, but I am facing a number of challenges as ...

Why does the page not work when I enter a certain URL with an ID parameter, and instead displays the error message "Uncaught ReferenceError: System is not defined"?

This is my "app.routing.ts": import {provideRouter, RouterConfig} from "@angular/router"; import {DashboardComponent} from "./dashboard.component"; import {HeroesComponent} from "./heroes.component"; import {HeroDetailsComponent} from "./hero-details.com ...

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

Is it possible to import both type and value on the same line when isolatedModules=true?

Did you know with Typescript, you can do type-only imports? import type { Foo } from "./types" If the file exports both types and values, you can use two separate import statements like this: import type { Foo } from "./types"; import ...

How do I add a new module to an existing one using Angular-CLI?

After generating modules: $ ng generate module myTestModule installing module create src/app/my-test-module/my-test-module.module.ts $ ng generate module myTestModule2 installing module create src/app/my-test-module2/my-test-module2.module.ts I ha ...

Creating a JSON file from a custom key-value class in Typescript: A comprehensive guide

I am struggling to find an npm package or create my own function that can generate a JSON file from elements within this specific class: export class TranslatedFileElement { private key: string private hasChild: boolean priva ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

Updating the dropdown option value in Angular 10's edit component

In my Angular and ASP.NET application, I have an edit form in a component with multiple select options in a dropdown list. When displaying all data in the edit form, the dropdown list fields are displayed as empty instead of showing the previously stored v ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Learn how to customize the background colors of the x and y axes in Highcharts graphs

I am attempting to modify the background color of the highcharts x and y axis. My goal is to apply a fill color as shown in the highlighted image below. https://i.sstatic.net/NX6nF.jpg ...

Encountering an "Invalid hook call error" while utilizing my custom library with styled-components

I recently developed my own custom UI tool using the styled-components library, integrating typescript and rollup for efficiency. One of the components I created looks like this: import styled from 'styled-components' export const MyUITest2 = s ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

A guide to efficiently utilizing conditional dynamic import within a React application

Currently, I am working on a component that receives an array of strings as props. The goal is to iterate over each string in the array, capitalize it, and then dynamically import JSX elements from the "react-icons/si" module. While I have successfully acc ...

There appears to be an issue with Axios incorrectly parsing TypeScript objects

I have a TypeScript object representing a user, with an id: number. However, when this id is passed through axios, it is being parsed as a string internally which is causing issues with my server. I need to correct this issue. The axios call I am making l ...