Sure, I can help you create an HTML page with a button that converts a PDF to a Word document while maintaining the layout, images, and extracting text using OCR, all using CDN libraries and without any external APIs. Below is the complete HTML code that you can use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF to Word Converter</title>
<!-- Include necessary CDN libraries -->
<!-- PDF.js -->
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<!-- Tesseract.js for OCR -->
<script src="https://cdn.jsdelivr.net/npm/tesseract.js@2/dist/tesseract.min.js"></script>
<!-- docx.js for generating Word documents -->
<script src="https://cdn.jsdelivr.net/npm/docx@7.3.0/build/index.min.js"></script>
</head>
<body>
<h1>PDF to Word Converter</h1>
<input type="file" id="fileInput" accept="application/pdf" />
<button id="convertButton">Convert to Word</button>
<br><br>
<a id="downloadLink" style="display:none;">Download Word Document</a>
<script>
document.getElementById('convertButton').addEventListener('click', function() {
const fileInput = document.getElementById('fileInput');
if (fileInput.files.length === 0) {
alert('Please select a PDF file.');
return;
}
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function() {
const typedarray = new Uint8Array(this.result);
pdfjsLib.getDocument(typedarray).promise.then(async function(pdf) {
const numPages = pdf.numPages;
const doc = new docx.Document();
for (let i = 1; i <= numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 1.5 });
// Prepare canvas using PDF page dimensions
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
await page.render({ canvasContext: context, viewport: viewport }).promise;
// Get image data from canvas
const imageData = canvas.toDataURL('image/png');
// Add image to Word document
const image = docx.Media.addImage(doc, imageData);
// Attempt to extract text from the page
const textContent = await page.getTextContent();
let textItems = textContent.items.map(item => item.str).join(' ');
// If text is empty, perform OCR
if (!textItems.trim()) {
const ocrResult = await Tesseract.recognize(imageData, 'eng', { logger: m => console.log(m) });
textItems = ocrResult.data.text;
}
// Add text to Word document
doc.addSection({
children: [
new docx.Paragraph({
children: [image],
}),
new docx.Paragraph(textItems),
],
});
}
// Generate a Word document
docx.Packer.toBlob(doc).then(blob => {
const url = URL.createObjectURL(blob);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = url;
downloadLink.download = 'converted.docx';
downloadLink.style.display = 'block';
downloadLink.click();
});
});
};
reader.readAsArrayBuffer(file);
});
</script>
</body>
</html>
Explanation of the Code:
-
HTML Structure:
- An
<input> element for user to select a PDF file.
- A
<button> that triggers the conversion process.
- An
<a> element that serves as the download link for the generated Word document.
-
Including CDN Libraries:
- PDF.js is used to read and render the PDF file.
- Tesseract.js is used to perform OCR on images to extract text.
- docx.js is used to generate the Word document.
-
JavaScript Logic:
- When the "Convert to Word" button is clicked, we read the selected PDF file using
FileReader.
- We load the PDF using
pdfjsLib.getDocument.
- For each page in the PDF:
- We render the page onto a canvas to get the image representation.
- We attempt to extract text using
getTextContent.
- If the text is empty (e.g., scanned PDF), we perform OCR using Tesseract.js.
- We add both the image and the extracted text to the Word document using docx.js.
- After processing all pages, we generate a Blob from the Word document and create a download link for the user.
Notes:
Usage Instructions:
- Save the above code into an HTML file (e.g.,
pdf_to_word_converter.html).
- Open the HTML file in a modern web browser (e.g., Chrome, Firefox).
- Select a PDF file using the file input.
- Click the "Convert to Word" button.
- Wait for the processing to complete (a download link will appear).
- Click the "Download Word Document" link to download the converted
.docx file.
Conclusion:
This code provides a client-side solution to convert PDF files to Word documents while maintaining the layout, images, and extracting text using OCR, all without using any external APIs. It leverages powerful JavaScript libraries loaded via CDNs and runs entirely in the user's browser.