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

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

Introduction

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

Prototype


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

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:fr.opensagres.xdocreport.itext.extension.TableWithAlignment.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {/*from w ww  . ja v  a 2 s . c om*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TableWithAlignment.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);

        table.setWidths(new float[] { 5, 10 });
        table.setWidthPercentage(10);

        PdfPCell cell1 = new PdfPCell();
        cell1.addElement(new Chunk("cell1"));
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell();
        cell2.addElement(new Chunk("cell2"));
        table.addCell(cell2);

        table.setSpacingBefore(-100);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.opensagres.xdocreport.itext.extension.TableWithVerticalAlignment.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {// w  w  w.ja v a2s.c o  m
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream("TableWithVerticalAlignment.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(1);
        // PdfPCell cell1 = new PdfPCell();
        // cell1.setVerticalAlignment( Element.ALIGN_BOTTOM );
        // //cell1.setMinimumHeight( 100f );
        // cell1.addElement( new Chunk( "cell1" ) );
        // table.addCell( cell1 );

        PdfPCell cell2 = new PdfPCell();
        Paragraph p = new Paragraph();
        p.add(new Chunk("cellp&"));

        cell2.addElement(p);
        cell2.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell2.setMinimumHeight(38f);
        table.addCell(cell2);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.paris.lutece.plugins.directory.modules.pdfproducer.utils.PDFUtils.java

License:Open Source License

/**
 * method to create PDF/*from ww w.ja  v  a  2s  . co  m*/
 * @param adminUser The admin user
 * @param locale The locale
 * @param strNameFile PDF name
 * @param out OutputStream
 * @param nIdRecord the id record
 * @param listIdEntryConfig list of config id entry
 * @param bExtractNotFilledField if true, extract empty fields, false
 */
public static void doCreateDocumentPDF(AdminUser adminUser, Locale locale, String strNameFile, OutputStream out,
        int nIdRecord, List<Integer> listIdEntryConfig, Boolean bExtractNotFilledField) {
    Document document = new Document(PageSize.A4);

    Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);

    EntryFilter filter;

    Record record = RecordHome.findByPrimaryKey(nIdRecord, plugin);

    filter = new EntryFilter();
    filter.setIdDirectory(record.getDirectory().getIdDirectory());
    filter.setIsGroup(EntryFilter.FILTER_TRUE);

    List<IEntry> listEntry = DirectoryUtils.getFormEntries(record.getDirectory().getIdDirectory(), plugin,
            adminUser);
    int nIdDirectory = record.getDirectory().getIdDirectory();
    Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, plugin);

    try {
        PdfWriter.getInstance(document, out);
    } catch (DocumentException e) {
        AppLogService.error(e);
    }

    document.open();

    if (record.getDateCreation() != null) {
        SimpleDateFormat monthDayYearformatter = new SimpleDateFormat(
                AppPropertiesService.getProperty(PROPERTY_POLICE_FORMAT_DATE));

        Font fontDate = new Font(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_DATE)),
                DirectoryUtils
                        .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_DATE)));

        Paragraph paragraphDate = new Paragraph(
                new Phrase(monthDayYearformatter.format(record.getDateCreation()).toString(), fontDate));

        paragraphDate.setAlignment(DirectoryUtils
                .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_ALIGN_DATE)));

        try {
            document.add(paragraphDate);
        } catch (DocumentException e) {
            AppLogService.error(e);
        }
    }

    Image image;

    try {

        image = Image.getInstance(ImageIO.read(new File(AppPathService
                .getAbsolutePathFromRelativePath(AppPropertiesService.getProperty(PROPERTY_IMAGE_URL)))), null);
        image.setAlignment(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_IMAGE_ALIGN)));
        float fitWidth;
        float fitHeight;

        try {
            fitWidth = Float.parseFloat(AppPropertiesService.getProperty(PROPERTY_IMAGE_FITWIDTH));
            fitHeight = Float.parseFloat(AppPropertiesService.getProperty(PROPERTY_IMAGE_FITHEIGHT));
        } catch (NumberFormatException e) {
            fitWidth = 100f;
            fitHeight = 100f;
        }

        image.scaleToFit(fitWidth, fitHeight);

        try {
            document.add(image);
        } catch (DocumentException e) {
            AppLogService.error(e);
        }
    } catch (BadElementException e) {
        AppLogService.error(e);
    } catch (MalformedURLException e) {
        AppLogService.error(e);
    } catch (IOException e) {
        AppLogService.error(e);
    }

    directory.getTitle();

    Font fontTitle = new Font(
            DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_TITLE_DIRECTORY)),
            DirectoryUtils.convertStringToInt(
                    AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_TITLE_DIRECTORY)));
    fontTitle.isUnderlined();

    Paragraph paragraphHeader = new Paragraph(new Phrase(directory.getTitle(), fontTitle));
    paragraphHeader.setAlignment(Element.ALIGN_CENTER);
    paragraphHeader.setSpacingBefore(DirectoryUtils.convertStringToInt(
            AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_BEFORE_TITLE_DIRECTORY)));
    paragraphHeader.setSpacingAfter(DirectoryUtils.convertStringToInt(
            AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_AFTER_TITLE_DIRECTORY)));

    try {
        document.add(paragraphHeader);
    } catch (DocumentException e) {
        AppLogService.error(e);
    }

    builderPDFWithEntry(document, plugin, nIdRecord, listEntry, listIdEntryConfig, locale,
            bExtractNotFilledField);
    document.close();
}

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * /*  www.ja  va 2  s.c  o  m*/
 * @return le fichier pdf du calendrier des examens.
 */
public com.vaadin.server.Resource exportPdf() {

    String nomFichier = applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";

    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                creerPdfCalendrier(document, MainUI.getCurrent().getEtudiant());
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du calendrier des examens : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du calendrier des examens : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;

}

From source file:fr.univlorraine.mondossierweb.controllers.InscriptionController.java

License:Apache License

/**
 * //from  www.ja va2  s  . c om
 * @return le fichier pdf.
 */
public com.vaadin.server.Resource exportPdf(Inscription inscription) {

    // verifie les autorisations
    if (!etudiantController.proposerCertificat(inscription, MainUI.getCurrent().getEtudiant())) {
        return null;
    }

    String nomFichier = applicationContext.getMessage("pdf.certificat.title", null, Locale.getDefault()) + "_"
            + inscription.getCod_etp() + "_" + inscription.getCod_anu().replace('/', '-') + "_"
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument();
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                creerPdfCertificatScolarite(document, MainUI.getCurrent().getEtudiant(), inscription);
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du certificat : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du certificat : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:fr.univlorraine.mondossierweb.controllers.ListeInscritsController.java

License:Apache License

/**
 * Retourne le trombinoscope en pdf/*from  w  w w  .  java2s. c o m*/
 * @param linscrits
 * @param listecodind
 * @return
 */
public InputStream getPdfStream(List<Inscrit> linscrits, List<String> listecodind, String libObj,
        String annee) {

    LOG.debug("generation pdf : " + libObj + " " + annee + " " + linscrits.size() + " " + listecodind.size());
    try {
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
        PdfWriter docWriter = null;
        Document document = configureDocument(MARGE_PDF);
        docWriter = PdfWriter.getInstance(document, baosPDF);
        docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
        docWriter.setStrictImageSequence(true);
        creerPdfTrombinoscope(document, linscrits, listecodind, libObj, annee);
        docWriter.close();
        baosPDF.close();
        //Creation de l'export
        byte[] bytes = baosPDF.toByteArray();
        return new ByteArrayInputStream(bytes);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du trombinoscope : DocumentException ", e);
        return null;
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du trombinoscope : IOException ", e);
        return null;
    }

}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /* w ww.  java2s  .  c  o  m*/
 * @return le fichier pdf du rsum des notes.
 */
public com.vaadin.server.Resource exportPdfResume() {

    String nomFichier = applicationContext.getMessage("pdf.notes.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                if (configController.isInsertionFiligranePdfNotes()) {
                    docWriter.setPageEvent(new Watermark());
                }
                creerPdfResume(document, MainUI.getCurrent().getEtudiant());
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du rsum des notes : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du rsum des notes : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /*from  w  w w.  j  a  va  2 s.co  m*/
 * @return le fichier pdf du detail des notes.
 */
public com.vaadin.server.Resource exportPdfDetail(Etape etape) {

    String nomFichier = applicationContext.getMessage("pdf.detail.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                if (configController.isInsertionFiligranePdfNotes()) {
                    docWriter.setPageEvent(new Watermark());
                }
                creerPdfDetail(document, MainUI.getCurrent().getEtudiant(), etape);
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du dtail des notes : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du dtail des notes : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.getStream().setParameter("Content-Disposition", "attachment; filename=" + nomFichier);
    //resource.setMIMEType("application/unknow");
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:geoportal.presentacion.beans.ReportesControlador.java

public void imprimirReporte() {
    //DateFormat dfDateFull = DateFormat.getDateInstance(DateFormat.FULL);
    try {//from w  w  w .  j a  v  a 2  s. c om

        //Generamos el archivo PDF
        String directorioArchivos;
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        directorioArchivos = ctx.getRealPath("/") + "reportes";
        String name = directorioArchivos + "/document-reporte.pdf";
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(name));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
        //PdfWriter writer = PdfWriter.getInstance(document,
        //new FileOutputStream("C:"));

        Paragraph paragraph = new Paragraph();
        Paragraph paragraph1 = new Paragraph();
        Paragraph paragraph2 = new Paragraph();

        //PdfPTable table = new PdfPTable(4);
        PdfPTable table1 = new PdfPTable(1);
        PdfPTable table2 = new PdfPTable(4);
        PdfPTable table3 = new PdfPTable(4);
        PdfPTable table5 = new PdfPTable(1);

        paragraph.add("\n\n\n\n\n\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph1.add("\n");
        paragraph1.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph2.add("Total Denuncias:" + totalDenuncias);
        paragraph2.setAlignment(Paragraph.ALIGN_LEFT);

        //  Obtenemos una instancia de nuestro manejador de eventos
        MembreteHeaderiText header = new MembreteHeaderiText();
        //Asignamos el manejador de eventos al escritor.
        writer.setPageEvent(header);

        document.open();
        //            Chunk titulo = new Chunk(CHUNK, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
        //
        //            titulo = new Chunk(IMAGE, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
        //            document.add(titulo);
        //            Image foto = Image.getInstance(resources / ferrari.jpg?);
        //foto.scaleToFit(100, 100);        foto.setAlignment(Chunk.ALIGN_MIDDLE);

        //primera linea   
        PdfPCell cell5 = new PdfPCell(new Paragraph("VIOLENCIA INTRAFAMILIAR "));
        //segunda linea
        PdfPCell cell12 = new PdfPCell(new Paragraph("AO"));
        PdfPCell cell6 = new PdfPCell(new Paragraph("2010"));
        PdfPCell cell7 = new PdfPCell(new Paragraph("2011"));
        PdfPCell cell8 = new PdfPCell(new Paragraph("2012"));

        //tercera fila
        PdfPCell cell13 = new PdfPCell(new Paragraph("# DENUNCIAS"));
        PdfPCell cell9 = new PdfPCell(new Paragraph("" + lstVif2010.size()));
        PdfPCell cell10 = new PdfPCell(new Paragraph("" + lstVif2011.size()));
        PdfPCell cell11 = new PdfPCell(new Paragraph("" + lstVif_2012.size()));

        PdfPCell cell15 = new PdfPCell(new Paragraph("TOTAL DENUNCIAS:" + totalDenuncias));

        cell5.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell15.setHorizontalAlignment(Element.ALIGN_LEFT);

        cell12.setBackgroundColor(Color.cyan);
        cell13.setBackgroundColor(Color.cyan);

        cell5.setBorder(Rectangle.NO_BORDER);
        cell15.setBorder(Rectangle.NO_BORDER);

        table1.addCell(cell5);
        //aadir segunda fila
        table2.addCell(cell12);
        table2.addCell(cell6);
        table2.addCell(cell7);
        table2.addCell(cell8);
        //aadir tercera fila
        table3.addCell(cell13);
        table3.addCell(cell9);
        table3.addCell(cell10);
        table3.addCell(cell11);
        //aadir cuarta fila
        table5.addCell(cell15);

        document.add(paragraph);
        document.add(table1);
        document.add(paragraph1);
        document.add(table2);
        document.add(table3);
        document.add(table5);
        //document.add(paragraph2);

        //document.add(table);
        //document.setFooter(event);
        document.close();
        //----------------------------
        //Abrimos el archivo PDF
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline=filename=" + name);
        try {
            response.getOutputStream().write(Util.getBytesFromFile(new File(name)));
            response.getOutputStream().flush();
            response.getOutputStream().close();
            context.responseComplete();

        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:gerarpdf.GerarPdf.java

private void btnGeraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGeraActionPerformed
    // Instanciando o document
    Document documento = new Document();
    try {/*from  www  . ja v  a 2s . c  om*/
        PdfWriter.getInstance(documento, new FileOutputStream("documento.pdf"));

        if (jtxt_area == null || jtxt_area.getText().toString().isEmpty()) {

        }
        documento.open();
        //documento.add(new Paragraph("aLO ALOA AMOANOANIANINO"));
        documento.add(new Paragraph(jtxt_area.getText()));

    } catch (DocumentException | FileNotFoundException ex) {
        System.err.println("Erro ao carregar arquivo");
    } finally {
        documento.close();
    }
    try {
        Desktop.getDesktop().open(new File("documento.pdf"));
    } catch (IOException ex) {
        Logger.getLogger(GerarPdf.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("Erro ao carregar arquivo " + ex);
    }
}