Vue 3 TypeScript 实现 PDF 转 Word、PDF 转 图片、Word 转 PDF (无 Node.js)
以下是一个使用 Vue 3 和 TypeScript 实现 PDF 转 Word、PDF 转 图片、Word 转 PDF 的案例,无需 Node.js 环境,直接在浏览器中运行:
- 安装依赖:
- 创建一个名为
FileConverter.vue的组件: - 在需要使用的页面中引入
FileConverter.vue组件:
npm install pdf2docx pdf-image word2pdf
<template>
<div>
<input type="file" ref="fileInput" @change="handleFileChange" accept=".pdf,.docx" />
<button @click="convertToWord" :disabled="!file">PDF to Word</button>
<button @click="convertToImage" :disabled="!file">PDF to Image</button>
<button @click="convertToPDF" :disabled="!file">Word to PDF</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { convert } from 'pdf2docx';
import { convertToImages } from 'pdf-image';
import { convert as convertToPDF } from 'word2pdf';
export default defineComponent({
name: 'FileConverter',
setup() {
const file = ref<File | null>(null);
const handleFileChange = (event: any) => {
file.value = event.target.files[0];
};
const convertToWord = async () => {
if (file.value) {
const pdfData = await fileToBase64(file.value);
const wordData = await convert(pdfData);
downloadFile(wordData, 'converted.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
}
};
const convertToImage = async () => {
if (file.value) {
const pdfData = await fileToBase64(file.value);
const imagesData = await convertToImages(pdfData);
imagesData.forEach((imageData, index) => {
downloadFile(imageData, `converted_${index}.png`, 'image/png');
});
}
};
const convertToPDF = async () => {
if (file.value) {
const wordData = await fileToBase64(file.value);
const pdfData = await convertToPDF(wordData);
downloadFile(pdfData, 'converted.pdf', 'application/pdf');
}
};
const fileToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
resolve(reader.result as string);
};
reader.onerror = (error) => {
reject(error);
};
});
};
const downloadFile = (data: string, filename: string, mimeType: string) => {
const link = document.createElement('a');
link.href = data;
link.download = filename;
link.type = mimeType;
link.click();
};
return {
file,
handleFileChange,
convertToWord,
convertToImage,
convertToPDF,
};
},
});
</script>
<template>
<div>
<FileConverter />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import FileConverter from '@/components/FileConverter.vue';
export default defineComponent({
name: 'App',
components: {
FileConverter,
},
});
</script>
在这个案例中,我们使用了 pdf2docx 库来将 PDF 转换为 Word 文档,pdf-image 库将 PDF 转换为图片,word2pdf 库将 Word 文档转换为 PDF。用户可以选择一个 PDF 或 Word 文件,然后点击相应的按钮来进行转换,转换后的文件将会自动下载到用户的设备中。
注意:由于涉及文件读取和下载,该案例需要在浏览器环境下运行,不能直接在 Node.js 中使用。
原文地址: https://www.cveoy.top/t/topic/o57b 著作权归作者所有。请勿转载和采集!