jsPDF OPENPA pdf utilty

PRINTPDF

Questo programma utilizza la libreria jsPDF per generare un file PDF a partire da una serie di istruzioni specificate in un file JSON (specifiche.json) per generare un file PDF. Il codice è diviso in tre funzioni: printData(), generatePDF() e window.onload().

La funzione printData() viene chiamata quando l’utente fa clic sul pulsante “Stampa”. La funzione controlla se il file specifiche.json è stato caricato correttamente. Se il file è stato caricato correttamente, la funzione chiama la funzione generatePDF().

La funzione generatePDF() crea un nuovo oggetto jsPDF e lo configura. Quindi, la funzione legge il file specifiche.json e itera su ogni record nel file. Per ogni record, la funzione esegue l’istruzione specificata nel campo instruction.

Le istruzioni possibili sono:

  • CONFIG: configura le proprietà del documento PDF.
  • TEXT: aggiunge del testo al documento PDF.
  • PAGE: aggiunge una nuova pagina al documento PDF.
  • OUTPUT: imposta il nome del file PDF che verrà generato.

La funzione window.onload() viene chiamata quando la pagina viene caricata. La funzione controlla se il file specifiche.json è stato caricato correttamente. Se il file è stato caricato correttamente, la funzione abilita il pulsante “Stampa”.

La documentazione tecnica approfondita per la pagina è la seguente:

  • La funzione printData() viene chiamata quando l’utente fa clic sul pulsante “Stampa”.
  • La funzione generatePDF() crea un nuovo oggetto jsPDF e lo configura.
  • La funzione window.onload() viene chiamata quando la pagina viene caricata.
  • Le istruzioni possibili nel file specifiche.json sono: CONFIG, TEXT, PAGE e OUTPUT.

Di seguito sono elencate tutte le opzioni disponibili per l’utente e una breve spiegazione per ciascuna di esse:

  1. CONFIG: questa istruzione consente di configurare le proprietà del documento PDF. Le opzioni disponibili sono:
  • orientation: specifica l’orientamento del documento (valori possibili: “p” per portrait, “l” per landscape).
  • title: specifica il titolo del documento.
  • unit: specifica l’unità di misura utilizzata per le dimensioni del documento (valori possibili: “mm”, “cm”, “in”).
  1. TEXT: questa istruzione consente di aggiungere del testo al documento. Le opzioni disponibili sono:
  • text: il testo da aggiungere.
  • x: la coordinata x del punto di inizio del testo.
  • y: la coordinata y del punto di inizio del testo.
  • align: l’allineamento del testo (valori possibili: “left”, “center”, “right”).
  • font_name: il nome del carattere da utilizzare.
  • font_size: la dimensione del carattere.
  • bold: indica se il testo deve essere in grassetto (valori possibili: true, false).
  • italic: indica se il testo deve essere in corsivo (valori possibili: true, false).
  • color: il colore del testo (valori possibili: qualsiasi valore CSS).
  • background_color: il colore di sfondo del testo (valori possibili: qualsiasi valore CSS).
  1. PAGE: questa istruzione consente di aggiungere una nuova pagina al documento. Le opzioni disponibili sono:
  • file: il percorso del file da utilizzare come immagine di sfondo per la pagina.
  • format: il formato della pagina (valori possibili: “a0”, “a1”, “a2”, “a3”, “a4”, “a5”, “a6”, “a7”, “a8”, “a9”, “a10”, “b0”, “b1”, “b2”, “b3”, “b4”, “b5”, “b6”, “b7”, “b8”, “b9”, “b10”, “c0”, “c1”, “c2”, “c3”, “c4”, “c5”, “c6”, “c7”, “c8”, “c9”, “c10”, “ra0”, “ra1”, “ra2”, “ra3”, “ra4”, “sra0”, “sra1”, “sra2”, “sra3”, “sra4”, “letter”, “legal”, “ledger”).
  • compress: indica se la pagina deve essere compressa (valori possibili: true, false).
  1. OUTPUT: questa istruzione consente di specificare il nome del file di output. L’opzione disponibile è:
  • file: il nome del file di output.

<!DOCTYPE html>
<HTML>
  <HEAD>
    <META charset="UTF-8">
    <TITLE>Generazione di PDF con jsPDF
 Copyright (C) 2010-2021 Federico Priolo TP ONE SRL federico.priolo@tp-one.it
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE
    </TITLE>
  </HEAD>
  <BODY> 
   <H1>Generazione di PDF con jsPDF</H1>
    <P>Clicca sul pulsante per generare il PDF:
    </P>
    <BUTTON onclick="generatePDF()">Genera PDF
    </BUTTON>
<SCRIPT src="/openpa/easyui/jspdf.min.js"></SCRIPT>
<SCRIPT>
      function generatePDF() {
  const doc = new jsPDF();
  let outputFilename = "DOCUMENTO.PDF";
  
  fetch("specifiche.json", {cache: "no-cache"})
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error(`Errore durante il caricamento del file specifiche.json. Codice errore: ${response.status} - ${response.statusText}`);
      }
    })
    .then(data => {
      data.forEach(record => {
        const { instruction, params } = record;
        switch (instruction) {
          case "CONFIG":
            try {
              doc.setProperties({
                orientation: params.orientation || "p",
                title: params.title || "",
                unit: params.unit || "mm"
              });
            } catch (error) {
              alert(`Errore durante la configurazione: ${error}`);
            }
            break;
		 
         case "TEXT":
  const textColor = params.color || "black";
  const backgroundColor = params.background_color || "white";
  doc.setFillColor(backgroundColor);
  doc.setTextColor(textColor);
  try {
    const fontStyle = (params.bold && params.italic) ? "bolditalic" :
                      (params.bold) ? "bold" :
                      (params.italic) ? "italic" :
                      "";
    doc.setFont(params.font_name || "Courier New", fontStyle);
    doc.setFontSize(params.font_size || 12);
    doc.text(params.text, params.x || 10, params.y || 10, {
      align: params.align || "left",
      fillColor: backgroundColor
    });
  } catch (error) {
    alert(`Errore durante l'impostazione del testo: ${error}`);
  }
  break;
		 
		 
          case "PAGE":
            if (params.file) {
              fetch(params.file)
                .then(response => {
                  if (response.ok) {
                    return response.arrayBuffer();
                  } else {
                    throw new Error(`Errore durante il caricamento del file ${params.file}. Codice errore: ${response.status} - ${response.statusText}`);
                  }
                })
                .then(arrayBuffer => {
                  try {
                    doc.addPage(arrayBuffer, params.format || "a4", params.compress || false);
                  } catch (error) {
                    alert(`Errore durante l'aggiunta della pagina: ${error}`);
                  }
                })
                .catch(error => {
                  alert(error.message);
                });
            } else {
              try {
                doc.addPage();
              } catch (error) {
                alert(`Errore durante l'aggiunta della pagina: ${error}`);
              }
            }
            break;
          case "OUTPUT":
            outputFilename = params.file || "DOCUMENTO.PDF";
            break;
          default:
            break;
        }
      });
      try {
        doc.save(outputFilename);
      } catch (error) {
        alert(`Errore durante il salvataggio del file PDF: ${error}`);
      }
    })
    .catch(error => {
      alert(error.message);
    });
}
    </SCRIPT>   
  </BODY>
</HTML>
[
  { "instruction": "CONFIG", "params": { "orientation": "l", "title": "Documento di prova", "unit": "mm" } },
  { "instruction": "PAGE", "params": { "format": "a4", "compress": true } },
  { "instruction": "TEXT", "params": { "text": "Prima pagina\nStringa di testo su una nuova riga", "x": 50, "y": 50, "font_size": 16, "align": "center" } },
  { "instruction": "PAGE", "params": { "file": "pagina2.pdf", "label": "Pagina 2" } },
  { "instruction": "TEXT", "params": { "text": "Stringa di testo su una nuova riga", "x": 10, "y": 50, "font_size": 16, "align": "center" } },
  
  { "instruction": "TEXT", "params": { "text": "Stringa di testo su una nuova riga", "x": 20, "y": 50, "font_size": 16, "align": "center" } },
  { "instruction": "CONFIG", "params": { "orientation": "p", "unit": "pt" } },
  { "instruction": "TEXT", "params": { "text": "Stringa di testo su una nuova riga", "x": 30, "y": 50, "font_size": 16, "align": "center", "color": "red", "background_color": "yellow" } },
  
  { "instruction": "TEXT", "params": { "text": "Stringa di testo su una nuova riga", "x": 40, "y": 50, "font_size": 16, "align": "center", "font_name": "Helvetica", "bold": true } },
  
  { "instruction": "TEXT", "params": { "text": "Stringa di testo su una nuova riga", "x": 50, "y": 50, "font_size": 16, "align": "center", "font_name": "Times New Roman", "italic": true } },
  
  { "instruction": "TEXT", "params": { "text": "Stringa di testo su una nuova riga", "x": 60, "y": 50, "font_size": 16, "align": "center", "font_name": "Arial", "bold": true, "italic": true, "color": "blue" } },
  { "instruction": "OUTPUT", "params": { "file": "prova.pdf" } }
]





<!DOCTYPE html>
<HTML>

<HEAD>
    <META charset="UTF-8">
    <TITLE>Generazione di PDF con pdf-lib</TITLE>
</HEAD>

<BODY>
    <H1>Generazione di PDF con pdf-lib</H1>
    <P>Clicca sul pulsante per generare il PDF:</P>
    <BUTTON onclick="generatePDF()">Genera PDF</BUTTON>

    <!-- Importazione della libreria pdf-lib da CDN -->
    <script src="/OPENPA/easyui/pdf-lib.js"></script>

    <SCRIPT>
        async function generatePDF() {
            const { PDFDocument, rgb, StandardFonts } = PDFLib;

            const pdfDoc = await PDFDocument.create();
            const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

            let outputFilename = "DOCUMENTO.PDF";

            fetch("specifiche2.json", { cache: "no-cache" })
                .then(response => response.json())
                .then(async data => {
                    for (const record of data) {
                        const { instruction, params } = record;

                        switch (instruction) {
                            case "TEXT":
                                const page = pdfDoc.getPages()[pdfDoc.getPages().length - 1];
                                const color = params.color ? rgb(...params.color) : rgb(0, 0, 0);
                                page.drawText(params.text || "", {
                                    x: params.x || 0,
                                    y: params.y || 0,
                                    size: params.font_size || 10,
                                    font: helveticaFont,
                                    color: color
                                });
                                break;


							case "IMAGE":
								if (params.url) {
								// Carica l'immagine dal web
								const imageBytes = await fetch(params.url).then(res => res.arrayBuffer());
	
								// Embedda l'immagine nel PDF
								const image = await pdfDoc.embedPng(imageBytes);  // Supponendo che sia PNG. Usa `embedJpg` se è JPEG.
		
								// Preleva l'ultima pagina (o quella specificata)
								const page = pdfDoc.getPages()[pdfDoc.getPages().length - 1];
	
								// Disegna l'immagine
								page.drawImage(image, {
								x: params.x || 0,
								y: params.y || 0,
								width: params.width || image.width,
								height: params.height || image.height
								});
								} else {
								console.warn(`URL dell'immagine non fornito`);
								}
								break;


                            case "PAGE":
                                if (params.file) {
                                    const existingPdfBytes = await fetch(params.file).then(res => res.arrayBuffer());
                                    const existingPdfDoc = await PDFDocument.load(existingPdfBytes);
                                    const copiedPages = await pdfDoc.copyPages(existingPdfDoc, existingPdfDoc.getPageIndices());
                                    copiedPages.forEach(page => pdfDoc.addPage(page));
                                } else {
                                    let pageSize = getPageSize(params.size, params.orientation);
                                    pdfDoc.addPage(pageSize);
                                }
                                break;

                            case "OUTPUT":
                                outputFilename = params.file || outputFilename;
                                break;

                            default:
                                console.warn(`Istruzione non riconosciuta: ${instruction}`);
                        }
                    }

                    const pdfBytes = await pdfDoc.save();

                    const blob = new Blob([pdfBytes], { type: 'application/pdf' });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = outputFilename;
                    link.click();

                })
                .catch(error => {
                    console.error("Errore:", error.message);
                });
        }

        function getPageSize(size, orientation) {
            switch (size) {
                case 'A3':
                    return orientation === 'landscape' ? [1191, 842] : [842, 1191];
                case 'A4':
                default:
                    return orientation === 'landscape' ? [842, 595] : [595, 842];
            }
        }
    </SCRIPT>
</BODY>

</HTML>
[
    { "instruction": "PAGE", "params": { "size": "A4", "orientation": "portrait" } },
    { "instruction": "TEXT", "params": { "text": "Benvenuto nel documento A4 in verticale!", "x": 50, "y": 800, "font_size": 20 } },
    { "instruction": "PAGE", "params": { "size": "A4", "orientation": "landscape" } },
    { "instruction": "TEXT", "params": { "text": "Questo è un documento A4 in orizzontale!", "x": 50, "y": 550, "font_size": 20 } },
    { "instruction": "PAGE", "params": { "size": "A3", "orientation": "portrait" } },
    { "instruction": "TEXT", "params": { "text": "E ora, un documento A3 in verticale!", "x": 50, "y": 1100, "font_size": 20 } },
    { "instruction": "PAGE", "params": { "size": "A3", "orientation": "landscape" } },
    { "instruction": "TEXT", "params": { "text": " un documento A3 in orizzontale!", "x": 50, "y": 1050, "font_size": 20, "color": [1, 0, 0] } },
	{"instruction": "PAGE", "params": { "file": "pagina2.pdf" }},
    { "instruction": "TEXT", "params": { "text": "DATI AGGIUNGI SU PAGAINA2!", "x": 50, "y": 800, "font_size": 16, "color": [1, 0, 0] } },
{
    "instruction": "IMAGE",
    "params": {
        "url": "http://127.0.0.1/WEBcofin/IMAGES/logotp.png",
        "x": 100,
        "y": 500,
        "width": 150,
        "height": 100
    }
},

    { "instruction": "OUTPUT", "params": { "file": "MioDocumento.pdf" } }

    
   
]