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:br.com.treg.utils.GeneratorPDF.java

public GeneratorPDF(String valorExtenso, ObraFuncionario of, double valor) {
    //criao do documento
    Document document = new Document();

    try {/*ww  w.  j  ava2s . com*/
        PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Gustavo\\Desktop\\Recibo.pdf"));
        document.open();

        Paragraph preface = new Paragraph();

        addEmptyLine(preface, 1);

        preface.add(new Paragraph("RECIBO", catFont));
        addEmptyLine(preface, 1);

        preface.add(new Paragraph("Valor: R$ " + valor));
        addEmptyLine(preface, 3);

        preface.add(new Paragraph("Recebi da empresa TR&G "));
        addEmptyLine(preface, 1);
        preface.add(new Paragraph("A importncia de " + valorExtenso));
        addEmptyLine(preface, 1);
        preface.add(
                new Paragraph("referente a servios prestados de " + of.getFuncionario().getFuncao() + "."));

        addEmptyLine(preface, 4);

        Calendar data = Calendar.getInstance();
        String mes = NomeDoMes(data.get(Calendar.MONTH), 0);
        int ds = data.get(Calendar.DAY_OF_WEEK);

        preface.add(new Paragraph("Campo Grande, " + data.get(Calendar.DATE) + " de " + mes + " de "
                + data.get(Calendar.YEAR) + " (" + DiaDaSemana(ds, 1) + ")."));
        addEmptyLine(preface, 1);
        preface.add(new Paragraph("Funcionrio: " + of.getFuncionario().getNome() + " - CPF/RG: "
                + of.getFuncionario().getCpf()));
        addEmptyLine(preface, 1);
        preface.add(new Paragraph("Endereo: " + of.getFuncionario().getEndereco()));
        addEmptyLine(preface, 1);
        preface.add(new Paragraph("Assinatura: _____________________________"));

        document.add(preface);
    } catch (DocumentException | IOException de) {
        System.err.println(de.getMessage());
    }
    document.close();

}

From source file:br.edu.unipampa.recipemanager.pdf.CreatePDF.java

public boolean newPdf(List<MenuRecipe> menuRecipe, String month, String responsibleName) {
    double valueMonth = 0;
    try {/*w ww  .j a v a2  s .  c o  m*/
        Document doc = new Document(PageSize.A4, 72, 72, 72, 72);
        OutputStream os = new FileOutputStream(namePdf(menuRecipe));
        PdfWriter.getInstance(doc, os);

        doc.open();
        Paragraph p;
        Font f = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);

        p = new Paragraph("Ms: " + month, f);
        doc.add(p);

        f = new Font(Font.FontFamily.COURIER, 14, Font.ITALIC);

        for (MenuRecipe menu : menuRecipe) {
            valueMonth += menu.priceMenu();
            p.setSpacingBefore(5);
            p.setSpacingAfter(5);
            p = new Paragraph(menu.toString(), f);
            doc.add(p);
        }

        p = new Paragraph("Preo total de todos os cardpios: " + valueMonth, f);
        doc.add(p);

        f = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        p = new Paragraph("_____________________________________\n" + responsibleName, f);
        p.setSpacingAfter(15);
        p.setAlignment(Element.ALIGN_RIGHT);
        doc.add(p);

        doc.close();
        os.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:br.jus.jfpr.Divisor1.java

/**
 * Divide um arquivo inicialmente em 2, testa se o tamanho que todos
 * arquivos ficaram dentro do limite, se no ficaram apaga tudo e recomea
 * dividindo por, 3, 4, 5, etc. at que todos arquivo fiquem dentro do
 * limite//  www .ja v a2  s  .  c  o  m
 *
 * @param arquivoEntrada O arquivo que ser dividido
 * @param arquivoSaida O nome do arquivo que ser criado
 * @param tamArqSel Tamanho selecionado que devero ficar os arquivos
 * divididos
 * @return String informativa do resultado
 */
public static String dividePDF(File arquivoEntrada, String arquivoSaida, int tamArqSel) {

    int daPagina = 1;
    int paraPagina;
    int tamInicial;
    // FileOutputStream arquivoSair = null;
    String MensagemErro = "ok";
    int fatorDivisao = 2; //Incialmente dividir em 2
    arquivoSaida = arquivoSaida.substring(0, arquivoSaida.indexOf('.')) + "-divido"; //PAra definir o nome do arquivo de sada

    try {
        PdfReader PdfDeEntrada = new PdfReader(arquivoEntrada.getAbsolutePath()); //Para ler o arquivo de entrada
        final int totalPaginas = PdfDeEntrada.getNumberOfPages(); //Verifica o total de pginas
        tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Define o tamanho (em pginas) do 1 arquivo e em quanto dever incrementar(sero o mesmo)
        PdfImportedPage pagina;

        int i = 1; //Contador simples
        while (i <= fatorDivisao && totalPaginas > fatorDivisao) { //Enquanto no fizer todas as divises
            Document documento = new Document();
            FileOutputStream arquivoSair = new FileOutputStream(arquivoSaida + "-" + i + ".pdf"); //Cria o arquivo, vazio
            PdfWriter writer = PdfWriter.getInstance(documento, arquivoSair); //
            documento.open();
            PdfContentByte PContentByte = writer.getDirectContent();
            while (daPagina <= paraPagina) {
                documento.newPage(); //Aloca uma nova pginA
                pagina = writer.getImportedPage(PdfDeEntrada, daPagina); //Seleciona uma pgina especfica. indicada pelo contador
                PContentByte.addTemplate(pagina, 0, 0); //Adiciona a pagina ao contedo
                daPagina++; //Contador simples
            }
            arquivoSair.flush();
            documento.close(); //Grava o arquivo de sada
            arquivoSair.close();
            File arquivoDest = new File(arquivoSaida + "-" + i + ".pdf");
            if (arquivoDest.length() > tamArqSel) { // O tamanho do arquivo de destino ficou maior do que deveria
                delete(arquivoSaida, i); //Chamar a funo para deletar todos arquivos at a chave i
                daPagina = i = 1; //Para recomear tudo de novo
                fatorDivisao++; //Se um arquivo ficou maior, ento deve aumentar a diviso
                tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Para recomear tudo de novo
            } else {
                i++; //Continua a divisao
                if (i == fatorDivisao) { //Ou seja, chegou a ultima divisao
                    paraPagina = totalPaginas; //O ultimo arquivo conter mais pginas
                } else {
                    paraPagina += tamInicial; //Cada arquivo ter o mesmo nmero de pginas//Incrementa sempre o tamanho inicial
                }
            }
        }
    } catch (IOException | DocumentException e) {
        System.err.println(e.getMessage());
        MensagemErro = e.getMessage();
    }
    return MensagemErro;
}

From source file:br.miltecnologias.estagio.teste.Principal.java

public void gerarPDF() throws DocumentException, FileNotFoundException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("E:\\Relatorio_Prefeitura.pdf"));
    document.open();/*from w  w w  .ja  v a 2s . c o  m*/

    for (int i = 0; i < parags.size(); i++) {
        document.add(parags.get(i));
    }

    document.close();
}

From source file:br.unifor.mia.xmpsemantico.xmp.MetadataXmp.java

License:GNU General Public License

/**
 * create PDF document/*  w w  w .j  a  va  2s  .  c  om*/
 * @param filename of new archive PDF
 * @throws DocumentException 
 * @throws IOException 
 */
public void createPdf() throws IOException {

    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(pathPdf));

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XmpWriter xmp = new XmpWriter(os);

        MiaSchema miaSchema = new MiaSchema();
        miaSchema.addDescription(this.descricao);
        miaSchema.setProperty(MiaSchema.DISCIPLINA, this.disciplina);
        miaSchema.setProperty(MiaSchema.PROFESSOR, this.professor);
        miaSchema.setProperty(MiaSchema.CARGA_HORARIA, this.cargaHoraria);
        miaSchema.setProperty(MiaSchema.CREDITOS, this.creditos);
        xmp.addRdfDescription(miaSchema);

        xmp.close();
        writer.setXmpMetadata(os.toByteArray());

        document.open();
        document.addAuthor("docsemantico");
        Paragraph paragraph = new Paragraph("Quick brown ");
        Anchor foxRefence = new Anchor("fox");
        foxRefence.setReference("#fox");
        paragraph.add(foxRefence);
        paragraph.add(" jumps over the lazy dog.");
        document.add(paragraph);
        document.newPage();
        Anchor foxName = new Anchor("This is the FOX");
        foxName.setName("fox");
        document.add(foxName);
        document.add(new Paragraph(this.texto));

        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    //teste commit
}

From source file:br.unisc.video_locadora.controll.Generator_PDF.java

public void geraRelatorio() throws DocumentException, FileNotFoundException {
    // Cria um novo documento com tamanho e margens definidas pelo usurio
    // new Document(tamanho da pgina, margem esquerda, margem direita,
    // margem topo, margem rodap);
    Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
    try {//from  w ww.j  a  v  a 2 s  .  c  o  m

        JFileChooser jFileChooser = new JFileChooser();

        //seta para selecionar apenas arquivos
        jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        //desabilita todos os tipos de arquivos
        jFileChooser.setAcceptAllFileFilterUsed(false);

        //filtra por extensao
        jFileChooser.setFileFilter(new FileFilter() {
            @Override
            public String getDescription() {
                return "Extenso PDF";
            }

            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith("pdf");
            }
        });

        //mostra janela para salvar
        int acao = jFileChooser.showSaveDialog(null);

        //executa acao conforme opcao selecionada
        if (acao == JFileChooser.APPROVE_OPTION) {
            //escolheu arquivo
            System.out.println(jFileChooser.getSelectedFile().getAbsolutePath());
            PdfWriter.getInstance(doc,
                    new FileOutputStream(jFileChooser.getSelectedFile().getAbsolutePath() + ".pdf"));
            doc.open();

            listaF = f.buscaFilme("");

            // Definindo uma fonte, com tamanho 20 e negrito
            Font f = new Font(Font.FontFamily.COURIER, 30, Font.BOLD);
            Font f2 = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);

            // adicionando um pargrafo ao documento com a fonte acima
            Paragraph pa = new Paragraph("Relatrio", f);
            // Setando o alinhamento p/ o centro
            pa.setAlignment(Paragraph.ALIGN_CENTER);

            // Definindo
            pa.setSpacingAfter(50);
            doc.add(pa);

            //doc.add(new Paragraph(" "));

            // Criando uma tabela com 4 colunas
            PdfPTable table = new PdfPTable(7);
            // Ttulo para a tabela
            Paragraph tableHeader = new Paragraph("Todos os Ttulos", f2);

            PdfPCell header = new PdfPCell(tableHeader);
            // Definindo que o header vai ocupar as 4 colunas
            header.setColspan(7);
            // Definindo alinhamento do header
            header.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
            // Adicionando o header  tabela
            table.addCell(header);

            List<String> list = new ArrayList<>();
            list.add("Id");
            list.add("Ttulo");
            list.add("Ano");
            list.add("Diretor");
            list.add("Gnero");
            list.add("Linguagem");
            list.add("Locado");
            for (Filmes p : listaF) {
                list.add(String.valueOf(p.getId()));
                list.add(p.getTitulo());
                list.add(String.valueOf(p.getAno()));
                list.add(p.getDiretor());
                list.add(p.getGenero());
                list.add(p.getIdioma());
                list.add(p.getLocado());
            }

            for (String s : list) {
                table.addCell(s);
            }

            doc.add(table);

            /* doc.add(new Paragraph(" ID | Nome | Idade | Cidade"));
            for (Pessoa p : lista) {
                doc.add(new Paragraph(p.getId() + " |  " + p.getNome() + "  |  " + p.getIdade() + "  |  " + p.getCidade()));
            }*/
        }
    } catch (FileNotFoundException | DocumentException e) {
        System.err.println(e.getMessage());
    }
    doc.close();
}

From source file:braliie.CODIGO.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    JFileChooser Seleccionar_Archivo;
    Seleccionar_Archivo = new JFileChooser();
    int opcion = Seleccionar_Archivo.showSaveDialog(null);
    if (opcion == JFileChooser.APPROVE_OPTION) {
        try {/*from w  w w .  j  a v  a  2  s . c  om*/
            File f;
            String cad = "";
            f = new File(Seleccionar_Archivo.getSelectedFile() + ".PDF");
            //Escritura
            try {
                try (OutputStream Texto_Salida = new FileOutputStream(
                        Seleccionar_Archivo.getSelectedFile() + ".pdf")) {
                    com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
                    PdfWriter.getInstance(doc, Texto_Salida);
                    doc.open();
                    com.itextpdf.text.Image imagen2 = com.itextpdf.text.Image.getInstance("src/img/UAEM.png");
                    doc.add(imagen2);
                    doc.add(new Paragraph(
                            "\\\\\\\\\\\\\\\\\\\\\\\\=============================================================///////////////"));
                    doc.add(new Paragraph("CDIGO BRAILLE" + "\n \nPALABRA:" + "\n" + jTextField1.getText()));

                    doc.add(new Paragraph(
                            "\\\\\\\\\\\\\\\\\\\\\\\\=============================================================///////////////"));
                    doc.close();
                }
            } catch (IOException e) {

                System.out.println(e);
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea Abrir el documento", "Alerta!",
                JOptionPane.YES_NO_OPTION);
        if (respuesta == YES_NO_OPTION) {
            try {
                File path = new File(Seleccionar_Archivo.getSelectedFile() + ".PDF");
                Desktop.getDesktop().open(path);
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
    }

    // TODO add your handling code here:
}

From source file:bsf.conn.DBMS.java

public static void pdfConvertor(javax.swing.JTable table, String path) {
    try {/*  w w w  . j a v a 2  s .  com*/
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        addTitlePage(document);
        addContent(document);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:BUS.ExportPDF.java

public boolean ExportPN(ArrayList<String[]> al) throws BadElementException, IOException, DocumentException {

    // To i tng ti liu
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    File fontFile = new File("src\\Helper\\arialuni.ttf");
    BaseFont unicode = BaseFont.createFont(fontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font f = new Font(unicode, 12);

    try {//w  ww  .ja  va2s . c  o m
        // To i tng PdfWriter
        Date d = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");

        String s = "PhieuNhap_" + ft.format(d) + ".pdf";
        PdfWriter.getInstance(document, new FileOutputStream(s));

        // M file  thc hin ghi
        document.open();

        Paragraph title1 = new Paragraph("CO's BAKERY", FontFactory.getFont(FontFactory.HELVETICA, 18,
                Font.BOLDITALIC, new CMYKColor(0, 255, 255, 17)));
        document.add(title1);

        //Logo Group
        Image image1 = Image.getInstance("src\\Library\\cao.png");
        document.add(new Paragraph());
        document.add(image1);

        //Data

        PdfPTable t = new PdfPTable(7);
        t.setSpacingBefore(25);
        t.setSpacingAfter(25);

        PdfPCell c1 = new PdfPCell(new Phrase("STT"));
        t.addCell(c1);
        PdfPCell c2 = new PdfPCell(new Phrase("M phiu nhp", f));
        t.addCell(c2);
        PdfPCell c3 = new PdfPCell(new Phrase("M Nhn Vin", f));
        t.addCell(c3);
        PdfPCell c4 = new PdfPCell(new Phrase("Tn Nhn Vin", f));
        t.addCell(c4);
        PdfPCell c5 = new PdfPCell(new Phrase("Ngy lp", f));
        t.addCell(c5);
        PdfPCell c6 = new PdfPCell(new Phrase("Nh cung cp", f));
        t.addCell(c6);
        PdfPCell c7 = new PdfPCell(new Phrase("Tng ti?n", f));
        t.addCell(c7);

        for (int i = 0; i < al.size(); i++) {
            Object ob = i + 1;
            t.addCell(ob.toString());
            t.addCell(al.get(i)[0]);
            t.addCell(al.get(i)[1]);
            t.addCell(new Phrase(al.get(i)[2], f));
            t.addCell(al.get(i)[3]);
            t.addCell(new Phrase(al.get(i)[4], f));
            t.addCell(al.get(i)[5]);
        }
        document.add(t);
        // ?ng File
        document.close();
    } catch (FileNotFoundException | DocumentException e) {
        return false;
    }
    return true;
}

From source file:BUS.ExportPDF.java

public boolean ExportPX(ArrayList<String[]> al) throws BadElementException, IOException, DocumentException {

    // To i tng ti liu
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    File fontFile = new File("src\\Helper\\arialuni.ttf");
    BaseFont unicode = BaseFont.createFont(fontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font f = new Font(unicode, 12);

    try {//  w w  w  .  j a va2  s.  c o  m
        // To i tng PdfWriter
        Date d = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");

        String s = "PhieuXuat_" + ft.format(d) + ".pdf";
        PdfWriter.getInstance(document, new FileOutputStream(s));

        // M file  thc hin ghi
        document.open();

        Paragraph title1 = new Paragraph("CO's BAKERY", FontFactory.getFont(FontFactory.HELVETICA, 18,
                Font.BOLDITALIC, new CMYKColor(0, 255, 255, 17)));
        document.add(title1);

        //Logo Group
        Image image1 = Image.getInstance("src\\Library\\cao.png");
        document.add(new Paragraph());
        document.add(image1);

        //Data
        PdfPTable t = new PdfPTable(5);
        t.setSpacingBefore(25);
        t.setSpacingAfter(25);

        PdfPCell c1 = new PdfPCell(new Phrase("STT"));
        t.addCell(c1);
        PdfPCell c2 = new PdfPCell(new Phrase("M phiu xut", f));
        t.addCell(c2);
        PdfPCell c3 = new PdfPCell(new Phrase("M Nhn Vin", f));
        t.addCell(c3);
        PdfPCell c4 = new PdfPCell(new Phrase("Tn Nhn Vin", f));
        t.addCell(c4);
        PdfPCell c5 = new PdfPCell(new Phrase("Ngy lp", f));
        t.addCell(c5);

        for (int i = 0; i < al.size(); i++) {
            Object ob = i + 1;
            t.addCell(ob.toString());
            t.addCell(al.get(i)[0]);
            t.addCell(al.get(i)[1]);
            t.addCell(new Phrase(al.get(i)[2], f));
            t.addCell(al.get(i)[3]);
        }
        document.add(t);

        // ?ng File
        document.close();
    } catch (FileNotFoundException | DocumentException e) {
        return false;
    }
    return true;
}