简体   繁体   中英

How to import pdf file using nodejs?

I am having trouble on how to import the pdf file, the url is undefined

the file tree is

pdfTempaltes
  pdf
    PdfGeneration.js
    MonthlyPeriod.pdf

my code

import { PDFDocument } from 'pdf-lib';
const PdfGeneration = async (data) => {

const pdfLocation = url('MonthlyPeriod.pdf');
const formPdfBytes = await fetch(pdfLocation).then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(formPdfBytes);
const form = pdfDoc.getForm();

const applicationFor = form.getTextField('applicationFor');
applicationFor.setText('Mario');
return  await pdfDoc.save();
}

export default PdfGeneration;

this is how i call the PDFGeneration

  test: async (req, res) => {
    try {
      const result = await Pdf1905Generation();
      const data = {
        msg: 'successful',
        code: 0,
        data: result,
      };
      res.status(200).json(data);
    } catch (err) {
      console.log(err);
      const safeErr = ErrorManager.getSafeError(err);
      const data = {
        msg: 'unsuccessful',
        code: 1,
        data: safeErr,
      };
      res.status(400).json(data);
    }
  },

UPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATEUPDATE

I am not sure I understand why you are using fetch() when the file you want to read is next to the JavaScript file.

Based on your folder structure, to read the "MonthlyPeriod.pdf", you can use readFileSync() of the fs module to read the file as follows:

import { PDFDocument } from 'pdf-lib';
import { readFileSync } from "fs"

const PdfGeneration = async (data) => {

const pdfDoc = await PDFDocument.load(readFileSync("./MonthlyPeriod.pdf"));
const form = pdfDoc.getForm();

const applicationFor = form.getTextField('applicationFor');
applicationFor.setText('Mario');
return  await pdfDoc.save();
}

export default PdfGeneration;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM