将 pdfmake 生成的 pdf 导出到 docx/word 文档

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

正如标题所暗示的,有没有办法在javascript中将pdf转换为word文档?

pdf 是使用 javascript 中的 pdmake 库以编程方式生成的。我可以访问 BLOB 或 pdf 文档的 URI。我可以把它转换成word文档并下载吗?

我一直在四处寻找,但找不到与此特定场景相关的任何内容。任何形式的帮助将不胜感激。

javascript pdf-generation docx pdfmake
2个回答
0
投票

是的,有一些方法可以使用 JavaScript 将 PDF 转换为 Word 文档。一种选择是使用第三方库,如 pdf2docx 或 Docxpresso。这些库允许您以编程方式将 PDF 文件转换为 Word 文档。

这是一个使用 pdf2docx 的例子:

const pdf2docx = require('pdf2docx');

const pdfBlob = /* get your pdf blob here */;
const options = {
  preset: 'letter',
  margins: { top: 720, left: 720, bottom: 720, right: 720 }
};

pdf2docx(pdfBlob, options)
  .then(docxBuffer => {
    // Download the converted Word document
    const downloadLink = document.createElement('a');
    downloadLink.href = URL.createObjectURL(new Blob([docxBuffer], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }));
    downloadLink.download = 'converted.docx';
    downloadLink.click();
  })
  .catch(error => {
    console.error(error);
  });

在此示例中,我们使用 pdf2docx 库将 PDF blob 转换为 Word 文档缓冲区。然后,我们为转换后的文档创建一个下载链接并触发点击它来下载文件。

请记住,这些第三方库可能并不总是能产生完美的结果,并且转换后的文档中可能存在一些格式问题。此外,转换过程可能会占用大量资源,因此可能需要一些时间才能完成。


0
投票

如果您没有找到

pdf2docx
包,您可以尝试使用另一个提供类似功能的库,例如
pdfjs-dist
库。请看下面的例子:

const pdfjsLib = require('pdfjs-dist');
const mammoth = require('mammoth');

// Busca o arquivo PDF
const fileInput = document.getElementById('pdf-file');
fileInput.addEventListener('change', handleFileInput);

function handleFileInput(event) {
  const file = event.target.files[0];

  // Converte o arquivo para HTML
  const fileReader = new FileReader();
  fileReader.readAsArrayBuffer(file);
  fileReader.onload = async function() {
    const pdfData = new Uint8Array(this.result);
    const pdfDocument = await pdfjsLib.getDocument({ data: pdfData }).promise;
    const pdfPage = await pdfDocument.getPage(1);
    const textContent = await pdfPage.getTextContent();
    const text = textContent.items.map(item => item.str).join('\n');
    const html = `<html><body>${text}</body></html>`;

    // Converte o HTML para um arquivo do Word
    const options = {};
    mammoth.convertToHtml({ arrayBuffer: new Uint8Array(html) }, options).then(result => {
      const converted = mammoth.convertToWord(result.value);
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(converted);
      downloadLink.download = 'converted.docx';
      downloadLink.click();
    });
  };
}

在这个例子中,我们使用

pdfjs-dist
包来读取PDF文件并从第一页中提取文本。然后使用
mammoth
包将文本转换为 HTML 文件。最后,HTML 被转换为 Word 文件并可供下载。

© www.soinside.com 2019 - 2024. All rights reserved.