refactored the js scripts. better now.

TODO: save PDF or save pdfByte data on file or DB
This commit is contained in:
jndaniels 2024-11-26 22:16:21 -06:00
parent 284818d650
commit 1821f63c44
6 changed files with 146 additions and 2 deletions

Binary file not shown.

Binary file not shown.

View File

@ -35,6 +35,15 @@ dmx.config({
}
],
"local": {}
},
"processPDF": {
"meta": [
{
"name": "PDFprocess",
"type": "text"
}
],
"local": {}
}
},
"index": {

View File

@ -0,0 +1,123 @@
// JavaScript Document
// Replaces libPDFscripts.js
// NEW - Process Scripts
// Utility to fetch PDF bytes
//const path = FileSystemHandle.require('node:path')
let showLog = true;
const dd = createDebugLogger(showLog, "dd");
function createDebugLogger(debug, prefix = "") {
return function (message, ...optionalParams) {
if (debug) {
console.log(
`[${prefix}]`.toUpperCase(), `${message}`,
...optionalParams
);
}
};
}
async function fetchPdfBytes(filePath) {
dd(filePath);
try {
const response = await fetch(filePath);
if (!response.ok) throw new Error(`Failed to fetch PDF from ${filePath}`);
return await response.arrayBuffer();
} catch (err) {
console.error("Error fetching PDF bytes:", err);
throw err;
}
}
// Update form fields in the PDF
async function updatePdfFields(
pdfBytes,
dataSources,
skipMissingFields = true
) {
try {
const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
const form = pdfDoc.getForm();
dataSources.forEach((dataSource) => {
dataSource.forEach((record) => {
Object.entries(record).forEach(([fieldName, fieldValue]) => {
try {
const formField = form.getTextField(fieldName);
if (formField) {
dd(fieldName, "-->", fieldValue);
formField.setText(String(fieldValue));
} else if (!skipMissingFields) {
console.warn(`Field "${fieldName}" not found.`);
}
} catch (err) {
console.error(`Error updating field "${fieldName}":`, err);
}
});
});
});
return await pdfDoc.save();
} catch (err) {
console.error("Error updating PDF fields:", err);
throw err;
}
}
// Function to trigger download of the updated PDF
function downloadPdf(pdfBytes, fileName) {
const blob = new Blob([pdfBytes], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
const link = Object.assign(document.createElement("a"), {
href: url,
download: fileName,
});
link.click();
URL.revokeObjectURL(url); // Clean up the URL immediately
}
function generateRandomFilename(length = 8, prefix = "", suffix = "") {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const array = Array.from({ length }, () =>
characters.charAt(Math.floor(Math.random() * characters.length))
);
const filename = `${prefix}${array.join("")}${suffix}`;
dd("Random Filename:", filename);
return filename;
}
// Example Usage:
// Wrapper function to fetch, update, and download PDF
async function processAndDownloadPdf(filePath, ...dataSources) {
try {
const pdfBytes = await fetchPdfBytes(filePath);
const updatedPdfBytes = await updatePdfFields(pdfBytes, dataSources);
const fileName = generateRandomFilename(8, "ERT_", ".pdf");
//const saveFilePath = await savePdfToFile(pdfBytes);
//dd("[PDF PATH]", saveFilePath);
downloadPdf(updatedPdfBytes, fileName);
} catch (err) {
console.error("Error processing the PDF:", err);
}
}
async function savePdfToFile(pdfBytes) {
const randomFilename = generateRandomFilename(12, "", ".pdf");
File.path;
const filePath = Filehandle.path.join(__dirname, "PDF", randomFilename);
dd("[SAVE TO DISK]", randomFilename);
// Save the file to disk
await fs.writeFile(filePath, Buffer.from(pdfBytes));
// Return a URL or file path based on your server setup
return `/PDF/${randomFilename}`;
}

View File

@ -0,0 +1,2 @@
// JavaScript Document

View File

@ -48,6 +48,15 @@
args: ["/PDF/testpdf.pdf", "{{datastore1.data}}", "{{data_view1.data}}"]
}
}</script>
<script is="dmx-flow" id="processPDF" type="text/dmx-flow">{
runJS: {
name: "PDFprocess",
output: true,
outputType: "text",
function: "processAndDownloadPdf",
args: ["/PDF/testpdf.pdf", "{{datastore1.data}}", "{{data_view1.data}}"]
}
}</script>
<div class="container wappler-block pt-3 pb-3">
<div class="modal" id="modal-success" is="dmx-bs5-modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
@ -169,7 +178,8 @@
<div class="col">
<button id="btn2" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal1">Print</button>
<button id="savePDF" class="btn btn-warning" data-bs-target="#modal1" dmx-on:click="flowClearPoints.run()">SAVE</button>
<button id="btn7" class="btn" data-bs-toggle="modal" data-bs-target="#modalTestButton">modalTest</button>
<button id="btn7" class="btn" data-bs-toggle="modal" data-bs-target="#modalTestButton">ModelTest</button>
<button id="btn8" class="btn btn-info" dmx-on:click="processPDF.run()">ProcessPDF</button>
<p>A nice paragraph {{myResult}}</p>
</div>
<div class="col"></div>
@ -301,7 +311,7 @@
</table>
</div>
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
<script src="/PDF/libPDFscripts.js"></script>
<script src="/js/libProcessScript.js"></script>
<!--
<script src="/PDF/pdfLibSignature.js"></script>
-->