getting a "ENOENT: no such file or directory" when i try to convert a pdf to word

Hello guys , i’ve installed libre office (for windows) ,
i’m working with node Js (nestJs framework) and i’m trying to convert the uploaded pdf to a word file ,
whenever i try upload the file im getting this error

Conversion error: [Error: ENOENT: no such file or directory, open ‘C:\Users\user\AppData\Local\Temp\libreofficeConvert_-12472-Bh0bjZYZoi4m\33e34cdc-a6c9-44e9-aac8-8986eeeadcf2.docx’] {

  • errno: -4058,*
  • code: ‘ENOENT’,*
  • syscall: ‘open’,*
  • path: ‘C:\Users\user\AppData\Local\Temp\libreofficeConvert_-12472-Bh0bjZYZoi4m\33e34cdc-a6c9-44e9-aac8-8986eeeadcf2.docx’*
    }

here is the code

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { join } from 'path';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.setGlobalPrefix('api');
  app.useGlobalPipes(new ValidationPipe({ transform: true }));
  app.useStaticAssets(join(process.cwd(), 'uploads'), {
    prefix: '/uploads/',
  });

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

import { Body, Controller, Post } from '@nestjs/common';
import { FormDataRequest } from 'nestjs-form-data';
import { UploadPdfDto } from 'src/dtos/upload-pdf.dto';
import { FileConvertorService } from './file-convertor.service';

@Controller('convert')
export class FileConvertorController {
  constructor(private readonly fileConvertorService: FileConvertorService) {}

  @Post('pdf-to-word')
  @FormDataRequest()
  async convertPdfToWord(@Body() { pdfFile }: UploadPdfDto) {
    const result = await this.fileConvertorService.convertPdfToDocx(
      pdfFile.buffer,
    );
    return result;
  }
}

import { Injectable } from '@nestjs/common';
import { randomUUID } from 'crypto';
import * as libre from 'libreoffice-convert';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class FileConvertorService {
  async convertPdfToDocx(pdfBuffer: Buffer) {
    return new Promise((resolve, reject) => {
      // Create filename and paths
      const fileName = randomUUID();
      const uploadDir = path.join(process.cwd(), 'uploads');
      const filePath = path.join(uploadDir, fileName);

      // Ensure uploads directory exists
      if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true });
      }

      libre.convertWithOptions(
        pdfBuffer,
        'docx',
        undefined,
        {
          fileName: fileName,
          tmpOptions: {
            // dir: uploadDir, // Use our uploads directory for temp files
            // prefix: 'convert-',
            keep: true, // Keep the temporary files
          },
        },
        (error, docxBuffer) => {
          if (error) {
            console.error('Conversion error:', error);
            reject(error);
          } else {
            // Write the buffer to a file
            fs.writeFileSync(filePath, docxBuffer);

            // Return the URL that can be used to access the file
            const fileUrl = `/uploads/${fileName}`;
            resolve({ fileUrl });
          }
        },
      );
    });
  }
}

It seems to me, that you are using some third-party js library, that itself uses LibreOffice. That library has that “convertWithOptions” call - that’s not part of LibreOffice itself. You need to ask on that library website / forum…

here is the package that im using , can u tell me what is the name or send the url of npm package that its part of libreoffice so i can use it without errors in my node js app

Screenshot 2025-02-14 225711

There are no npm packages in LibreOffice.

look i have installed new package and im getting different error now

**The application cannot be started. **
The configuration file “C:\Program Files\LibreOffice\program\bootstrap.ini” is corrupt.

and here what im getting in terminal

Error converting file: Error: Command failed: C:\Program Files\LibreOffice\program\soffice.exe -env:UserInstallation=file://C:\Users\user\AppData\Local\Temp\soffice-11224-khSfC9NyGB8m --headless --convert-to .docx --outdir C:\Users\user\AppData\Local\Temp\libreofficeConvert_-11224-gRtAWlN4I7Ao C:\Users\user\AppData\Local\Temp\libreofficeConvert_-11224-gRtAWlN4I7Ao\source

[Nest] 11224  - 02/14/2025, 11:28:48 PM   ERROR [ExceptionsHandler] Error: Failed to convert file
    at FileConvertorService.convertPdfToDocx (C:\Users\user\Desktop\file-convertor\src\file-convertor\file-convertor.service.ts:43:13)
    at FileConvertorController.convertPdfToWord (C:\Users\user\Desktop\file-convertor\src\file-convertor\file-convertor.controller.ts:13:20)

and my new code

import { Injectable } from '@nestjs/common';
import { randomUUID } from 'crypto';
import * as libre from 'libreoffice-convert';
import * as fs from 'fs';
import * as path from 'path';
import { promisify } from 'util';

libre.convertAsync = promisify(libre.convert);

@Injectable()
export class FileConvertorService {
  private readonly uploadDir = path.join(__dirname, '../../uploads'); // Directory to store uploaded files

  constructor() {
    // Ensure the upload directory exists
    if (!fs.existsSync(this.uploadDir)) {
      fs.mkdirSync(this.uploadDir, { recursive: true });
    }
  }

  /**
   * Converts a PDF file to DOCX and returns the URL to the converted file.
   * @param fileBuffer - The buffer of the uploaded PDF file.
   * @param originalFileName - The original name of the uploaded file.
   * @returns The URL to the converted DOCX file.
   */
  async convertPdfToDocx(fileBuffer: Buffer): Promise<string> {
    try {
      const ext = '.docx'; // Target file extension
      const uniqueFileName = `${randomUUID() + ext}`;
      const outputPath = path.join(this.uploadDir, uniqueFileName);

      // Convert the PDF buffer to DOCX
      const docxBuffer = await libre.convertAsync(fileBuffer, ext, undefined);

      // Save the converted DOCX file
      await fs.promises.writeFile(outputPath, docxBuffer);

      // Return the URL to the converted file
      return `/uploads/${uniqueFileName}`; // Assuming your server serves static files from /uploads
    } catch (err) {
      console.error(`Error converting file: ${err}`);
      throw new Error('Failed to convert file');
    }
  }

  /**
   * Handles file upload and conversion.
   * @param file - The uploaded file object (e.g., from Multer).
   * @returns The URL to the converted DOCX file.
   */
  // async handleFileUpload(file: Express.Multer.File): Promise<string> {
  //   if (!file || !file.buffer) {
  //     throw new Error('No file uploaded');
  //   }

  //   // Check if the file is a PDF file
  //   if (path.extname(file.originalname).toLowerCase() !== '.pdf') {
  //     throw new Error('Only PDF files are supported');
  //   }

  //   // Convert the file to DOCX and return the URL
  //   return this.convertPdfToDocx(file.buffer, file.originalname);
  // }
}

The -env:UserInstallation=file://C:\Users\user\AppData\Local\Temp\soffice-11224-khSfC9NyGB8m is definitely an invalid URL. How IT people can not know nothing about file URLs escapes me. It must be

-env:UserInstallation=file:///C:/Users/user/AppData/Local/Temp/soffice-11224-khSfC9NyGB8m

No idea if that’s what causes that bootstrap error. As I said, better ask on the “libreoffice-convert” site.