Example usage for com.itextpdf.text Document add

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

Introduction

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

Prototype


public boolean add(Element element) throws DocumentException 

Source Link

Document

Adds an Element to the Document.

Usage

From source file:com.myapp.struts.transaction.transactionAction.java

public ActionForward generatememberreport(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, Exception {
    if (Constants.isSessionActive(request)) {
        transactionForm transactionForm = (transactionForm) form;
        try {//from   w w  w. j  av a2  s.  co m
            Date utilDate = new Date();
            java.sql.Date date = new java.sql.Date(utilDate.getTime());
            Font bigFont = FontFactory.getFont(FontFactory.HELVETICA, "Windows-1254", 12, Font.BOLD,
                    BaseColor.BLACK);
            Font bigFont_Uderline = FontFactory.getFont(FontFactory.HELVETICA, "Windows-1254", 12,
                    Font.BOLD | Font.UNDERLINE, BaseColor.BLACK);
            Font boldfont = FontFactory.getFont(FontFactory.HELVETICA, "Windows-1254", 9, Font.BOLD);

            Document document = new Document();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            document.open();

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); //Or whatever format fits best your needs.

            Paragraph para1 = new Paragraph("PALKE JEWELLERS", bigFont);
            para1.setAlignment(Element.ALIGN_CENTER);
            document.add(para1);

            para1 = new Paragraph("MEMBER ACCOUNT DETAILS", bigFont);
            para1.setAlignment(Element.ALIGN_CENTER);
            document.add(para1);

            para1 = new Paragraph(transactionForm.getSelectedmember(), boldfont);
            para1.setAlignment(Element.ALIGN_LEFT);
            document.add(para1);

            para1 = new Paragraph(
                    transactionForm.getMemberaddress() + "\n" + transactionForm.getMembercontactno(), boldfont);
            para1.setAlignment(Element.ALIGN_LEFT);
            document.add(para1);
            Groups obj = (Groups) hmGroups.get(transactionForm.getGroupid() + "");
            if (obj != null) {
                para1 = new Paragraph("Group : " + obj.getGroupname(), font);
                para1.setAlignment(Element.ALIGN_LEFT);
                document.add(para1);

                para1 = new Paragraph("Paid Amount : " + transactionForm.getTotalpaidamount(), font);
                para1.setAlignment(Element.ALIGN_LEFT);
                document.add(para1);

                para1 = new Paragraph("Prize Amount : " + transactionForm.getDrawamount(), font);
                para1.setAlignment(Element.ALIGN_LEFT);
                document.add(para1);

                para1 = new Paragraph("Total Amount : " + transactionForm.getTotalamount(), boldfont);
                para1.setAlignment(Element.ALIGN_LEFT);
                document.add(para1);

                para1 = new Paragraph("Status : " + transactionForm.getStatus(), boldfont);
                para1.setAlignment(Element.ALIGN_RIGHT);
                document.add(para1);

                if (transactionForm.getStatus().equalsIgnoreCase("Settled")) {
                    para1 = new Paragraph(transactionForm.getSettlementcomment(), boldfont);
                    para1.setAlignment(Element.ALIGN_RIGHT);
                    document.add(para1);
                }

                String dateStr = sdf.format(date);
                para1 = new Paragraph("DATED:" + dateStr, font);
                para1.setAlignment(Element.ALIGN_RIGHT);
                document.add(para1);

                // add a couple of blank lines
                document.add(Chunk.NEWLINE);

                if (transactionForm.getLstPayment() != null && transactionForm.getLstPayment().size() > 0) {
                    PdfPTable table2 = new PdfPTable(7);
                    float[] columnWidths = { 1.5f, 1.5f, 3f, 4f, 4f, 7f, 2f };

                    table2.setWidthPercentage(100);
                    table2.setWidths(columnWidths);

                    para1 = new Paragraph("Sl No.", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    PdfPCell cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    para1 = new Paragraph("Term", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    para1 = new Paragraph("Receipt No.", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    para1 = new Paragraph("Receipt Date", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    para1 = new Paragraph("Payment Mode", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    para1 = new Paragraph("Remarks", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    para1 = new Paragraph("Paid Amount", font);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    cell = new PdfPCell(para1);
                    table2.addCell(cell);

                    int x = 1;
                    double total = 0;
                    //Iterator it = hmPayments.entrySet().iterator();
                    //while (it.hasNext()) {
                    if (hmPayments.size() > 0) {
                        for (int i = 1; i <= obj.getNoofinstallment(); i++) {
                            //float f = columnWidths[i];
                            Payment f1 = (Payment) hmPayments.get(i + "");
                            //}
                            //Map.Entry pairs = (Map.Entry) it.next();
                            //Payment f1 = (Payment) pairs.getValue();
                            String term = i + "";

                            para1 = new Paragraph(Integer.toString(x), font);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);
                            x++;

                            para1 = new Paragraph(term, font);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);

                            para1 = new Paragraph(f1.getPaymentid() + "", font);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);

                            para1 = new Paragraph(sdf.format(f1.getPaiddate()), font);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);

                            para1 = new Paragraph(f1.getPaymentmode() == 1 ? "Cash" : "Cheque/NEFT", font);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);

                            para1 = new Paragraph(f1.getRemarks(), font);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);

                            //para1 = new Paragraph(f1.getPaidamount() + "", boldfont);
                            para1 = new Paragraph((int) obj.getInstallmentamount() + "", boldfont);
                            para1.setAlignment(Element.ALIGN_CENTER);
                            cell = new PdfPCell(para1);
                            table2.addCell(cell);
                            total = total + obj.getInstallmentamount();
                            if (hmPayments.size() == i) {
                                break;
                            }
                        }

                        para1 = new Paragraph("Total", boldfont);
                        para1.setAlignment(Element.ALIGN_LEFT);
                        cell = new PdfPCell(para1);
                        cell.setColspan(6);
                        table2.addCell(cell);

                        //String numberStr = String.format("%.2f", total + "");
                        para1 = new Paragraph(total + "", boldfont);
                        para1.setAlignment(Element.ALIGN_CENTER);
                        cell = new PdfPCell(para1);
                        //cell.setColspan(7);
                        table2.addCell(cell);

                        table2.setHorizontalAlignment(Element.ALIGN_LEFT);
                        document.add(table2);
                    } else {
                        para1 = new Paragraph("NO PAYMENTS FOUND", boldfont);
                        para1.setAlignment(Element.ALIGN_CENTER);
                        document.add(para1);
                    }

                } else {
                    para1 = new Paragraph("NO RECORDS FOUND", boldfont);
                    para1.setAlignment(Element.ALIGN_CENTER);
                    document.add(para1);
                }
                document.add(Chunk.NEWLINE);

                //document.close();
                //fileInputStream = new FileInputStream(new File("C:\\reports\\PaymentReports.pdf"));
                document.close();
                ServletOutputStream outputStream = response.getOutputStream();
                baos.writeTo(outputStream);
                response.setHeader("Content-Disposition", "attachment; filename=\"PaymentStatusReport.pdf\"");
                response.setContentType("application/pdf");
                outputStream.flush();
                outputStream.close();
                return mapping.findForward("display");
            } else {
                para1 = new Paragraph("NO RECORDS FOUND", boldfont);
                para1.setAlignment(Element.ALIGN_CENTER);
                document.add(para1);
                document.close();
                ServletOutputStream outputStream = response.getOutputStream();
                baos.writeTo(outputStream);
                response.setHeader("Content-Disposition", "attachment; filename=\"PaymentStatusReport.pdf\"");
                response.setContentType("application/pdf");
                outputStream.flush();
                outputStream.close();
                return mapping.findForward("display");
            }
        } catch (DocumentException i) {
            System.out.println(i);
            return mapping.findForward("fail");
        } catch (IOException i) {
            System.out.println(i);
            return mapping.findForward("fail");
        }
    } else {
        return mapping.findForward("exp");
    }
}

From source file:com.mycom.products.mywebsite.backend.util.DownloadHandler.java

License:Open Source License

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
protected final void downloadUserInformation(@PathVariable int id, HttpServletRequest request,
        final HttpServletResponse response) throws ServletException, BusinessException, DocumentException {
    UserBean user = userService.select(id, FetchMode.EAGER);
    if (user == null) {
        return;/*from  w  ww.  jav  a 2s .  c  o m*/
    }
    Document document = new Document();
    document.setMargins(70, 70, 20, 20);

    try {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + user.getName() + "_profile.pdf\"");
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        Image profileImage = null;
        try {
            profileImage = Image.getInstance(user.getContent().getFilePath());
        } catch (Exception e) {
            // e.printStackTrace();
        }
        if (profileImage != null) {
            profileImage.setAlignment(Image.MIDDLE | Image.TEXTWRAP);
            profileImage.setBorder(Image.BOX);
            profileImage.setBorderWidth(5);
            BaseColor bgcolor = WebColors.getRGBColor("#E5E3E3");
            profileImage.setBorderColor(bgcolor);
            profileImage.scaleToFit(100, 100);
            document.add(profileImage);
        }
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        // Adding Table Data
        PdfPTable table = new PdfPTable(2); // 2 columns.
        table.setWidthPercentage(100); // Width 100%
        table.setSpacingBefore(15f); // Space before table
        table.setSpacingAfter(15f); // Space after table

        // Set Column widths
        float[] columnWidths = { 1f, 2f, };
        table.setWidths(columnWidths);

        // Name
        setTableHeader("Name", table);
        setTableContent(user.getName(), table);

        // Gender
        setTableHeader("Gender", table);
        String gender = "Male";
        if (user.getGender() == Gender.FEMALE) {
            gender = "Female";
        }
        setTableContent(gender, table);

        // Age
        setTableHeader("Age", table);
        setTableContent("" + user.getAge(), table);

        // Date of Birth
        setTableHeader("DOB", table);
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        setTableContent(dateFormatter.format(user.getDob()), table);

        // Email
        setTableHeader("Email", table);
        setTableContent(user.getEmail(), table);

        // NRC
        setTableHeader("NRC", table);
        setTableContent(user.getNrc(), table);

        // Phone
        setTableHeader("Phone", table);
        setTableContent(user.getPhone(), table);

        // Roles
        String roleStr = "";
        List<RoleBean> roles = user.getRoles();
        if (roles != null && roles.size() > 0) {
            Iterator<RoleBean> itr = roles.iterator();
            while (itr.hasNext()) {
                RoleBean role = itr.next();
                roleStr += role.getName();
                if (itr.hasNext()) {
                    roleStr += ",";
                }
            }
        }
        setTableHeader("Role(s)", table);
        setTableContent(roleStr, table);

        // Address
        setTableHeader("Address", table);
        setTableContent(user.getAddress(), table);

        document.add(table);
        document.add(new Paragraph(new Date().toString()));

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

    }
    document.close();
}

From source file:com.mycompany.bandaru_exam.accountDriver.java

/**
 * @param args the command line arguments
 *///from   w  w  w  . j  av  a  2  s .com
public static void main(String[] args)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {
    // TODO code application logic here
    ReadfromExcel rd = new ReadfromExcel();
    List<Account> accountList = rd.getAccountListFromExcel();
    for (Account a : accountList) {
        System.out.println(a.getFirstName());
        OutputStream file = new FileOutputStream(new File(a.getLastName() + ".pdf"));
        Document document = new Document();
        PdfWriter.getInstance(document, file);

        //Inserting Image in PDF
        Image image = Image.getInstance("logo.png");
        image.scaleAbsolute(600f, 100f);//image width,height

        //Now Insert Every Thing Into PDF Document
        document.open();//PDF document opened........                
        document.add(image);
        document.add(new Paragraph("Welcome! " + a.getFirstName() + " " + a.getLastName() + "!"));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("        " + "Below are your Account Details :"));
        document.add(new Paragraph("        " + "First Name:" + a.getFirstName()));
        document.add(new Paragraph("        " + "Last Name:" + a.getLastName()));
        document.add(new Paragraph("        " + "Account Number:" + a.getAccNumber()));
        document.add(new Paragraph("        " + "Account Balance:$" + a.getBalance()));
        document.close();
        file.close();
    }
}

From source file:com.mycompany.mavenproject1.Createpdf.java

private void generateLayout(Document doc, PdfContentByte cb) {

    try {/*from ww  w  .j  a v  a 2 s.c o  m*/

        cb.setLineWidth(1f);

        // Invoice Header box layout
        cb.rectangle(420, 700, 150, 60);
        cb.moveTo(420, 720);
        cb.lineTo(570, 720);
        cb.moveTo(420, 740);
        cb.lineTo(570, 740);
        cb.moveTo(480, 700);
        cb.lineTo(480, 760);
        cb.stroke();

        // Invoice Header box Text Headings 
        createHeadings(cb, 422, 743, "Account No.");
        createHeadings(cb, 422, 723, "Invoice No.");
        createHeadings(cb, 422, 703, "Invoice Date");

        // Invoice Detail box layout 
        cb.rectangle(20, 50, 550, 600);
        cb.moveTo(20, 630);
        cb.lineTo(570, 630);
        cb.moveTo(50, 50);
        cb.lineTo(50, 650);
        cb.moveTo(150, 50);
        cb.lineTo(150, 650);
        cb.moveTo(430, 50);
        cb.lineTo(430, 650);
        cb.moveTo(500, 50);
        cb.lineTo(500, 650);
        cb.stroke();

        // Invoice Detail box Text Headings 
        createHeadings(cb, 22, 633, "Qty");
        createHeadings(cb, 52, 633, "Item Number");
        createHeadings(cb, 152, 633, "Item Description");
        createHeadings(cb, 432, 633, "Price");
        createHeadings(cb, 502, 633, "Ext Price");

        //add the images
        Image companyLogo = Image.getInstance("images/olympics_logo.gif");
        companyLogo.setAbsolutePosition(25, 700);
        companyLogo.scalePercent(25);
        doc.add(companyLogo);

    }

    catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.mycompany.mavenproject1.HelloWorld.java

/**
 * Creates a PDF document.//  w  w w.j a v  a2  s  .  c o m
 * @param filename the path to the new PDF document
 * @throws    DocumentException 
 * @throws    IOException 
 */
public void createPdf(String filename) throws DocumentException, IOException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    document.add(new Paragraph("Hello World!"));
    // step 5
    document.close();
}

From source file:com.mycompany.mavenproject2.ItemHistoryController.java

@FXML
public void OnPrintButtonAction(ActionEvent a) {
    Document document = new Document();
    //JavaPdfHelloWorld jp=new JavaPdfHelloWorld();

    try {//w w  w  .j a v a 2 s  .  c  o m
        PdfWriter.getInstance(document, new FileOutputStream("javaHello.pdf"));

        document.open();
        document.add(new Paragraph("A Hello World PDF document."));

        document.close();

        final File file = new File(
                "C:/Users/Third Ev/Documents/NetBeansProjects/FinalDemo/src/finaldemo/Controller/javaHello.pdf");

        f4.getHostServices().showDocument(file.toURI().toString());

        // no need to close PDFwriter?
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:com.mycompany.mavenproject2.JavaPdfHelloWorld.java

public static void main(String[] args) {
    Document document = new Document();
    try {//from   w  ww  .  j  a v  a 2  s .  c om
        PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));

        document.open();
        document.add(new Paragraph("A Hello World PDF document."));
        document.close(); // no need to close PDFwriter?

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.mycompany.mavenproject2.VirtualkeyController.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//w  ww  . j av  a  2  s  .  co m
    // Lets write a big header
    preface.add(new Paragraph("Report Item On History", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    /*  preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          smallBold));*/
    preface.add(new Paragraph("Address 1"));
    //addEmptyLine(preface, 1);
    preface.add(new Paragraph("Address 2"));
    // addEmptyLine(preface, 1);
    preface.add(new Paragraph("City"));
    // addEmptyLine(preface, 1);
    preface.add(new Paragraph("Store"));
    //addEmptyLine(preface, 3);
    //preface.add(new Paragraph("This document describes something which is very important ",smallBold));
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
            smallBold));
    addEmptyLine(preface, 2);
    createTable("category_detail", preface);
    //addEmptyLine(preface, 8);

    /*preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
        redFont));*/
    //preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$        smallBold));
    document.add(preface);
    // Start a new page
    //document.newPage();
}

From source file:com.mycompany.peram_inclassexam.WritePDFFile.java

public void createPDF(AccountDetails account)
        throws DocumentException, FileNotFoundException, BadElementException, IOException {

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    PdfWriter write = PdfWriter.getInstance(document,
            new FileOutputStream(account.getLastName() + "_output.pdf"));

    document.open();//from   w ww . j ava  2s .  c  o  m

    Image image = Image.getInstance("image.png");

    image.scaleToFit(450f, 1800f);

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

    Paragraph welcomeParagraph = new Paragraph(
            "Welcome! " + account.getFirstName() + " " + account.getLastName() + "!");
    welcomeParagraph.setSpacingBefore(50);

    document.add(welcomeParagraph);

    String firstName = "First Name: " + account.getFirstName();
    String lastName = "Last Name: " + account.getLastName();
    String acctNumber = "Account Number: " + account.getAccountNo();
    String acctBalance = String.format("Account Balance: $%.1f", account.getAccountBalance());

    Paragraph detailsPara = new Paragraph("Below are your Account Details:\n" + firstName + "\n" + lastName
            + "\n" + acctNumber + "\n" + acctBalance);
    detailsPara.setIndentationLeft(30);
    detailsPara.setSpacingBefore(20);
    document.add(detailsPara);

    document.close();
    write.close();
}

From source file:com.netsteadfast.greenstep.bsc.command.KpiReportPdfCommand.java

License:Apache License

private String createPdf(Context context) throws Exception {
    BscReportPropertyUtils.loadData();/*from  w w w  . java 2 s .  c om*/
    BscReportSupportUtils.loadExpression(); // 2015-04-18 add
    String visionOid = (String) context.get("visionOid");
    VisionVO vision = null;
    BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context);
    for (VisionVO visionObj : treeObj.getVisions()) {
        if (visionObj.getOid().equals(visionOid)) {
            vision = visionObj;
        }
    }
    FontFactory.register(BscConstants.PDF_ITEXT_FONT);
    String fileName = UUID.randomUUID().toString() + ".pdf";
    String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
    OutputStream os = new FileOutputStream(fileFullPath);
    //Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    document.left(100f);
    document.top(150f);
    PdfWriter writer = PdfWriter.getInstance(document, os);
    document.open();

    int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0)
            .getDateRangeScores().size();
    PdfPTable table = new PdfPTable(MAX_COLSPAN);
    PdfPTable dateRangeTable = new PdfPTable(dateRangeRows);
    PdfPTable chartsTable = new PdfPTable(2);
    PdfPTable signTable = new PdfPTable(1);
    table.setWidthPercentage(100f);
    dateRangeTable.setWidthPercentage(100f);
    chartsTable.setWidthPercentage(100f);
    signTable.setWidthPercentage(100f);

    this.createHead(table, vision);
    this.createBody(table, vision);
    this.createDateRange(dateRangeTable, vision, context, dateRangeRows);
    this.putCharts(chartsTable, context);
    this.putSignature(signTable, context);

    document.add(chartsTable);
    document.add(table);
    document.add(dateRangeTable);
    document.add(signTable);
    document.close();
    writer.close();

    os.flush();
    os.close();
    os = null;

    File file = new File(fileFullPath);
    String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file,
            "kpi-report.pdf");
    file = null;
    return oid;
}