Example usage for com.itextpdf.text Document open

List of usage examples for com.itextpdf.text Document open

Introduction

In this page you can find the example usage for com.itextpdf.text Document open.

Prototype

boolean open

To view the source code for com.itextpdf.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

From source file:BUS.ExportPDF.java

public boolean ExportTKSP(ArrayList<String[]> al, String year)
        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 {/*from   w ww .j  a  v  a  2s .co m*/
        // To i tng PdfWriter
        Date d = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");

        String s = "ThongKeSanPham_" + 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);

        //Nm c bo co
        Paragraph title2 = new Paragraph(year, FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLDITALIC,
                new CMYKColor(0, 255, 255, 17)));
        document.add(title2);

        //Chart
        Image image = Image.getInstance("src\\Library\\pie_Chart3D.jpeg");
        image.scaleToFit(500, 400);
        document.add(new Paragraph());
        document.add(image);

        //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 sn phm", f));
        t.addCell(c2);
        PdfPCell c3 = new PdfPCell(new Phrase("Tn sn phm", f));
        t.addCell(c3);
        PdfPCell c4 = new PdfPCell(new Phrase("Tng s lng", f));
        t.addCell(c4);
        PdfPCell c5 = new PdfPCell(new Phrase("Tng ti?n", 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(new Phrase(al.get(i)[1], f));
            t.addCell(al.get(i)[2]);
            t.addCell(al.get(i)[3]);
        }
        document.add(t);

        // ?ng File
        document.close();
        System.out.println("Write file succes!");
    } catch (FileNotFoundException | DocumentException e) {
        return false;
    }
    return true;
}

From source file:Business.PDFMaker.java

public PDFMaker(String filename, TicketMap tm, int pr1, int pr2, int pr3) {
    Document doc = new Document();
    try {/*from  w ww  .ja  v a 2  s  . c o  m*/
        PdfWriter.getInstance(doc, new FileOutputStream(filename));
        doc.open();
        doc.add(new Phrase("Cabaz de Natal, Cl Schindler"));
        doc.add(new Paragraph("As seguintes Rifas foram vendidas:"));
        doc.add(new Paragraph("\n"));
        PdfPTable table = new PdfPTable(5);
        for (Ticket t : tm.getFullTickets()) {

            PdfPCell cell = new PdfPCell(new Paragraph(t.getId() + "-" + t.getName()));
            table.addCell(cell);
        }
        doc.add(table);
        doc.add(new Chapter("Vencedores deste ano:", 1));
        doc.add(new Paragraph("1 Prmio. " + tm.getTicket(pr1)));
        doc.add(new Paragraph("2 Prmio. " + tm.getTicket(pr2)));
        doc.add(new Paragraph("3 Prmio. " + tm.getTicket(pr3)));
        doc.close();
    } catch (Exception e) {

    }
}

From source file:BusinessLogic.Controller.HandleCertificate.java

public void downloadCertificate(ContractDAO contrDAO, CertificateDAO certificateDAO, UserDAO usDAO,
        HttpServletResponse response, int idUser, int option) throws DocumentException, IOException {
    User user = usDAO.searchByPkID(idUser);
    List<Certificate> certificateObject = certificateDAO.searchUserAproved();
    List<Certificate> certificateReturn = new ArrayList<Certificate>();
    if (certificateObject != null) {
        certificateReturn.clear();//from  ww  w  . j  av  a 2 s . c o  m
        for (int i = 0; i < certificateObject.size(); i++) {
            if (certificateObject.get(i).getFkuserID().getPkID().equals(user.getPkID())) {
                certificateReturn.add(certificateObject.get(i));
            }
        }
    }
    Contract contractObject = contrDAO.getUserContract(new User(user.getPkID()));
    Certificate cert = certificateReturn.get(option);
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);
    document.open();
    Font fuente = new Font();
    fuente.setStyle(Font.BOLD);
    fuente.setColor(BaseColor.BLACK);
    fuente.setFamily(Font.FontFamily.TIMES_ROMAN.toString());
    fuente.setSize(15);
    Paragraph header = new Paragraph("\n\n\n\n\nEL DEPARTAMENTO DE GESTION HUMANA\n"
            + "DE TALENTO-HUMANO LTDA\n\n\n\n\n" + "CERTIFICA QUE:\n\n\n\n\n", fuente);
    header.setAlignment(Element.ALIGN_CENTER);
    Calendar fecha = new GregorianCalendar();
    int annio = fecha.get(Calendar.YEAR);
    int mes = fecha.get(Calendar.MONTH) + 1;
    int dia = fecha.get(Calendar.DAY_OF_MONTH);
    Paragraph endtext = new Paragraph("\n\nSe expide la presente certificacion a solicitud"
            + " del interesado a la fecha de : " + dia + "/" + mes + "/" + annio
            + "\n\n\nCordialmente\n\n\nEdwin Alexander Bohorquez\nGERENTE GENERAL DE TALENTO-HUMANO LTDA");
    endtext.setAlignment(Element.ALIGN_LEFT);
    String typeCertificate = "";
    if (cert.getType().toLowerCase().equals("laboral")) {
        typeCertificate = "Laboral";
        document.add(header);
        List<String> positionlist = new ArrayList<String>();
        for (Position cargo : contractObject.getPositionSet()) {
            positionlist.add(cargo.getName());
        }
        Paragraph body = new Paragraph(user.getName().toUpperCase() + " " + user.getLastname().toUpperCase()
                + " con cedula de ciudadania No." + user.getIdentifyCard() + ", trabaja en esta empresa"
                + " desde " + contractObject.getStartDate() + ", desempeandose actualmente como "
                + positionlist + " con una asignacion mensual de $" + contractObject.getSalary()
                + ".Su contrato de trabajo es a termino " + contractObject.getType() + ".");
        body.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
        document.add(body);
        document.add(endtext);
    } else if (cert.getType().toLowerCase().equals("nmina")) {
        typeCertificate = "Nomina";
        Paragraph Payroll_header = new Paragraph("DEPARTAMENTO DE CONTABILIDAD\n" + "TALENTO-HUMANO LTDA\n\n"
                + "LIQUIDACION DE NOMINA:\n" + "Nombre del empleado : " + user.getName() + " "
                + user.getLastname() + "\n" + "Cedula : " + user.getIdentifyCard() + "\n\n", fuente);
        Payroll_header.setAlignment(Element.ALIGN_CENTER);
        document.add(Payroll_header);
        double commissions = 10000;
        double extra_hours = 50000;
        double transportation_aid = 63600;
        double totalAccrued = contractObject.getSalary() + commissions + extra_hours + transportation_aid;

        PdfPTable basetable = new PdfPTable(2);
        PdfPCell headertable = new PdfPCell(new Paragraph("Tabla Base", fuente));
        headertable.setColspan(2);
        basetable.addCell(headertable);
        PdfPCell cell1 = new PdfPCell(new Paragraph("Salario Basico : "));
        PdfPCell cell2 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary())));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Comisiones : "));
        PdfPCell cell4 = new PdfPCell(new Paragraph(String.valueOf(commissions)));
        PdfPCell cell5 = new PdfPCell(new Paragraph("Horas Extras : "));
        PdfPCell cell6 = new PdfPCell(new Paragraph(String.valueOf(extra_hours)));
        PdfPCell cell7 = new PdfPCell(new Paragraph("Auxilio de transporte : "));
        PdfPCell cell8 = new PdfPCell(new Paragraph(String.valueOf(transportation_aid)));
        PdfPCell ce9 = new PdfPCell(new Paragraph("Total Devengado : "));
        PdfPCell ce10 = new PdfPCell(new Paragraph(" $ " + String.valueOf(totalAccrued)));
        basetable.setWidthPercentage(100F);
        basetable.setHorizontalAlignment(Element.ALIGN_CENTER);
        basetable.addCell(cell1);
        basetable.addCell(cell2);
        basetable.addCell(cell3);
        basetable.addCell(cell4);
        basetable.addCell(cell5);
        basetable.addCell(cell6);
        basetable.addCell(cell7);
        basetable.addCell(cell8);
        basetable.addCell(ce9);
        basetable.addCell(ce10);
        document.add(basetable);

        PdfPTable tableliquidation = new PdfPTable(2);
        PdfPCell title = new PdfPCell(
                new Paragraph("Liquidacion. Deducciones de nomina(Conceptos a cargo del empleado) ", fuente));
        title.setColspan(2);
        tableliquidation.addCell(title);
        PdfPCell cell9 = new PdfPCell(new Paragraph("Salud (4%) : "));
        PdfPCell cell10 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.04)));
        PdfPCell cell11 = new PdfPCell(new Paragraph("Pension (4%) : "));
        PdfPCell cell12 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.04)));

        tableliquidation.setWidthPercentage(100F);
        tableliquidation.setHorizontalAlignment(Element.ALIGN_CENTER);
        tableliquidation.addCell(cell9);
        tableliquidation.addCell(cell10);
        tableliquidation.addCell(cell11);
        tableliquidation.addCell(cell12);
        document.add(tableliquidation);

        PdfPTable tablesocialSecurity = new PdfPTable(2);
        PdfPCell title2 = new PdfPCell(new Paragraph("Seguridad Social a cargo del empleador", fuente));
        title2.setColspan(2);
        tablesocialSecurity.addCell(title2);
        PdfPCell cell13 = new PdfPCell(new Paragraph("Salud (8.5%) : "));
        PdfPCell cell14 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.085)));
        PdfPCell cell15 = new PdfPCell(new Paragraph("Pension (12%) : "));
        PdfPCell cell16 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.12)));
        PdfPCell cell17 = new PdfPCell(new Paragraph("A.R.P : "));
        PdfPCell cell18 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.00522)));

        tablesocialSecurity.setWidthPercentage(100F);
        tablesocialSecurity.setHorizontalAlignment(Element.ALIGN_CENTER);
        tablesocialSecurity.addCell(cell13);
        tablesocialSecurity.addCell(cell14);
        tablesocialSecurity.addCell(cell15);
        tablesocialSecurity.addCell(cell16);
        tablesocialSecurity.addCell(cell17);
        tablesocialSecurity.addCell(cell18);
        document.add(tablesocialSecurity);

        PdfPTable social_benefits = new PdfPTable(2);
        PdfPCell title3 = new PdfPCell(new Paragraph("Prestaciones Sociales", fuente));
        title3.setColspan(2);
        social_benefits.addCell(title3);
        PdfPCell cell19 = new PdfPCell(new Paragraph("Prima de servicios : "));
        PdfPCell cell20 = new PdfPCell(new Paragraph(String.valueOf(totalAccrued * 0.0833)));
        PdfPCell cell21 = new PdfPCell(new Paragraph("Cesantias : "));
        PdfPCell cell22 = new PdfPCell(new Paragraph(String.valueOf(totalAccrued * 0.0833)));
        PdfPCell cell23 = new PdfPCell(new Paragraph("Intereses sobre las cesantias : "));
        PdfPCell cell24 = new PdfPCell(new Paragraph(String.valueOf(totalAccrued * 0.0833 * 0.12)));
        PdfPCell cell25 = new PdfPCell(new Paragraph("Vacaciones : "));
        PdfPCell cell26 = new PdfPCell(new Paragraph(String.valueOf(contractObject.getSalary() * 0.0417)));
        social_benefits.setWidthPercentage(100F);
        social_benefits.setHorizontalAlignment(Element.ALIGN_CENTER);
        social_benefits.addCell(cell19);
        social_benefits.addCell(cell20);
        social_benefits.addCell(cell21);
        social_benefits.addCell(cell22);
        social_benefits.addCell(cell23);
        social_benefits.addCell(cell24);
        social_benefits.addCell(cell25);
        social_benefits.addCell(cell26);
        document.add(social_benefits);

        PdfPTable fiscal_contributions = new PdfPTable(2);
        PdfPCell title4 = new PdfPCell(new Paragraph("Aportes Parafiscales", fuente));
        title4.setColspan(2);
        fiscal_contributions.addCell(title4);
        PdfPCell cell27 = new PdfPCell(new Paragraph("Cajas de compensacion familiar (4%) : "));
        PdfPCell cell28 = new PdfPCell(
                new Paragraph(String.valueOf((contractObject.getSalary() + extra_hours + commissions) * 0.04)));
        PdfPCell cell29 = new PdfPCell(new Paragraph("I.CB.F (3%) : "));
        PdfPCell cell30 = new PdfPCell(
                new Paragraph(String.valueOf((contractObject.getSalary() + extra_hours + commissions) * 0.03)));
        PdfPCell cell31 = new PdfPCell(new Paragraph("Sena (2%) : "));
        PdfPCell cell32 = new PdfPCell(
                new Paragraph(String.valueOf((contractObject.getSalary() + extra_hours + commissions) * 0.02)));
        fiscal_contributions.setWidthPercentage(100F);
        fiscal_contributions.setHorizontalAlignment(Element.ALIGN_CENTER);
        fiscal_contributions.addCell(cell27);
        fiscal_contributions.addCell(cell28);
        fiscal_contributions.addCell(cell29);
        fiscal_contributions.addCell(cell30);
        fiscal_contributions.addCell(cell31);
        fiscal_contributions.addCell(cell32);
        document.add(fiscal_contributions);

        PdfPTable totalValue = new PdfPTable(2);
        PdfPCell title5 = new PdfPCell(new Paragraph("Neto a pagar al empleado", fuente));
        title5.setColspan(2);
        totalValue.addCell(title5);
        PdfPCell cell33 = new PdfPCell(new Paragraph(" Total devengado - salud - pension"));
        cell33.setColspan(2);
        PdfPCell cell34 = new PdfPCell(new Paragraph(
                " $ " + String.valueOf(totalAccrued - contractObject.getSalary() * 0.08), fuente));
        cell34.setColspan(2);
        totalValue.setWidthPercentage(100F);
        totalValue.setHorizontalAlignment(Element.ALIGN_CENTER);
        totalValue.addCell(cell33);
        totalValue.addCell(cell34);
        document.add(totalValue);

        document.add(endtext);
    } else if (cert.getType().toLowerCase().equals("salud")) {
        typeCertificate = "Salud";
        document.add(header);
        Paragraph body = new Paragraph(user.getName().toUpperCase() + " " + user.getLastname().toUpperCase()
                + " con cedula de ciudadania No." + user.getIdentifyCard() + ", esta afiliado desde "
                + contractObject.getStartHealthDate() + " a la empresa de salud "
                + contractObject.getHealthEnterprise() + ".");
        body.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
        document.add(body);
        document.add(endtext);
    } else if (cert.getType().toLowerCase().equals("pensin")) {
        typeCertificate = "Pension";
        document.add(header);
        Paragraph body = new Paragraph(user.getName().toUpperCase() + " " + user.getLastname().toUpperCase()
                + " con cedula de ciudadania No." + user.getIdentifyCard()
                + ", esta afiliado a la empresa de pension " + contractObject.getPensionEnterprise()
                + ".La fecha de inicio de pension es " + contractObject.getStartPensionDate() + ".");
        body.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
        document.add(body);
        document.add(endtext);
    }
    document.close();
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentType("application/octet-strem");
    File f = new File("Certificado" + typeCertificate + ".pdf");
    response.setHeader("Content-Disposition", "attachment;filename=" + f.getName());
    response.setContentLength(baos.size());
    System.out.println("Hasta aca crea el pdf bien");
    OutputStream os = response.getOutputStream();
    System.out.println("Ac'a ya deberia haber descargado");
    baos.writeTo(os);
    os.flush();
    os.close();
}

From source file:bussiness.ReportHandler.java

public void BuildSaleReport(double totalCost) {
    try {/*w  w  w.  j ava 2  s  .co  m*/
        // Se crea el documento
        Document documento = new Document();
        // Se crea el OutputStream para el fichero donde queremos dejar el pdf.
        FileOutputStream ficheroPdf = new FileOutputStream("fichero.pdf");

        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
        Image imagen = Image.getInstance("logo.jpeg");

        documento.open();
        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        table.getDefaultCell().setPaddingLeft(60);
        BuildHeaderSaleReport(documento);

        documento.add(new Chunk("\n"));
        documento.add(new Chunk("\n"));
        documento.add(new Chunk("\n"));
        documento.add(new Chunk("\n"));
        documento.add(new Chunk("\n"));
        documento.add(new Chunk("\n"));

        imagen.setAbsolutePosition(110f, 150f);

        BuildBodySaleReport(table, totalCost, documento);

        BuildFooterSaleReport(documento);
        documento.add(imagen);
        documento.close();

    } catch (Exception e) {
        System.err.println("Ocurrio un error: " + e);
        System.exit(-1);
    }
}

From source file:bussiness.ReportHandler.java

public void BuildVeterinaryPrescription(String clientName, String petName, List<Medicine> medicines,
        String comments, Double totalCost) {
    try {/*from  w  ww .  ja  va 2s  . c  o  m*/
        Document veterinaryPrescription = new Document(PageSize.A3.rotate());
        //Tal vez agregar la fecha al nombre de la receta
        FileOutputStream fileOutputStream = new FileOutputStream("prescription.pdf");
        PdfWriter.getInstance(veterinaryPrescription, fileOutputStream).setInitialLeading(20);
        Image logo = Image.getInstance("logo2.png");
        Image division = Image.getInstance("linea.png");
        veterinaryPrescription.open();
        division.setAbsolutePosition(20f, 600f);
        veterinaryPrescription.add(division);
        logo.setAbsolutePosition(400, 50f);
        veterinaryPrescription.add(logo);

        //Encabezado
        BuildHeaderPrescription(veterinaryPrescription, clientName, petName);

        //Cuerpo
        veterinaryPrescription.add(new Chunk("\n"));
        veterinaryPrescription.add(new Chunk("\n"));
        veterinaryPrescription.add(new Chunk("\n"));

        PdfPTable table = new PdfPTable(3);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        table.getDefaultCell().setPaddingLeft(60);

        BuildBodyPrescription(medicines, veterinaryPrescription, totalCost, table);

        BuildFooterPrescription(veterinaryPrescription, comments);

        veterinaryPrescription.close();
    } catch (Exception e) {
        System.err.println("Ocurrio un error: " + e);
        System.exit(-1);
    }
}

From source file:by.bsuir.group172301.matskevich.tour.util.PDFCreator.java

public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName, int col1, int col2,
        double perc) {
    PdfWriter writer = null;//from   w ww  . ja  va 2s  .com

    Document document = new Document();

    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        Paragraph paragraph = new Paragraph();
        // We add one empty line

        paragraph = new Paragraph("Results:");
        paragraph.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph);
        paragraph = new Paragraph("Test before: " + col1);
        document.add(paragraph);
        paragraph = new Paragraph("Test after: " + col2);
        document.add(paragraph);
        paragraph = new Paragraph("Percentage: " + perc);
        document.add(paragraph);
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);

        chart.draw(graphics2d, rectangle2d);

        graphics2d.dispose();
        contentByte.addTemplate(template, 150, 250);

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

From source file:ca.sqlpower.wabit.report.LayoutToPDF.java

License:Open Source License

public void writePDF() throws DocumentException, FileNotFoundException, PrinterException {
    monitorableHelper.setStarted(true);/*from  w w  w  .j ava 2s .c  o m*/
    int pageNum = 0;

    int numPages = layout.getNumberOfPages();
    monitorableHelper.setJobSize(numPages);
    Page page = layout.getPage();
    OutputStream out = fileOS;
    Rectangle pageSize;
    pageSize = new Rectangle(page.getWidth(), page.getHeight());

    Document pdfDoc = new Document(pageSize, 0f, 0f, 0f, 0f);

    PdfWriter pdfOut = PdfWriter.getInstance(pdfDoc, out);
    pdfDoc.open();
    pdfDoc.addCreator("Wabit " + WabitVersion.VERSION);
    PdfContentByte pdfContent = pdfOut.getDirectContent();
    Graphics2D pdfGraphics = null;
    try {
        while (pageNum < numPages) {
            monitorableHelper.checkCancelled();
            monitorableHelper.setProgress(pageNum);
            pdfGraphics = pdfContent.createGraphics(pageSize.getWidth(), pageSize.getHeight());
            int flag = layout.print(pdfGraphics, layout.getPageFormat(pageNum), pageNum);

            if (watermarker != null) {
                java.awt.Rectangle watermarkSize = new java.awt.Rectangle();
                watermarkSize.setSize(Math.round(pageSize.getWidth()), Math.round(pageSize.getHeight()));
                watermarker.watermark(pdfGraphics, watermarkSize);
            }

            pdfGraphics.dispose();
            pdfGraphics = null;

            if (flag == Printable.NO_SUCH_PAGE)
                break;

            pdfDoc.newPage();

            pageNum++;
        }
    } finally {
        if (pdfGraphics != null)
            pdfGraphics.dispose();
        if (pdfDoc != null)
            pdfDoc.close();
        monitorableHelper.setFinished(true);
    }
}

From source file:ca.uwo.csd.cs2212.team02.MainWindow.java

/**
 * Export current page to PDF//from  ww  w . ja v a2  s.c om
 *
 * @param jpanel Panel to be exported to PDF
 */
public void createPDF(JLayeredPane jpanel) {
    playButtonSound();
    com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(0, 0, jpanel.getWidth(),
            jpanel.getHeight());
    Document doc = new Document(r);
    String filename = fileChooser();
    if (filename != "INVALID") {
        try {
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
            doc.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(PageSize.A4.getHeight() * 2, PageSize.A4.getWidth() * 2);
            Graphics2D g2;
            g2 = tp.createGraphics(jpanel.getWidth(), jpanel.getHeight(), new DefaultFontMapper());
            jpanel.print(g2);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
            PopUpWindow saveSuccess = new PopUpWindow(filename, "Save Successful!", 8);
        } catch (Exception e) {
            new PopUpWindow("Please try again.", "Error saving file");
        }
    }
    doc.close();
}

From source file:CadastroDeMusicas.Principal.java

public static void main(String[] args) throws Exception {
    ConecBanco c = new ConecBanco(con);
    Genero g;/*from w ww. j  a  va2s. co  m*/
    Artista a1;
    Album a2;
    Musica m;
    String nome, tipo;
    int nota, duracao, ano;
    int opc;
    try {
        new Principal();
    } catch (ClassNotFoundException | SQLException e) {
        System.out.println("No conectado.");
    }

    do {
        opc = Integer.parseInt(JOptionPane.showInputDialog(
                "Informe a OPO:\n1.Inserir\n2.Deletar\n3.Pesquisar\n4.Relatorio em Pdf\n5.Sair"));
        switch (opc) {
        case 1:
            nome = JOptionPane.showInputDialog("Genero: ");
            g = new Genero(nome);
            nome = JOptionPane.showInputDialog("Artista: ");
            a1 = new Artista(nome);
            nome = JOptionPane.showInputDialog("Album: ");
            ano = Integer.parseInt(JOptionPane.showInputDialog("Ano: "));
            a2 = new Album(nome, ano);
            nome = JOptionPane.showInputDialog("Musica: ");
            nota = Integer.parseInt(JOptionPane.showInputDialog("Nota (1/10): "));
            duracao = Integer.parseInt(JOptionPane.showInputDialog("Durao: "));
            m = new Musica(nome, nota, duracao);
            c.cadastrar(g, a1, a2, m);
            break;
        case 2:
            System.out.println("DELETAR MUSICA: ");
            nome = JOptionPane.showInputDialog("Musica: ");
            c.deletar(nome);
            break;
        case 3:
            System.out.println("PESQUISAR MUSICA: ");
            ResultSet rs = ConecBanco.pesquisar();
            if (rs != null) {
                try {
                    while (rs.next()) {
                        System.out.println("MUSICA:  " + rs.getString("nome"));
                        System.out.println("NOTA:  " + rs.getString("nota"));
                        System.out.println("DURAO:  " + rs.getString("duracao"));
                        System.out.println("ALBUM:  " + rs.getString("nomeAL"));
                        System.out.println("ANO:  " + rs.getString("ano"));
                        System.out.println("ARTISTA:  " + rs.getString("nomeAR"));
                        System.out.println("GENERO:  " + rs.getString("nomeGE"));

                    }
                } catch (SQLException e) {
                    System.out.println("Problema para exibir registros!");
                }
            } else {
                System.out.println("A pesquisa no retornou nenhum registro!");
            }
            break;
        case 4:
            Document doc = null;
            OutputStream os = null;
            String add;
            System.out.println("LISTA DE MUSICAS: ");
            try {
                doc = new Document(PageSize.A4, -1, -1, 25, 1) {
                };
                os = new FileOutputStream("Relatorio.pdf");
                PdfWriter.getInstance((com.itextpdf.text.Document) doc, os);
                doc.open();
                Image img = Image.getInstance("images.jpg");
                img.setAlignment(Element.ALIGN_CENTER);
                doc.add(img);
                PdfPTable TB1, TB2, TB3, TB4;
                TB1 = new PdfPTable(2);
                TB2 = new PdfPTable(3);
                TB3 = new PdfPTable(4);
                TB4 = new PdfPTable(5);
                PdfPCell T1, T2, T3, T4, T5;
                T1 = new PdfPCell(new Paragraph("\nCADASTRO DE MUSICAS\n"));
                T1.setColspan(2);
                TB1.addCell(T1);
                T2 = new PdfPCell(new Paragraph("\nGENEROS\n"));
                T2.setColspan(2);
                TB1.addCell(T2);
                ResultSet res, res1, res2, res3;
                res = ConecBanco.relatorioGenero();
                if (res != null) {
                    try {
                        while (res.next()) {
                            TB1.addCell("ID:  " + res.getString("id"));
                            TB1.addCell("NOME:  " + res.getString("nomeGE"));

                        }
                        doc.add(TB1);
                    } catch (SQLException e) {
                        System.out.println("Problema para exibir registros!");
                    }
                } else {
                    System.out.println("A pesquisa no retornou nenhum registro!");
                }
                T3 = new PdfPCell(new Paragraph("\nARTISTAS\n"));
                T3.setColspan(3);
                TB2.addCell(T3);
                res1 = ConecBanco.relatorioArtista();
                if (res1 != null) {
                    try {
                        while (res1.next()) {
                            TB2.addCell("ID:  " + res1.getString("id"));
                            TB2.addCell("NOME:  " + res1.getString("nomeAR"));
                            TB2.addCell("GENERO ID:  " + res1.getString("genero_id"));
                        }
                        doc.add(TB2);
                    } catch (SQLException e) {
                        System.out.println("Problema para exibir registros!");
                    }
                } else {
                    System.out.println("A pesquisa no retornou nenhum registro!");
                }
                T4 = new PdfPCell(new Paragraph("\nALBUM\n"));
                T4.setColspan(4);
                TB3.addCell(T4);
                res2 = ConecBanco.relatorioAlbum();
                if (res2 != null) {
                    try {
                        while (res2.next()) {
                            TB3.addCell("ID:  " + res2.getString("id"));
                            TB3.addCell("NOME:  " + res2.getString("nomeAL"));
                            TB3.addCell("ANO:  " + res2.getString("ano"));
                            TB3.addCell("ARTISTA ID:  " + res2.getString("artista_id"));
                        }
                        doc.add(TB3);
                    } catch (SQLException e) {
                        System.out.println("Problema para exibir registros!");
                    }
                } else {
                    System.out.println("A pesquisa no retornou nenhum registro!");
                }
                T5 = new PdfPCell(new Paragraph("\nMUSICA\n"));
                T5.setColspan(5);
                TB4.addCell(T5);
                res3 = ConecBanco.relatorioMusica();
                if (res3 != null) {
                    try {
                        while (res3.next()) {
                            TB4.addCell("ID:  " + res3.getString("id"));
                            TB4.addCell("NOME:  " + res3.getString("nome"));
                            TB4.addCell("NOTA:  " + res3.getString("nota"));
                            TB4.addCell("DURAO:  " + res3.getString("duracao"));
                            TB4.addCell("ALBUM ID:  " + res3.getString("album_id"));
                        }
                        doc.add(TB4);
                    } catch (SQLException e) {
                        System.out.println("Problema para exibir registros!");
                    }
                } else {
                    System.out.println("A pesquisa no retornou nenhum registro!");
                }
            } finally {
                if (doc != null) {
                    doc.close();
                }
                if (os != null) {
                    os.close();
                }
            }
            break;
        case 5:
            System.out.println("SAINDO...");
            break;
        default:
            System.out.println("OPO INVALIDA!");
        }
    } while (opc != 5);

}

From source file:Capa_Modelo.Reportes.java

public void generarReporteInventario() {
    Connection con;/*from w  ww .  j a va2  s .  c o m*/
    ResultSet res;
    Statement sentencia;
    Document documento = new Document(PageSize.A4);
    con = ConexionDB.GetConnection();
    try {
        sentencia = con.createStatement();
        res = sentencia.executeQuery(
                "SELECT Cantidad, Cantidadmin,  Cantidadmax, Medicamento.Nombre, Medicamento.FechaElaboracion, Medicamento.Composicion, Medicamento.FechaVencimiento, Medicamento.Laboratorio FROM Inventario inner join Medicamento on Inventario.ID_Medicamento = Medicamento.ID_Medicamento ");
        PdfWriter.getInstance(documento, new FileOutputStream(
                "reportes/reporte_de_inventario " + fechaActual() + " " + horaActual() + ".pdf"));
        documento.open();
        float[] columnWidths = { 2, 2, 2, 2, 2, 2, 2, 2 };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
        Font f = new Font(Font.FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de Medicamentos", f));
        cell.setBackgroundColor(GrayColor.GRAYBLACK);
        cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell.setColspan(8);
        table.addCell(cell);
        table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table.addCell("Medicamento");
            table.addCell("Composicion");
            table.addCell("Laboratorio");
            table.addCell("Fecha de Elaboracion");
            table.addCell("Fecha de Vencimiento");
            table.addCell("Cantidad minima");
            table.addCell("Cantidad actual");
            table.addCell("Cantidad maxima");
        }
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res.next()) {
            table.addCell(res.getString("Nombre"));
            table.addCell(res.getString("Composicion"));
            table.addCell(res.getString("Laboratorio"));
            table.addCell(res.getString("FechaElaboracion"));
            table.addCell(res.getString("FechaVencimiento"));
            table.addCell(res.getString("Cantidadmin"));
            table.addCell(res.getString("Cantidad"));
            table.addCell(res.getString("Cantidadmax"));
        }
        documento.add(table);
        documento.close();
        JOptionPane.showMessageDialog(null, "Reporte de Inventario generado correctamente");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Error al conectar con la base de datos");
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar la ruta del archivo");
    } catch (DocumentException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar el archivo");
    }

}