Example usage for com.itextpdf.text.pdf PdfWriter getInstance

List of usage examples for com.itextpdf.text.pdf PdfWriter getInstance

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter getInstance.

Prototype


public static PdfWriter getInstance(final Document document, final OutputStream os) throws DocumentException 

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:com.ftt.gui.FrameJoueur.java

private void pdf2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pdf2ActionPerformed

    JoueurDAO fd = new JoueurDAO();
    ArrayList<Joueur> joueurs = (ArrayList<Joueur>) fd.select_trie_par_club();
    SimpleDateFormat formateur = new SimpleDateFormat("dd-MM-yyyy");

    Document document = new Document();

    try {//from w  w  w.  j  a v a  2 s .com
        PdfWriter.getInstance(document, new FileOutputStream("rapport_joueurs.pdf"));

        document.open();

        com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance("ftt.png");
        document.add(image);
        document.add(new Paragraph("Liste des joueurs",
                FontFactory.getFont(FontFactory.TIMES_ROMAN, 18, Font.BOLD)));
        document.add(new Paragraph("   "));

        for (int i = 0; i < joueurs.size(); i++) {
            document.add(new Paragraph("    "));
            document.add(new Paragraph(joueurs.get(i).getNom_club()));
            document.add(new Paragraph("   "));
            Integer val = joueurs.get(i).getId();
            String val1 = joueurs.get(i).getNomJoueur();
            String val2 = joueurs.get(i).getPrenomJoueur();
            String val3 = joueurs.get(i).getDateNaissance();
            String val4 = joueurs.get(i).getCarriere();
            String val5 = joueurs.get(i).getSexe();
            Integer val6 = joueurs.get(i).getPoints();
            PdfPTable table = new PdfPTable(2);
            PdfPCell cell = new PdfPCell(new Paragraph("Joueur id: " + val));
            cell.setColspan(4);
            cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_LEFT);
            cell.setBackgroundColor(BaseColor.GRAY);
            table.addCell(cell);
            table.addCell("Nom");
            table.addCell(val1);
            table.addCell("Prenom");
            table.addCell(val2);
            table.addCell("Date de naissance");
            table.addCell(val3);
            table.addCell("Carriere");
            table.addCell(val4);
            table.addCell("sexe");
            table.addCell(val5);
            table.addCell("points");
            table.addCell(val6.toString());
            document.add(table);
        }

        document.add(new Paragraph("    "));
        document.add(new Paragraph("    "));

        document.add(new Paragraph("Federation Tunisenne de Tennis"));
        document.close();
        JOptionPane.showMessageDialog(null, "Rapport Enregistrer");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:com.gadroves.gsisinve.controller.FacturarController.java

void PrintToPDF(TbFacturaVenta facturaVenta, TbCLienteFactura cLienteFactura)
        throws DocumentException, IOException {
    Font header = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    Font normalBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    Font normal = new Font(Font.FontFamily.HELVETICA, 12);
    String fileName = "Factura_" + facturaVenta.getId() + ".pdf";
    // step 1/*  w ww  .jav  a 2s  .c  o m*/
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(fileName));
    // step 3
    document.open();
    // step 4
    document.add(new Paragraph("Gadroves S.A Factura De Venta", header));
    document.add(new Paragraph(" "));
    document.add(new Paragraph("Factura N" + facturaVenta.getId(), normalBold));
    document.add(new Chunk("Cliente:            ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(cLienteFactura.getName(), normal));

    document.add(new Paragraph());
    document.add(new Chunk("Direccin:        ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(cLienteFactura.getAddress(), normal));

    document.add(new Paragraph());
    document.add(new Chunk("Identificacion: ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(cLienteFactura.getId(), normal));

    document.add(new Paragraph());
    document.add(new Chunk("Credito:            ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(Boolean.FALSE.toString(), normal));
    document.add(new Paragraph());

    for (int i = 0; i < 3; i++)
        document.add(new Paragraph(" "));
    createItemsTable(document, facturaVenta);
    document.add(new Paragraph(" "));
    Paragraph subs = new Paragraph();

    subs.setAlignment(Element.ALIGN_RIGHT);
    subs.setIndentationRight(40);
    subs.add(new Chunk("Subtotal:  " + String.format("%1$" + 10 + "s", String.valueOf(facturaVenta.getSub()))));
    subs.add(Chunk.NEWLINE);
    subs.add(new Chunk(
            "Impuestos:  " + String.format("%1$" + 10 + "s", String.valueOf(facturaVenta.getImpuestos()))));
    subs.add(Chunk.NEWLINE);
    subs.add(new Chunk(
            "Total:       " + String.format("%1$" + 10 + "s", String.valueOf(facturaVenta.getTotal()))));
    subs.add(Chunk.NEWLINE);
    document.add(subs);
    // step 5

    document.close();
    Desktop.getDesktop().open(new File(fileName));
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

public final synchronized void export(final OutputStream os) throws Exception {
    checkParameters();//from   w w  w.ja  v  a2s .  c  om
    Document document = new Document();

    try {
        if (isPrintPageNumbers()) {
            this.totalPages = gePageCount();
            this.actualPage = 0;
        }
        PdfWriter writer = PdfWriter.getInstance(document, os);
        setParametersAndHeaders(writer, document);
        document.open();
        for (File file : this.files) {
            add(file, document, writer);
        }
    } finally {
        ItextUtils.close(document);
    }
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void GeneraPDF(ResultSet Resultados) throws Exception {

    ResultSetMetaData metaData = Resultados.getMetaData();
    Object[] Columnas = new Object[metaData.getColumnCount()];

    String encabezado = "Reportes del Sistema Administrativo" + "\n" + "REGISTROS ACTUALES EN AL BASE DE DATOS"
            + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n";
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));

    Font fuente = new Font(Font.getFamily("ARIAL"), 12, Font.BOLD);

    String choro = "Reporte por fecha de los modulos\n" + "de catalogo" + "\n" + "Systema Administrativo" + "\n"
            + "\n" + "\n" + "\n";

    Image imagen = Image.getInstance(System.getProperty("user.dir") + "/Image/logo.png");
    imagen.setAlignment(Image.TEXTWRAP);

    try {/* w w w. java2s .c  om*/
        Paragraph linea = new Paragraph(encabezado, fuente);
        Phrase para = new Phrase(choro);
        Paragraph fecha = new Paragraph(date + "\n" + "\n");

        PdfPTable tabla = new PdfPTable(Columnas.length);
        tabla.setWidthPercentage(100);

        //Document documento = new Document(PageSize.LETTER);
        Document documento = new Document(PageSize.A4.rotate(), 50, 50, 100, 72);
        File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
        if (!Dir.exists()) {
            Dir.mkdirs();
        }

        String file = System.getProperty("user.dir") + "/Reportes/" + metaData.getTableName(1) + " " + date
                + ".pdf";

        PdfWriter.getInstance(documento, new FileOutputStream(file));

        documento.open();
        documento.add(imagen);
        documento.add(linea);
        documento.add(para);
        documento.add(fecha);

        for (int x = 0; x < Columnas.length; x++) {
            PdfPCell Celda = new PdfPCell(new Paragraph(metaData.getColumnName(x + 1),
                    FontFactory.getFont("arial", 9, Font.BOLD, BaseColor.RED)));
            Celda.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabla.addCell(Celda);
        }

        while (Resultados.next()) {
            for (int x = 0; x < Columnas.length; x++) {
                //if(Resultados.getObject(x+1).getClass().getSimpleName().equals("Integer"))
                PdfPCell Celda = new PdfPCell(new Paragraph(String.valueOf(Resultados.getObject(x + 1)),
                        FontFactory.getFont("arial", 9, BaseColor.BLACK)));
                Celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabla.addCell(Celda);
            }
        }

        documento.add(tabla);
        documento.close();
    } catch (DocumentException e) {
        Log.SaveLog(e.toString());
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        Log.SaveLog(e.toString());
        JOptionPane.showMessageDialog(null, e.getMessage(), "error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void CreateTablePDF(JTable tabla) {
    boolean shapes = false;
    Document document = new Document();
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));
    File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
    if (!Dir.exists()) {
        Dir.mkdirs();//  www .  ja v  a 2  s .co  m
    }
    try {
        PdfWriter writer;
        if (shapes) {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        } else {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(500, 500);
        Graphics2D g2;
        if (shapes) {
            g2 = tp.createGraphicsShapes(500, 500);
        } else {
            g2 = tp.createGraphics(500, 500);
        }

        g2.dispose();
        cb.addTemplate(tp, 30, 300);
    } catch (Exception e) {
        Log.SaveLog(e.toString());
    }
    document.close();
}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * This is the old <code>convert()</code> method, almost untouched.<br>
 * This method will be used if {@link #pdfFormat} is not set.
 *
 * @return true if the conversion was successful.
 *//* w  w w .j  av  a 2s.com*/
private boolean convertSimple() {
    boolean result = false;

    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;
}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * @param pdfXConformance determines into which format the PDF-X will be converted.
 * @return true if the conversion was successful.
 *//*from   w  ww.j  a va2 s . c om*/
private boolean convertToPDFX(int pdfXConformance) {
    boolean result = false;
    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());
        writer.setPDFXConformance(pdfXConformance);

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

From source file:com.github.ukase.bulk.BulkRenderTask.java

License:Open Source License

private void mergeSubTasksPdfs() {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();// ww  w.j  a va2 s  . com
        PdfContentByte cb = writer.getDirectContent();

        appendPdfs(document, writer, cb);

        document.close();
        pdf = baos.toByteArray();
    } catch (IOException | DocumentException e) {
        log.warn("Cannot bulk pdfs", e);
    } finally {
        registerResult();
    }
}

From source file:com.github.wolfposd.imsqti2pdf.PDFCreator.java

License:Open Source License

public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer,
        PageCounter pagecounter, int maximumPageNumber, String inputFolder)
        throws DocumentException, IOException {
    _inputFolder = inputFolder;//  w ww  .jav  a2 s . c  o  m
    Document document = new Document(PageSize.A4, 50, 50, 70, 50);
    PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));

    pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber));

    if (pagecounter != null) {
        pdfwriter.setPageEvent(pagecounter);
    }

    document.open();

    Paragraph p = new Paragraph();
    // p.setSpacingBefore(SPACING);
    p.setSpacingAfter(SPACING);
    p.setIndentationLeft(INDENTATION);

    writeQuestions(p, document, showCorrectAnswer, qlist);

    document.close();

}

From source file:com.gp.cong.logisoft.lcl.report.LclAllBLPdfCreator.java

public void init(String outputFileName, String realPath, String documentName, String fileId, String printRadio)
        throws Exception {
    this.printdocumentName = "Bill Of Lading";
    document = new Document(PageSize.A4, 18, 3, 30, 355);
    pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(outputFileName));
    LclAllBLPdfCreator.headerFooterEvent event = new LclAllBLPdfCreator.headerFooterEvent();
    pdfWriter.setPageEvent(event);//  ww w  . j  a v  a  2 s .  c  o m
    String[] file = fileId.split(",");
    if (file.length > 0) {
        this.fileId = file[file.length - 1];
        document.open();
        for (LclBlPiece lclBlPiece : lclBlPiecesList) {
            commodity_count++;
            document.add(commodityTab(lclBlPiece));
        }
        if (file.length > 1) {
            for (int i = file.length - 2; i >= 0; i--) {
                page_count = 0;
                commodity_count = 0;
                this.fileId = file[i];
                document.newPage();
                isFirst_page = true;
                for (LclBlPiece lclBlPiece : lclBlPiecesList) {
                    commodity_count++;
                    document.add(commodityTab(lclBlPiece));
                }
            }
        }
        document.close();
    }
}