- Catalogo: qualità di stampa, margini. ora è 300 DPI.
This commit is contained in:
148049
.yarn/releases/yarn-1.22.22.cjs
vendored
Executable file
148049
.yarn/releases/yarn-1.22.22.cjs
vendored
Executable file
File diff suppressed because one or more lines are too long
5
.yarnrc
Normal file
5
.yarnrc
Normal file
@@ -0,0 +1,5 @@
|
||||
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
|
||||
|
||||
yarn-path ".yarn/releases/yarn-1.22.22.cjs"
|
||||
@@ -33,6 +33,7 @@
|
||||
"email-templates": "^10.0.1",
|
||||
"express": "^4.18.1",
|
||||
"formidable": "^2.0.1",
|
||||
"ghostscript4js": "^3.2.3",
|
||||
"i18n": "^0.15.0",
|
||||
"image-downloader": "^4.3.0",
|
||||
"internet-available": "^1.0.0",
|
||||
@@ -42,6 +43,7 @@
|
||||
"lodash": "^4.17.21",
|
||||
"mongodb": "^4.4.1",
|
||||
"mongoose": "^5.13.15",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"mysql": "^2.18.1",
|
||||
"node-cron": "^3.0.2",
|
||||
"node-emoji": "^1.11.0",
|
||||
@@ -51,6 +53,8 @@
|
||||
"node-telegram-bot-api": "^0.65.1",
|
||||
"nodemailer": "^6.7.8",
|
||||
"npm-check-updates": "^16.14.18",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdf-parse": "^1.1.1",
|
||||
"pem": "^1.14.6",
|
||||
"preview-email": "^3.0.7",
|
||||
"pug": "^3.0.2",
|
||||
|
||||
BIN
public/upload/catalogo/Paolo_stampa_2664x3685.jpg
Normal file
BIN
public/upload/catalogo/Paolo_stampa_2664x3685.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 554 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 3.2 MiB |
@@ -30,8 +30,286 @@ const { ImageDownloader } = require('../tools/general.js');
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const gs = require('ghostscript4js');
|
||||
|
||||
const { PDFDocument, rgb } = require('pdf-lib');
|
||||
|
||||
const pdf = require('pdf-parse');
|
||||
|
||||
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
const multer = require('multer');
|
||||
|
||||
const DIR_PDF_IN = __dirname + '/upload/files_input/';
|
||||
const DIR_PDF_OUT = __dirname + '/upload/files_output/';
|
||||
|
||||
const upload = multer({ dest: DIR_PDF_IN });
|
||||
|
||||
const util = require('util');
|
||||
const cwd = process.cwd();
|
||||
|
||||
const { exec } = require('child_process');
|
||||
|
||||
const execPromise = util.promisify(exec);
|
||||
|
||||
|
||||
async function compressPdf(inputFile, outputFile, compressione) {
|
||||
try {
|
||||
const tempFolder = path.join(cwd, "temp");
|
||||
const hasTempFolder = tools.isFileExists(tempFolder);
|
||||
|
||||
if (!hasTempFolder) {
|
||||
await fs.mkdir(tempFolder); // Usa la versione promessa di mkdir
|
||||
}
|
||||
|
||||
/*
|
||||
Quando utilizzi Ghostscript per comprimere un PDF e desideri controllare la qualità di stampa, puoi modificare i parametri dell'opzione -dPDFSETTINGS per ottenere risultati migliori per scopi di stampa.
|
||||
Le seguenti opzioni sono disponibili per -dPDFSETTINGS:
|
||||
|
||||
Opzioni di -dPDFSETTINGS
|
||||
/screen: Buona per la visualizzazione su schermo; bassa qualità e dimensione del file ridotta.
|
||||
/ebook: Ottimizza il PDF per la lettura su ebook; qualità media e dimensione media.
|
||||
/printer: Ottimizza il PDF per la stampa di qualità; migliora la risoluzione rispetto a /ebook.
|
||||
/prepress: Ottimizza per la stampa di alta qualità; ideale per progetti di stampa professionali.
|
||||
/default: Usa impostazioni predefinite; generalmente fornisce un buon equilibrio tra qualità e dimensione.
|
||||
*/
|
||||
|
||||
// Comprime il PDF utilizzando Ghostscript
|
||||
const gsCommand = `gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/${compressione} -dNOPAUSE -dQUIET -dBATCH -sOutputFile="${outputFile}" "${inputFile}"`;
|
||||
|
||||
console.log('gsCommand', gsCommand);
|
||||
|
||||
// Esegui il comando per la compressione
|
||||
await execPromise(gsCommand);
|
||||
|
||||
console.log(`PDF compresso e salvato come '${outputFile}'`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Errore durante la compressione:', error);
|
||||
throw error; // Propaga l'errore
|
||||
}
|
||||
}
|
||||
|
||||
async function convertPDF_GS(inputFile, outputFile, width, height) {
|
||||
// Verifica che il file di input esista
|
||||
if (!tools.isFileExists(inputFile)) {
|
||||
throw new Error(`Il file di input non esiste: ${inputFile}`);
|
||||
}
|
||||
|
||||
// Converti cm in punti (1 cm = 28.34646 punti)
|
||||
const widthPt = width * 28.34646;
|
||||
const heightPt = height * 28.34646;
|
||||
|
||||
// Arrotonda i valori
|
||||
const widthPx = Math.round(widthPt);
|
||||
const heightPx = Math.round(heightPt);
|
||||
|
||||
// Comando Ghostscript
|
||||
const gsCommand = [
|
||||
'-sDEVICE=pdfwrite',
|
||||
'-dCompatibilityLevel=1.4',
|
||||
'-dPDFSETTINGS=/prepress',
|
||||
'-dNOPAUSE',
|
||||
'-dQUIET',
|
||||
'-dBATCH',
|
||||
`-dDEVICEWIDTHPOINTS=${widthPx}`,
|
||||
`-dDEVICEHEIGHTPOINTS=${heightPx}`,
|
||||
'-dDPIx=300',
|
||||
'-dDPIy=300',
|
||||
`-sOutputFile=${outputFile}`,
|
||||
inputFile
|
||||
].join(' ');
|
||||
|
||||
try {
|
||||
console.log(gsCommand);
|
||||
await gs.executeSync(gsCommand); // Assicurati che executeSync restituisca una promessa o usa la funzione corretta se è sincrona.
|
||||
console.log('Conversione completata con successo!');
|
||||
|
||||
// Verifica che il file di output sia stato generato
|
||||
if (tools.isFileExists(outputFile)) {
|
||||
console.log('File di output generato:', outputFile);
|
||||
} else {
|
||||
console.error('Il File di output NON è stato generato! :', outputFile);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') {
|
||||
throw new Error(`Il file di input non esiste: ${inputFile}`);
|
||||
} else if (error instanceof gs.GhostscriptError) {
|
||||
throw new Error(`Errore Ghostscript: ${error.message}`);
|
||||
} else {
|
||||
throw new Error(`Errore durante la conversione: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function extractPdfInfo(inputFile) {
|
||||
// Estrai le dimensioni delle pagine utilizzando pdf-lib
|
||||
const existingPdfBytes = fs.readFileSync(inputFile);
|
||||
const pdfDoc = await PDFDocument.load(existingPdfBytes);
|
||||
|
||||
// Ottieni informazioni sulle dimensioni delle pagine
|
||||
const pages = pdfDoc.getPages();
|
||||
const pageInfo = pages.map(page => {
|
||||
const { width, height } = page.getSize();
|
||||
return {
|
||||
width: width, // in punti
|
||||
height: height // in punti
|
||||
};
|
||||
});
|
||||
|
||||
// Estrai informazioni testuali e numero di pagine utilizzando pdf-parse
|
||||
const dataBuffer = fs.readFileSync(inputFile);
|
||||
const data = await pdf(dataBuffer);
|
||||
|
||||
const dpiInfo = {
|
||||
numPages: data.numpages,
|
||||
pageInfo: pageInfo
|
||||
};
|
||||
|
||||
console.log("DPI info might require image extraction (not available directly):");
|
||||
console.log("Number of Pages:", dpiInfo.numPages);
|
||||
console.log("Page Dimensions (in points):", dpiInfo.pageInfo);
|
||||
}
|
||||
|
||||
|
||||
async function convertPDF_PdfLib(inputFile, outputFile, width, height, compressione) {
|
||||
if (!tools.isFileExists(inputFile)) {
|
||||
throw new Error(`Il file di input non esiste: ${inputFile}`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Carica il PDF esistente
|
||||
const existingPdfBytes = fs.readFileSync(inputFile);
|
||||
const pdfDoc = await PDFDocument.load(existingPdfBytes);
|
||||
|
||||
// Crea un nuovo PDF
|
||||
const newPdfDoc = await PDFDocument.create();
|
||||
|
||||
// Itera attraverso le pagine esistenti
|
||||
const pages = pdfDoc.getPages();
|
||||
for (const page of pages) {
|
||||
const { width: originalWidth, height: originalHeight } = page.getSize();
|
||||
|
||||
// Calcola la larghezza e l'altezza in punti
|
||||
const newWidth = width * 72; // Convertito in punti
|
||||
const newHeight = height * 72; // Convertito in punti
|
||||
|
||||
// Crea una nuova pagina con le dimensioni specificate
|
||||
const newPage = newPdfDoc.addPage([newWidth, newHeight]);
|
||||
|
||||
// Calcola lo scaling per mantenere le proporzioni
|
||||
const scaleWidth = newWidth / originalWidth;
|
||||
const scaleHeight = newHeight / originalHeight;
|
||||
const scale = Math.min(scaleWidth, scaleHeight); // Usa il min per mantenere il rapporto
|
||||
|
||||
// Incorpora la pagina esistente nel nuovo PDF
|
||||
const embeddedPage = await newPdfDoc.embedPage(page);
|
||||
|
||||
// Disegna la pagina incorporata nel nuovo PDF
|
||||
newPage.drawPage(embeddedPage, {
|
||||
x: (newWidth - originalWidth * scale) / 2, // Centrato orizzontalmente
|
||||
y: (newHeight - originalHeight * scale) / 2, // Centrato verticalmente
|
||||
width: originalWidth * scale,
|
||||
height: originalHeight * scale,
|
||||
});
|
||||
}
|
||||
|
||||
// Salva il nuovo PDF
|
||||
const pdfBytes = await newPdfDoc.save();
|
||||
fs.writeFileSync(outputFile, pdfBytes);
|
||||
console.log(`PDF convertito e salvato come '${outputFile}'`);
|
||||
|
||||
const comprimi = false;
|
||||
|
||||
let fileout = outputFile;
|
||||
|
||||
if (compressione) {
|
||||
const compressed = tools.removeFileExtension(outputFile) + '-compressed.pdf';
|
||||
|
||||
await compressPdf(outputFile, compressed, compressione);
|
||||
|
||||
extractPdfInfo(compressed);
|
||||
fileout = compressed;
|
||||
}
|
||||
|
||||
return fileout;
|
||||
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Endpoint POST per la conversione del PDF
|
||||
router.post('/convert-pdf', upload.single('pdf'), async (req, res) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).send('No file uploaded.');
|
||||
}
|
||||
|
||||
const inputFile = req.file.path;
|
||||
const { width, height, compressione } = req.body;
|
||||
|
||||
if (!width) {
|
||||
fs.unlinkSync(inputFile);
|
||||
return res.status(400).send('Width parameter is required');
|
||||
}
|
||||
|
||||
let outputFile = path.join(DIR_PDF_OUT, `${tools.removeFileExtension(req.file.originalname)}-converted.pdf`);
|
||||
|
||||
try {
|
||||
await fs.promises.mkdir(DIR_PDF_IN, { recursive: true });
|
||||
await fs.promises.mkdir(DIR_PDF_OUT, { recursive: true });
|
||||
|
||||
// console.log('File:', req.file);
|
||||
// console.log('Width:', width);
|
||||
// console.log('Height:', height);
|
||||
|
||||
// Converti il PDF
|
||||
// await convertPDF_GS(inputFile, outputFile, width, height);
|
||||
const fileout = await convertPDF_PdfLib(inputFile, outputFile, width, height, compressione);
|
||||
|
||||
if (fileout) {
|
||||
// Invia il file convertito
|
||||
res.download(fileout, 'output-converted.pdf', (err) => {
|
||||
if (err) {
|
||||
console.error('Errore durante l\'invio del file:', err);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).send('Errore durante l\'invio del file convertito');
|
||||
}
|
||||
} else {
|
||||
// Rimuovi i file temporanei
|
||||
cleanupFiles(inputFile, outputFile);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Errore durante la conversione:', error);
|
||||
cleanupFiles(inputFile, outputFile);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).send(`Errore durante la conversione del PDF: ${error.message}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function cleanupFiles(inputFile, outputFile) {
|
||||
if (inputFile) {
|
||||
tools.deleteFile(inputFile)
|
||||
.catch((err) => {
|
||||
console.error('Errore durante la rimozione del file di INPUT:', err);
|
||||
})
|
||||
};
|
||||
if (outputFile) {
|
||||
tools.deleteFile(outputFile)
|
||||
.catch((err) => {
|
||||
console.error('Errore durante la rimozione del file di output:', err);
|
||||
})
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
router.post('/updateval', authenticate, async (req, res) => {
|
||||
console.log('/updateval', req.body.pairval);
|
||||
idapp = req.body.idapp;
|
||||
|
||||
@@ -4011,6 +4011,16 @@ module.exports = {
|
||||
return path.dirname(filename);
|
||||
},
|
||||
|
||||
async deleteFile(filePath) {
|
||||
try {
|
||||
await fs.promises.unlink(filePath);
|
||||
console.log(`File eliminato con successo: ${filePath}`);
|
||||
} catch (err) {
|
||||
console.error(`Errore durante l'eliminazione del file: ${filePath}`, err);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
delete(mypath, alsothumb, callback) {
|
||||
|
||||
fs.unlink(mypath, function (err) {
|
||||
@@ -4097,7 +4107,11 @@ module.exports = {
|
||||
},
|
||||
|
||||
isFileExists(filename) {
|
||||
return fs.existsSync(filename);
|
||||
try {
|
||||
return fs.existsSync(filename);
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
},
|
||||
|
||||
getiPAddressUser(req) {
|
||||
@@ -4783,6 +4797,20 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
|
||||
removeFileExtension(filename) {
|
||||
// Trova l'ultima occorrenza del punto nel nome del file
|
||||
const lastDotIndex = filename.lastIndexOf('.');
|
||||
|
||||
// Se non c'è un punto o il punto è all'inizio del nome file,
|
||||
// restituisci il nome file originale
|
||||
if (lastDotIndex === -1 || lastDotIndex === 0) {
|
||||
return filename;
|
||||
}
|
||||
|
||||
// Altrimenti, restituisci la parte del nome file prima dell'ultimo punto
|
||||
return filename.substring(0, lastDotIndex);
|
||||
},
|
||||
|
||||
removeSpanAndDivTags(text) {
|
||||
// Rimozione dei tag <span> e </span> dalla stringa di testo
|
||||
const spanRegex = /<span[^>]*>|<\/span>/gi;
|
||||
|
||||
BIN
upload/files/09d8f938929c19d429d3eedd6d9109b6
Normal file
BIN
upload/files/09d8f938929c19d429d3eedd6d9109b6
Normal file
Binary file not shown.
BIN
upload/files/232acec33f0e3059691e732521a1f828
Normal file
BIN
upload/files/232acec33f0e3059691e732521a1f828
Normal file
Binary file not shown.
BIN
uploads/48f966940e014e495c19c2b4b65f6a36
Normal file
BIN
uploads/48f966940e014e495c19c2b4b65f6a36
Normal file
Binary file not shown.
146842
uploads/50bb0536d2cad1f50310255eade97bab
Normal file
146842
uploads/50bb0536d2cad1f50310255eade97bab
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user