如何在 Angular 17 中使用 fs 模块(文件系统)?

问题描述 投票:0回答:1

我正在使用一个 pdf 符号库,它使用 fs 来读取 pdf 文件。

不幸的是我无法使用它,因为 Angular 应用程序通常在浏览器环境中运行,而 fs 模块(文件系统)是一个用于与文件系统交互的 Node.js 模块,无法直接在浏览器中访问。

我尝试了以下操作,我使用http客户端来获取p12证书作为数组缓冲区,然后将订阅的数据与缓冲区一起使用:

    PDFViewerApplication.pdfDocument.getData().then(async pdfData => {

  http.get('assets/AccuSign.p12', {responseType: 'arraybuffer'}).subscribe(async data => {

    const settings: SignerSettings = {
      rangePlaceHolder: 9999, signatureComputer: <P12SignatureComputerSettings>{
        password: '1q2w3e',
        certificate: Buffer.from(data)
      }, signatureLength: 0
    };

    const parameters: SignVisualParameters = {
      pageNumber: 1,
      rectangle: {
        left: 50,
        top: 641,
        right: 264,
        bottom: 711
      },
      texts: [{
        lines: [
          'Faris',
          'Shomali'
        ]
      }, {
        lines: [
          'Digitally signed by',
          'Faris Shomali',
          'Date: 2023.11.03',
          '20:28:46 +02\'00\''
        ]
      }
      ]
    };

    const pdfSigner = new PdfSigner(settings);
    const placeHolder = await pdfSigner.addPlaceholderAsync(Buffer.from(pdfData), parameters)
  });
})

它不起作用,我收到此错误消息:

有什么办法可以将 fs 与 Angular 一起使用吗? fs 有其他选择吗?

javascript angular typescript node.js-fs
1个回答
0
投票

您可以使用浏览器的 FileReader API 将文件读取为 ArrayBuffer。

PDFViewerApplication.pdfDocument.getData().then(async pdfData => {

  // Fetch the P12 certificate file
  fetch('assets/AccuSign.p12')
    .then(response => response.arrayBuffer())
    .then(async data => {

      const settings: SignerSettings = {
        rangePlaceHolder: 9999,
        signatureComputer: <P12SignatureComputerSettings>{
          password: '1q2w3e',
          certificate: Buffer.from(data)
        },
        signatureLength: 0
      };

      const parameters: SignVisualParameters = {
        pageNumber: 1,
        rectangle: {
          left: 50,
          top: 641,
          right: 264,
          bottom: 711
        },
        texts: [
          {
            lines: [
              'Faris',
              'Shomali'
            ]
          },
          {
            lines: [
              'Digitally signed by',
              'Faris Shomali',
              'Date: 2023.11.03',
              '20:28:46 +02\'00\''
            ]
          }
        ]
      };

      const pdfSigner = new PdfSigner(settings);
      const placeHolder = await pdfSigner.addPlaceholderAsync(Buffer.from(pdfData), parameters);
    })
    .catch(error => {
      console.error('Error fetching P12 certificate:', error);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.