Xules Codice

Oggi vedremo Itext una libreria PDF in Java che ci consente di creare, analizzare, modificare e mantenere i documenti Nel formato PDF IText non è utilizzato solo da Java è anche usato in .NET, Android e GAE per fornire le sue applicazioni con PDF.

Logo ITEXT

Cosa fornisce Itext?

ITEXT è una libreria PDF che ci consente di creare, adattarsi, revisione e mantenimento dei documenti nel formato del documento PDF, alcune delle funzionalità principali sono:

  • Genera documenti e report estratti da un file XML o da un database
  • Creare mappe e libri, incorporando funzioni interattive in formato PDF
  • Aggiungi segnalibri, numeri di pagina, filigrane, E altre caratteristiche ai documenti PDF esistenti
    dividi o concatena le pagine dei file PDF esistenti
  • Riempire forme interattive.
  • server generato dinamicamente o manipolare i documenti PDF in un browser Web.

Java Itext PDF – Creazione di un PDF in Java con IPEXT

  1. Aggiungi le librerie e cres Masters Class
  2. Creazione del documento e dei metadati
  3. Abbiamo creato la nostra prima pagina
  4. aggiungi altri elementi da testo al nostro PDF
  5. Uso di tavoli in ItExt: PDFPTABLE
  6. Risultato finale (codice completo)
  7. Documentazione utilizzata

software e strumenti utilizzati

  • Netbeans
  • java
  • italy pdf

Aggiungi le librerie e crea classe

Inizieremo a scaricare l’ultima versione di questa libreria, è possibile accedere a SourceForge o scaricarlo da questo collegamento: download da tasto da SourceForge.

Configura il progetto

Per questo progetto utilizzeremo NetBeans che fornisce un grande supporto per lo sviluppo di applicazioni con Java.

Abbiamo aperto NetBeans e cerchiamo la nuova opzione di progetto, quando la procedura guidata si aprivamo Java > Applicazione Java, quindi ti daremo solo un nome al nostro progetto e al suo UBIC IZAZIONE.

È possibile utilizzare qualsiasi altro IDE per Java, tutto ciò di cui avrai davvero bisogno è aggiungere le librerie ITEXT.

Creeremo classe

per creare a Nuova classe Soggiorniamo sul progetto e nel menu a comparsa selezioniamo il nuovo > Classe Java, ci presentiamo il nome della classe e il pacchetto dove vogliamo localizzare, Nel mio caso:

  • Nome della classe: GeneratePDFFFileiText.java
  • Pacchetto: org.xulescode.itext

Questo codice mira ad essere Il più semplice possibile, quindi inseriremo tutto il codice all’interno del metodo: Public Void CreatePDF (file pdfnewfile) per essere in grado di seguire come uno script in quanto creiamo un documento PDF e una variabile di origine e una posizione per un’immagine che lo farò Utilizzare nell’esempio:

package org.xulescode.itext;import com.itextpdf.*;import java.io.*; /** * Example of using the iText library to work with PDF documents on Java, * lets you create, analyze, modify and maintain documents in this format. * Ejemplo de uso de la librería iText para trabajar con documentos PDF en Java, * nos permite crear, analizar, modificar y mantener documentos en este formato. * * @author xules You can follow me on my website http://www.codigoxules.org/en * Puedes seguirme en mi web http://www.codigoxules.org */public class GeneratePDFFileIText { private static final Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 26, Font.BOLDITALIC); private static final Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL); private static final Font categoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); private static final Font subcategoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD); private static final Font blueFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED); private static final Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); private static final String iTextExampleImage = "/home/xules/codigoxules/iText-Example-image.png"; /** * We create a PDF document with iText using different elements to learn * to use this library. * Creamos un documento PDF con iText usando diferentes elementos para aprender * a usar esta librería. * @param pdfNewFile <code>String</code> * pdf File we are going to write. * Fichero pdf en el que vamos a escribir. */ public void createPDF(File pdfNewFile) { // Aquí introduciremos el código para crear el PDF. }}

Creazione del documento e metadati

In questo Primo passo con Java Istext PDF Dobbiamo creare un documento per lavorare con lui e aggiungerlo Le diverse pagine necessarie per il nostro esempio: documento documento = nuovo documento ();, una volta creato associare il documento di lavoro con il file di uscita, questo è fatto con il metodo com.itextpdf.text.pdf.pdfwriter, questo è Il codice di cui abbiamo bisogno:

 // We create the document and set the file name. // Creamos el documento e indicamos el nombre del fichero. try { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile)); } catch (FileNotFoundException fileNotFoundException) { System.out.println("No such file was found to generate the PDF " + "(No se encontró el fichero para generar el pdf)" + fileNotFoundException); } document.open(); // AQUÍ COMPLETAREMOS NUESTRO CÓDIGO PARA GENERAR EL PDF document.close(); System.out.println("Your PDF file has been generated!(¡Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println("The file not exists (Se ha producido un error al generar un documento): " + documentException); }

Ora aggiungere informazioni al nostro documento creato con Java Itext PDF inserendo i metadati, questi vengono aggiunti direttamente nei valori Del documento precedentemente definito: Documento:

 // We add metadata to PDF // Añadimos los metadatos del PDF document.addTitle("Table export to PDF (Exportamos la tabla a PDF)"); document.addSubject("Using iText (usando iText)"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Código Xules"); document.addCreator("Código Xules");

Creiamo la nostra prima pagina

Per la creazione della prima pagina useremo gli elementi generali:

  • com.itextpdf.text.chunk: la parte più piccola che può essere aggiunta a un documento, la maggior parte degli elementi può essere divisa In diversi blocchi e fondamentalmente è una stringa con una determinata fonte.
  • com.itextpdf.text.image: Rappresentazione grafica delle immagini che possiamo usare: JPEG, PNG o GIF.
  • com.itextpdf.text.fagraph: è una serie di blocchi.

e l’elemento com.itextpdf.text.chapter che usiamo per aggiungere una sezione speciale ed è così Dove stiamo andando in questo esempio gli elementi sopra menzionati, è possibile consultarlo nel codice:

Aggiungi altro Elementi ItExt al nostro PDF

Ora aggiungiamo semplicemente alcuni elementi alla nostra nuova pagina per mantenere gli elementi di test, prima di tutto abbiamo creato un nuovo capitolo a cui ci sono nominati utilizzando com.itextpdf.text.Paragrafo, creiamo anche un altro che aggiungeremo di seguito:

 // Second page - some elements // Segunda página - Algunos elementos Chapter chapSecond = new Chapter(new Paragraph(new Anchor("Some elements (Añadimos varios elementos)")), 1); Paragraph paragraphS = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont);

per dimostrare che molte cose possono essere fatte aggiungendo un esempio di come sottolineare un paragrafo con Una linea tratteggiata, Esempio prelevato dal blog PDF Java Istext e in cui viene utilizzato l’elemento com.itextpdf.text.pdf.draw.dottedline.pdf.Draw.DottedlineSineSeporator che disegna una linea tratteggiata da sinistra a destra:

 // Underline a paragraph by iText (subrayando un párrafo por iText) Paragraph paragraphE = new Paragraph("This line will be underlined with a dotted line (Está línea será subrayada con una línea de puntos)."); DottedLineSeparator dottedline = new DottedLineSeparator(); dottedline.setOffset(-2); dottedline.setGap(2f); paragraphE.add(dottedline); chapSecond.addSection(paragraphE);

Per creare un semplice esempio di elenchi aggiungiamo dall’esempio: elenco esempi di IText, semplicemente per mostrare un esempio di utilizzo e vedere quanto è semplice eseguire com .ITEXTPDF.Text.List:

Alla fine, non possiamo dimenticare Aggiungi il nostro codice al documento con document.add (…).

Utilizzo delle tabelle in ItExt: PDFtribuble

In questa sezione ci concentriamo sull’uso di com.itextpdf.text.pdf.pdftable creando a La nuova pagina, che diventerà diversi come vedremo, per la lunghezza della tabella che implenteremo per vedere l’operazione di com.itextpdf.text.pdf.pdfptable.

Prima di tutto nel codice Aggiungiamo diversi articoli per aggiungere titolo e sottotitolo, che non spiegherò di più perché usiamo elementi precedentemente spiegati e per ulteriori dettagli è possibile vederlo direttamente nel codice.

Concentrati su com.itextpdf.text .pdf.pdfptable che è un elemento che ci consente di creare una tabella la cui posizione può essere assoluta ma può anche essere aggiunta direttamente al documento. In questo esempio, aggiungiamo semplicemente un testo, ma sarà molto utile riempire ad esempio con i dati ottenuti dal database.

i passaggi che seguiamo con il codice:

  • Creiamo la tabella: tabella pdfptable = nuovo pdfptable (numcolumns);
  • Aggiungi le schede dalla tabella: Columnheader = New Pdfpcell (nuova frase (“Col” + colonna);
  • Complementiamo il contenuto della tabella con A per loop aggiungendo ogni cella con il codice: Tabella.Aggiunta (“riga” + riga + “- Col” + colonna;
  • Infine, aggiungeremo la tabella al documento, aggiungendolo in questo caso (non deve essere così) al paragrafo che creiamo all’inizio in modo che vada dopo.

Questo è il codice:

 // How to use PdfPTable // Utilización de PdfPTable // We use various elements to add title and subtitle // Usamos varios elementos para añadir título y subtítulo Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont); anchor.setName("Table export to PDF (Exportamos la tabla a PDF)"); Chapter chapTitle = new Chapter(new Paragraph(anchor), 1); Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); Section paragraphMore = chapTitle.addSection(paragraph); paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)")); Integer numColumns = 6; Integer numRows = 120; // We create the table (Creamos la tabla). PdfPTable table = new PdfPTable(numColumns); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column < numColumns; column++) { columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < numColumns; column++) { table.addCell("Row " + row + " - Col" + column); } } // We add the table (Añadimos la tabla) paragraphMore.add(table); // We add the paragraph with the table (Añadimos el elemento con la tabla). document.add(chapTitle); document.close(); System.out.println("Your PDF file has been generated!(¡Se ha generado tu hoja PDF!");

Risultato finale (codice completo)

Abbiamo già completato il nostro codice per generare un PDF con IText, ora dobbiamo eseguirlo dal nostro metodo principale:

 /** * @param args the command line arguments */ public static void main(String args) { GeneratePDFFileIText generatePDFFileIText = new GeneratePDFFileIText(); generatePDFFileIText.createPDF(new File("/home/xules/codigoxules/GeneratePDFFileIText.pdf")); }

in Il link è possibile scaricare il codice completo di questo esempio:

Icono icona

Generazione di un PDF da Java con ItExt

1 file (s) 8.75 kb

Inoltre, puoi vedere direttamente il codice completo:

package org.xulescode.itext;import com.itextpdf.text.Anchor;import com.itextpdf.text.BadElementException;import com.itextpdf.text.BaseColor;import com.itextpdf.text.Chapter;import com.itextpdf.text.Chunk;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Element;import com.itextpdf.text.Font;import com.itextpdf.text.FontFactory;import com.itextpdf.text.Image;import com.itextpdf.text.List;import com.itextpdf.text.ListItem;import com.itextpdf.text.Paragraph;import com.itextpdf.text.Phrase;import com.itextpdf.text.Section;import com.itextpdf.text.pdf.PdfPCell;import com.itextpdf.text.pdf.PdfPTable;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.text.pdf.draw.DottedLineSeparator;import java.io.*; /** * Example of using the iText library to work with PDF documents on Java, * lets you create, analyze, modify and maintain documents in this format. * Ejemplo de uso de la librería iText para trabajar con documentos PDF en Java, * nos permite crear, analizar, modificar y mantener documentos en este formato. * * @author xules You can follow me on my website http://www.codigoxules.org/en * Puedes seguirme en mi web http://www.codigoxules.org */public class GeneratePDFFileIText { // Fonts definitions (Definición de fuentes). private static final Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 26, Font.BOLDITALIC); private static final Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL); private static final Font categoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); private static final Font subcategoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD); private static final Font blueFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED); private static final Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); private static final String iTextExampleImage = "/home/xules/codigoxules/iText-Example-image.png"; /** * We create a PDF document with iText using different elements to learn * to use this library. * Creamos un documento PDF con iText usando diferentes elementos para aprender * a usar esta librería. * @param pdfNewFile <code>String</code> * pdf File we are going to write. * Fichero pdf en el que vamos a escribir. */ public void createPDF(File pdfNewFile) { // We create the document and set the file name. // Creamos el documento e indicamos el nombre del fichero. try { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile)); } catch (FileNotFoundException fileNotFoundException) { System.out.println("No such file was found to generate the PDF " + "(No se encontró el fichero para generar el pdf)" + fileNotFoundException); } document.open(); // We add metadata to PDF // Añadimos los metadatos del PDF document.addTitle("Table export to PDF (Exportamos la tabla a PDF)"); document.addSubject("Using iText (usando iText)"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Código Xules"); document.addCreator("Código Xules"); // First page // Primera página Chunk chunk = new Chunk("This is the title", chapterFont); chunk.setBackground(BaseColor.GRAY); // Let's create de first Chapter (Creemos el primer capítulo) Chapter chapter = new Chapter(new Paragraph(chunk), 1); chapter.setNumberDepth(0); chapter.add(new Paragraph("This is the paragraph", paragraphFont)); // We add an image (Añadimos una imagen) Image image; try { image = Image.getInstance(iTextExampleImage); image.setAbsolutePosition(2, 150); chapter.add(image); } catch (BadElementException ex) { System.out.println("Image BadElementException" + ex); } catch (IOException ex) { System.out.println("Image IOException " + ex); } document.add(chapter); // Second page - some elements // Segunda página - Algunos elementos Chapter chapSecond = new Chapter(new Paragraph(new Anchor("Some elements (Añadimos varios elementos)")), 1); Paragraph paragraphS = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); // Underline a paragraph by iText (subrayando un párrafo por iText) Paragraph paragraphE = new Paragraph("This line will be underlined with a dotted line (Está línea será subrayada con una línea de puntos)."); DottedLineSeparator dottedline = new DottedLineSeparator(); dottedline.setOffset(-2); dottedline.setGap(2f); paragraphE.add(dottedline); chapSecond.addSection(paragraphE); Section paragraphMoreS = chapSecond.addSection(paragraphS); // List by iText (listas por iText) String text = "test 1 2 3 "; for (int i = 0; i < 5; i++) { text = text + text; } List list = new List(List.UNORDERED); ListItem item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "a b c align "; for (int i = 0; i < 5; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "supercalifragilisticexpialidocious "; for (int i = 0; i < 3; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); paragraphMoreS.add(list); document.add(chapSecond); // How to use PdfPTable // Utilización de PdfPTable // We use various elements to add title and subtitle // Usamos varios elementos para añadir título y subtítulo Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont); anchor.setName("Table export to PDF (Exportamos la tabla a PDF)"); Chapter chapTitle = new Chapter(new Paragraph(anchor), 1); Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); Section paragraphMore = chapTitle.addSection(paragraph); paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)")); Integer numColumns = 6; Integer numRows = 120; // We create the table (Creamos la tabla). PdfPTable table = new PdfPTable(numColumns); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column < numColumns; column++) { columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < numColumns; column++) { table.addCell("Row " + row + " - Col" + column); } } // We add the table (Añadimos la tabla) paragraphMore.add(table); // We add the paragraph with the table (Añadimos el elemento con la tabla). document.add(chapTitle); document.close(); System.out.println("Your PDF file has been generated!(¡Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println("The file not exists (Se ha producido un error al generar un documento): " + documentException); } } /** * @param args the command line arguments */ public static void main(String args) { GeneratePDFFileIText generatePDFFileIText = new GeneratePDFFileIText(); generatePDFFileIText.createPDF(new File("/home/xules/codigoxules/GeneratePDFFileIText.pdf")); }}

Questo è il PDF che è ottenuto come a Risultato finale di questo esempio:

Icono

icon

.

Genera il file PDF Itext da Java

1 file (s) 157.59 kb

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *