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

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

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Signals that the Document was closed and that no other Elements will be added.

Usage

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Creates a/*  w  w w .j  av a2s.c o m*/
 * cited document from the given bitstream of the given item. This
 * requires that bitstream is contained in item.
 * <p>
 * The Process for adding a cover page is as follows:
 * <ol>
 *  <li> Load source file into PdfReader and create a
 *     Document to put our cover page into.</li>
 *  <li> Create cover page and add content to it.</li>
 *  <li> Concatenate the coverpage and the source
 *     document.</li>
 * </p>
 *
 * @param bitstream The source bitstream being cited. This must be a PDF.
 * @param cMeta The citation information used to generate the coverpage.
 * @return The temporary File that is the finished, cited document.
 * @throws com.itextpdf.text.DocumentException
 * @throws java.io.FileNotFoundException
 * @throws SQLException
 * @throws org.dspace.authorize.AuthorizeException
 */
private File makeCitedDocument(Bitstream bitstream, CitationMeta cMeta)
        throws DocumentException, IOException, SQLException, AuthorizeException {
    //Read the source bitstream
    PdfReader source = new PdfReader(bitstream.retrieve());

    Document citedDoc = new Document(PageSize.LETTER);

    File coverTemp = File.createTempFile(bitstream.getName(), ".cover.pdf");

    //Need a writer instance to make changed to the document.
    PdfWriter writer = PdfWriter.getInstance(citedDoc, new FileOutputStream(coverTemp));

    //Call helper function to add content to the coverpage.
    this.generateCoverPage(citedDoc, writer, cMeta);

    //Create reader from finished cover page.
    PdfReader cover = new PdfReader(new FileInputStream(coverTemp));

    //Get page labels from source document
    String[] labels = PdfPageLabels.getPageLabels(source);

    //Concatenate the finished cover page with the source document.
    File citedTemp = File.createTempFile(bitstream.getName(), ".cited.pdf");
    OutputStream citedOut = new FileOutputStream(citedTemp);
    PdfConcatenate concat = new PdfConcatenate(citedOut);
    concat.open();

    //Is the citation-page the first page or last-page?
    if (isCitationFirstPage()) {
        //citation as cover page
        concat.addPages(cover);
        concat.addPages(source);
    } else {
        //citation as tail page
        concat.addPages(source);
        concat.addPages(cover);
    }

    //Put all of our labels in from the orignal document.
    if (labels != null) {
        PdfPageLabels citedPageLabels = new PdfPageLabels();
        log.debug("Printing arbitrary page labels.");

        for (int i = 0; i < labels.length; i++) {
            citedPageLabels.addPageLabel(i + 1, PdfPageLabels.EMPTY, labels[i]);
            log.debug("Label for page: " + (i + 1) + " -> " + labels[i]);
        }
        citedPageLabels.addPageLabel(labels.length + 1, PdfPageLabels.EMPTY, "Citation Page");
        concat.getWriter().setPageLabels(citedPageLabels);
    }

    //Close it up
    concat.close();

    //Close the cover-page
    writer.close();
    coverTemp.delete();

    citedTemp.deleteOnExit();
    return citedTemp;
}

From source file:org.javad.stamp.pdf.PdfGenerator.java

License:Apache License

public void generate(GenerateBean bean) throws Exception {
    long t = System.currentTimeMillis();
    config.parseSkipTerms(bean.getTags());
    Rectangle rect = new Rectangle(PdfUtil.convertFromMillimeters(config.getWidth()),
            PdfUtil.convertFromMillimeters(config.getHeight()));
    Document document = new Document(rect);
    PdfWriter writer = null;
    FileOutputStream fos = null;/*from   ww  w.  ja  va 2s  . c o  m*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        boolean validName = bean.getInputFile().getName().toLowerCase().endsWith(".xml");
        writer = PdfWriter.getInstance(document, baos);

        if (validName) {
            setMargins(document);
            parseXMLDocument(bean, document, writer);
            baos.flush();
            fos = new FileOutputStream(bean.getOutputFile());
            fos.write(baos.toByteArray());
            fos.flush();
            baos.close();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

        baos.close();
        if (writer != null) {
            writer.close();
        }
        if (fos != null) {
            fos.close();
        }
    }
    long delta = System.currentTimeMillis() - t;
    logger.log(Level.INFO, "Successful album page generation. (total execution time: " + delta + "ms)");
}

From source file:org.restate.project.controller.PaymentReceiptController.java

License:Open Source License

@RequestMapping(method = RequestMethod.GET, value = "receipt.print")
public void downloadDocument(HttpServletResponse response,
        @RequestParam(value = "id", required = false) Integer id) throws Exception {

    if (id == null) {
        return;//from w  w  w.  j a  v  a  2s . c  o  m
    }

    // creation of the document with a certain size and certain margins
    // may want to use PageSize.LETTER instead
    // Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    Document doc = new Document();
    PdfWriter docWriter = null;

    DecimalFormat df = new DecimalFormat("0.00");
    File tmpFile = File.createTempFile("paymentReceipt", ".pdf");

    try {

        //special font sizes
        Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0));
        Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 12);

        //file path

        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(tmpFile));

        //document header attributes
        doc.addAuthor("betterThanZero");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("MySampleCode.com");
        doc.addTitle("Report with Column Headings");
        doc.setPageSize(PageSize.LETTER);

        //open document
        doc.open();

        //create a paragraph
        Paragraph paragraph = new Paragraph("iText  is a library that allows you to create and "
                + "manipulate PDF documents. It enables developers looking to enhance web and other "
                + "applications with dynamic PDF document generation and/or manipulation.");

        //specify column widths
        float[] columnWidths = { 1.5f, 2f, 5f, 2f };
        //create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(90f);

        //insert column headings
        insertCell(table, "Order No", Element.ALIGN_RIGHT, 1, bfBold12);
        insertCell(table, "Account No", Element.ALIGN_LEFT, 1, bfBold12);
        insertCell(table, "Account Name", Element.ALIGN_LEFT, 1, bfBold12);
        insertCell(table, "Order Total", Element.ALIGN_RIGHT, 1, bfBold12);
        table.setHeaderRows(1);

        //insert an empty row
        insertCell(table, "", Element.ALIGN_LEFT, 4, bfBold12);
        //create section heading by cell merging
        insertCell(table, "New York Orders ...", Element.ALIGN_LEFT, 4, bfBold12);
        double orderTotal, total = 0;

        //just some random data to fill
        for (int x = 1; x < 5; x++) {

            insertCell(table, "10010" + x, Element.ALIGN_RIGHT, 1, bf12);
            insertCell(table, "ABC00" + x, Element.ALIGN_LEFT, 1, bf12);
            insertCell(table, "This is Customer Number ABC00" + x, Element.ALIGN_LEFT, 1, bf12);

            orderTotal = Double.valueOf(df.format(Math.random() * 1000));
            total = total + orderTotal;
            insertCell(table, df.format(orderTotal), Element.ALIGN_RIGHT, 1, bf12);

        }
        //merge the cells to create a footer for that section
        insertCell(table, "New York Total...", Element.ALIGN_RIGHT, 3, bfBold12);
        insertCell(table, df.format(total), Element.ALIGN_RIGHT, 1, bfBold12);

        //repeat the same as above to display another location
        insertCell(table, "", Element.ALIGN_LEFT, 4, bfBold12);
        insertCell(table, "California Orders ...", Element.ALIGN_LEFT, 4, bfBold12);
        orderTotal = 0;

        for (int x = 1; x < 7; x++) {

            insertCell(table, "20020" + x, Element.ALIGN_RIGHT, 1, bf12);
            insertCell(table, "XYZ00" + x, Element.ALIGN_LEFT, 1, bf12);
            insertCell(table, "This is Customer Number XYZ00" + x, Element.ALIGN_LEFT, 1, bf12);

            orderTotal = Double.valueOf(df.format(Math.random() * 1000));
            total = total + orderTotal;
            insertCell(table, df.format(orderTotal), Element.ALIGN_RIGHT, 1, bf12);

        }
        insertCell(table, "California Total...", Element.ALIGN_RIGHT, 3, bfBold12);
        insertCell(table, df.format(total), Element.ALIGN_RIGHT, 1, bfBold12);

        //add the PDF table to the paragraph
        paragraph.add(table);
        // add the paragraph to the document
        doc.add(paragraph);

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (doc != null) {
            //close the document
            doc.close();

        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }

        response.setHeader("Content-disposition", "attachment; filename=" + "sampleDoc" + ".pdf");
        response.setContentType("application/pdf");
        OutputStream outputStream = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(tmpFile);

        IOUtils.copy(fileInputStream, outputStream);
        fileInputStream.close();
        outputStream.flush();

        tmpFile.delete();
    }

}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

public String createPdf(OutputStream outputStream, String basePath, String serverRoot, String remoteUser,
        String language, boolean generateBlank, String filename, boolean landscape, // Set true if landscape
        HttpServletResponse response) throws Exception {

    if (language != null) {
        language = language.replace("'", "''"); // Escape apostrophes
    } else {//  ww  w  .j  a v  a  2  s .  c om
        language = "none";
    }

    mExcludeEmpty = survey.exclude_empty;

    User user = null;

    ServerManager serverManager = new ServerManager();
    ServerData serverData = serverManager.getServer(sd, localisation);

    UserManager um = new UserManager(localisation);
    int[] repIndexes = new int[20]; // Assume repeats don't go deeper than 20 levels

    Document document = null;
    PdfWriter writer = null;
    PdfReader reader = null;
    PdfStamper stamper = null;

    try {

        // Get fonts and embed them
        String os = System.getProperty("os.name");
        log.info("Operating System:" + os);

        if (os.startsWith("Mac")) {
            FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols");
            //FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default");
            FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/Library/Fonts/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/Library/Fonts/NotoSansBengali-Bold.ttf", "bengalibold");
        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) {
            // Linux / Unix
            FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols");
            FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans");
            FontFactory.register("/usr/share/fonts/truetype/NotoSans-Bold.ttf", "notosansbold");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Regular.ttf", "bengali");
            FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Bold.ttf", "bengalibold");
        }

        Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFontLink = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
        defaultFont = FontFactory.getFont("notosans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        defaultFontBold = FontFactory.getFont("notosansbold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        arabicFont = FontFactory.getFont("arabic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFont = FontFactory.getFont("bengali", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        bengaliFontBold = FontFactory.getFont("bengalibold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

        defaultFontLink.setColor(BaseColor.BLUE);

        /*
         * Get the results and details of the user that submitted the survey
         */

        log.info("User Ident who submitted the survey: " + survey.instance.user);
        String userName = survey.instance.user;
        if (userName == null) {
            userName = remoteUser;
        }
        if (userName != null) {
            user = um.getByIdent(sd, userName);
        }

        // If a filename was not specified then get one from the survey data
        // This filename is returned to the calling program so that it can be used as a permanent name for the temporary file created here
        // If the PDF is to be returned in an http response then the header is set now before writing to the output stream
        log.info("Filename passed to createPDF is: " + filename);
        if (filename == null) {
            filename = survey.getInstanceName() + ".pdf";
        } else {
            if (!filename.endsWith(".pdf")) {
                filename += ".pdf";
            }
        }

        // If the PDF is to be returned in an http response then set the file name now
        if (response != null) {
            log.info("Setting filename to: " + filename);
            GeneralUtilityMethods.setFilenameInResponse(filename, response);
        }

        /*
         * Get a template for the PDF report if it exists
         * The template name will be the same as the XLS form name but with an extension of pdf
         */
        File templateFile = GeneralUtilityMethods.getPdfTemplate(basePath, survey.displayName, survey.p_id);

        /*
         * Get dependencies between Display Items, for example if a question result should be added to another
         *  question's results
         */
        GlobalVariables gv = new GlobalVariables();
        if (!generateBlank) {
            for (int i = 0; i < survey.instance.results.size(); i++) {
                getDependencies(gv, survey.instance.results.get(i), survey, i);
            }
        }
        gv.mapbox_key = serverData.mapbox_default;
        int oId = GeneralUtilityMethods.getOrganisationId(sd, remoteUser);

        languageIdx = GeneralUtilityMethods.getLanguageIdx(survey, language);
        if (templateFile.exists()) {

            log.info("PDF Template Exists");
            String templateName = templateFile.getAbsolutePath();

            reader = new PdfReader(templateName);
            stamper = new PdfStamper(reader, outputStream);

            for (int i = 0; i < survey.instance.results.size(); i++) {
                fillTemplate(gv, stamper.getAcroFields(), survey.instance.results.get(i), basePath, null, i,
                        serverRoot, stamper, oId);
            }
            if (user != null) {
                fillTemplateUserDetails(stamper.getAcroFields(), user, basePath);
            }
            stamper.setFormFlattening(true);

        } else {
            log.info("++++No template exists creating a pdf file programmatically");

            /*
             * Create a PDF without the stationary
             * If we need to add a letter head then create document in two passes, the second pass adds the letter head
             * Else just create the document directly in a single pass
             */
            Parser parser = getXMLParser();

            // Step 1 - Create the underlying document as a byte array
            if (landscape) {
                document = new Document(PageSize.A4.rotate());
            } else {
                document = new Document(PageSize.A4);
            }
            document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1);
            writer = PdfWriter.getInstance(document, outputStream);

            writer.setInitialLeading(12);

            writer.setPageEvent(new PdfPageSizer(survey.displayName, survey.projectName, user, basePath, null,
                    marginLeft, marginRight, marginTop_2, marginBottom_2));
            document.open();

            // If this form has data maintain a list of parent records to lookup ${values}
            ArrayList<ArrayList<Result>> parentRecords = null;
            if (!generateBlank) {
                parentRecords = new ArrayList<ArrayList<Result>>();
            }

            for (int i = 0; i < survey.instance.results.size(); i++) {
                processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                        generateBlank, 0, i, repIndexes, gv, false, parentRecords, remoteUser, oId);
            }

            fillNonTemplateUserDetails(document, user, basePath);

            // Add appendix
            if (gv.hasAppendix) {
                document.newPage();
                document.add(new Paragraph("Appendix", defaultFontBold));

                for (int i = 0; i < survey.instance.results.size(); i++) {
                    processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot,
                            generateBlank, 0, i, repIndexes, gv, true, parentRecords, remoteUser, oId);
                }
            }

        }

    } finally {
        if (document != null)
            try {
                document.close();
            } catch (Exception e) {
            }
        ;
        if (writer != null)
            try {
                writer.close();
            } catch (Exception e) {
            }
        ;
        if (stamper != null)
            try {
                stamper.close();
            } catch (Exception e) {
            }
        ;
        if (reader != null)
            try {
                reader.close();
            } catch (Exception e) {
            }
        ;
    }

    return filename;

}

From source file:org.ujmp.itext.ExportPDF.java

License:Open Source License

public static final void save(File file, Component c, int width, int height) {
    if (file == null) {
        logger.log(Level.WARNING, "no file selected");
        return;/*from   w w w  . ja v  a  2  s.  c  o  m*/
    }
    if (c == null) {
        logger.log(Level.WARNING, "no component provided");
        return;
    }
    try {
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getAbsolutePath()));
        document.addAuthor("UJMP v" + UJMP.UJMPVERSION);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = new PdfGraphics2D(cb, width, height, new DefaultFontMapper());
        if (c instanceof CanRenderGraph) {
            ((CanRenderGraph) c).renderGraph(g2);
        } else {
            c.paint(g2);
        }
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        writer.close();
    } catch (Exception e) {
        logger.log(Level.WARNING, "could not save PDF file", e);
    }
}

From source file:pdfcompressor.PDFCompressor.java

public void outputPDF(String pathToOutput)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {
    com.itextpdf.text.Image itextImg;
    Document outDocument = new Document();
    outDocument.setMargins(0f, 0f, 0f, 0f);
    PdfWriter writer = PdfWriter.getInstance(outDocument, new FileOutputStream(pathToOutput));
    writer.setFullCompression();//from   www  . java 2s .c o  m
    writer.open();
    outDocument.open();
    int progress = 0;
    for (java.awt.Image img : getBuffedImg()) {
        itextImg = Image.getInstance(getImageByteArray(img, compressRate));
        itextImg.scaleToFit(595f, 842f);
        outDocument.add(itextImg);

        for (ProgressListener listener : saveListener) {
            listener.haveProgress(++progress, numOfPages);
        }
    }
    outDocument.close();
    writer.close();
    for (ProgressListener listener : saveListener) {
        listener.finished();
    }
}

From source file:pdfcompressor.PDFCompressor.java

public void getFileSize() throws DocumentException, IOException {
    com.itextpdf.text.Image itextImg;
    Document outDocument = new Document();
    outDocument.setMargins(0f, 0f, 0f, 0f);
    ByteArrayOutputStream memoryOutput = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(outDocument, memoryOutput);
    writer.setFullCompression();//  w w  w  .j av  a2s . c  o m
    writer.open();
    outDocument.open();
    for (java.awt.Image img : getBuffedImg()) {
        itextImg = Image.getInstance(getImageByteArray(img, compressRate));
        itextImg.scaleToFit(595f, 842f);
        outDocument.add(itextImg);
    }
    outDocument.close();
    writer.close();
    for (ProgressListener listener : sizeEstimateListener) {
        listener.finished(memoryOutput.toByteArray().length);
    }
}

From source file:pdfreporter.PDFGenTable.java

public static void pdfgentable() {
    Document document = new Document();
    try {//from   ww  w .ja  v  a 2  s .  c  o m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTableExample.pdf"));
        document.open();

        PdfPTable table = new PdfPTable(4); // 3 columns.
        table.setWidthPercentage(100); //Width 100%
        table.setSpacingBefore(10f); //Space before table
        table.setSpacingAfter(10f); //Space after table

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

        PdfPCell cell1 = new PdfPCell(new Paragraph("Nemam Pojma"));
        cell1.setBorderColor(BaseColor.BLACK);
        cell1.setPaddingLeft(10);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell2 = new PdfPCell(new Paragraph("Nemam pojma 2"));
        cell2.setBorderColor(BaseColor.BLACK);
        cell2.setPaddingLeft(10);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell3 = new PdfPCell(new Paragraph("Nemam pojma 3"));
        cell3.setBorderColor(BaseColor.BLACK);
        cell3.setPaddingLeft(10);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell4 = new PdfPCell(new Paragraph("Nemam pojma 4"));
        cell4.setBorderColor(BaseColor.BLACK);
        cell4.setPaddingLeft(10);
        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

        //To avoid having the cell border and the content overlap, if you are having thick cell borders
        //cell1.setUserBorderPadding(true);
        //cell2.setUserBorderPadding(true);
        //cell3.setUserBorderPadding(true);
        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);

        document.add(table);

        document.close();
        writer.close();
    } catch (FileNotFoundException | DocumentException e) {
    }
}

From source file:pidevhany.Controllers.GeneratePDF.java

public GeneratePDF(String ReponsesCorretes, String ReponsesFausses) throws FileNotFoundException, IOException {
    Document document = new Document();
    OutputStream outputStream = new FileOutputStream(
            new File("D:\\Esprit\\Atelier Java\\piweb\\pidevHany\\src\\pidevhany\\TestFile.pdf"));
    try {//from w w  w . ja  va  2  s  . c  o m
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        document.add(new Paragraph("Resultat du test :"));
        PdfPTable table = new PdfPTable(2); // 3 columns.
        table.setWidthPercentage(100); //Width 100%
        table.setSpacingBefore(10f); //Space before table
        table.setSpacingAfter(10f); //Space after table

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

        PdfPCell cell1 = new PdfPCell(new Paragraph(ReponsesCorretes));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPaddingLeft(10);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell2 = new PdfPCell(new Paragraph(ReponsesFausses));
        cell2.setBorderColor(BaseColor.GREEN);
        cell2.setPaddingLeft(10);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

        table.addCell(cell1);
        table.addCell(cell2);

        document.add(table);
        document.close();
        outputStream.close();
        writer.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:pkginterface.PayByCard.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    int year = Calendar.getInstance().get(Calendar.YEAR);
    String stryear = jTextField6.getText();
    int keyInYear = Integer.parseInt(stryear);
    int Month = Integer.parseInt(jTextField5.getText());

    if (jtf1.getText().equals("") || jTextField4.getText().equals("") || jTextField3.getText().equals("")
            || jTextField2.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "Please Fill Up All the Card Numbers");
        jtf1.setText("");
        jTextField4.setText("");
        jTextField3.setText("");
        jTextField2.setText("");

    } else if (Month > 12 || jTextField5.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "Invalid Month Detected! \nPlease Try Again!");
        jTextField5.setText("");
    } else if (keyInYear < year || jTextField6.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "Invalid Year Detected! \nPlease Try Again!");
        jTextField6.setText("");
    } else if (jTextField8.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "You Should Key In Card Holder Name!");
    } else {/*from ww  w.  j  a  va2s .  co m*/
        ResultSet trs = null;
        trs = tControl.getRecordWithTranstStatus("Pending");
        try {
            while (trs.next()) {

                TransactionDetails transID = tControl.getRecord(trs.getString(1));
                String id = transID.getTranstId();
                String status = "Paid";
                TransactionDetails setPaid = new TransactionDetails(status, id);
                tControl.setStatus(setPaid);

            }
        } catch (SQLException ex) {
            Logger.getLogger(Payment.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NumberFormatException e) {
        }

        String cardNum = jtf1.getText() + jTextField4.getText() + jTextField3.getText() + jTextField2.getText();
        String cardMonth = jTextField5.getText();
        String cardYear = jTextField6.getText();
        String cvv = jTextField7.getText();
        String cardHolder = jTextField8.getText();
        String tempStrCustCardID = null;
        CustcardDetails cd = cdControl.getLastRow();
        if (cd != null) {
            int tempIntCustCardID = Integer.parseInt(cd.getCustcardId());
            tempIntCustCardID += 1;

            if (tempIntCustCardID <= 9) {
                tempStrCustCardID = "0000" + tempIntCustCardID;
            } else if (tempIntCustCardID <= 99) {
                tempStrCustCardID = "000" + tempIntCustCardID;
            } else if (tempIntCustCardID <= 999) {
                tempStrCustCardID = "00" + tempIntCustCardID;
            } else if (tempIntCustCardID <= 9999) {
                tempStrCustCardID = "0" + tempIntCustCardID;
            } else if (tempIntCustCardID <= 99999) {
                tempStrCustCardID = "" + tempIntCustCardID;
            }
            cd = new CustcardDetails(tempStrCustCardID, cardNum, cardMonth, cardYear, cvv, cardHolder);
            cdControl.addRecord(cd);
        } else {
            tempStrCustCardID = "00001";
            cd = new CustcardDetails(tempStrCustCardID, cardNum, cardMonth, cardYear, cvv, cardHolder);
            cdControl.addRecord(cd);
        }

        int confirmDialog = JOptionPane.showConfirmDialog(rootPane,
                "Payment Completed!\nDo you want to generate receipt?", null, YES_NO_OPTION);

        //This part is to generate ticket
        Document document = new Document();
        Document document1 = new Document();
        BusDetailsControl bdControl = new BusDetailsControl();
        BusScheduleControl bsControl = new BusScheduleControl();
        CustTypeControl ctControl = new CustTypeControl();
        ResultSet rs = Payment.getForTandR();
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream("../" + Payment.getPaymentID() + ".pdf"));
            document.open();
            while (rs.next()) {
                BusScheduleDomain bs = bsControl.getRecord(rs.getString(2));
                BusDetailsDomain bd = bdControl.getRecord(bs.getBusId().getBusId());
                CustTypeDomain ct = ctControl.getRecord(rs.getString(3));
                tempD = bs.getDepartLocation();
                tempI = bs.getArriveLocation();
                document.add(new Paragraph("TICKET"));
                document.add(new Paragraph("Depart Location         : " + bs.getDepartLocation()));
                document.add(new Paragraph("Arrive Location          : " + bs.getArriveLocation()));
                document.add(new Paragraph("Depart Date              : " + bs.getScheduleDate()));
                document.add(new Paragraph("Depart Time              : " + bs.getScheduleTime()));
                document.add(new Paragraph("Customer Type         : " + ct.getCustType()));
                document.add(new Paragraph("Bus Plate Number    : " + bd.getBusPlateNum()));
                document.add(new Paragraph("Bus Type                  : " + bd.getBusType()));
                document.add(new Paragraph(
                        "Price                         : " + bs.getPrice() * ct.getDiscountRate()));
                document.add(new Paragraph(" " + " "));

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException ex) {
            Logger.getLogger(PayByCash.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (confirmDialog == JOptionPane.YES_OPTION) {
            PdfWriter writer1 = null;
            Date today = new Date();
            SimpleDateFormat dateF = new SimpleDateFormat("d-M-yyyy");
            SimpleDateFormat timeF = new SimpleDateFormat("HH:mm:ss");
            try {
                writer1 = PdfWriter.getInstance(document1,
                        new FileOutputStream("../" + Payment.getPaymentID() + " Receipt.pdf"));
                document1.open();
                document1.add(new Paragraph("                        SERI MEJU BUS Malaysia Sdn. Bhd."));
                document1.add(new Paragraph("                        L3-11, JLN LINGKARAN TENGAG LI,"));
                document1.add(new Paragraph("                               BANDAR TASIK SELATAN,"));
                document1.add(new Paragraph("                                57100 KUALA LUMPUR,"));
                document1.add(new Paragraph("                 WILAYAH PERSEKUTUAN KUALA LUMPUR,"));
                document1.add(new Paragraph("                                           MALAYSIA"));
                document1.add(new Paragraph(" "));
                document1.add(new Paragraph("RECEIPT"));
                document1.add(new Paragraph(
                        "---------------------------------------------------------------------------------------------"));
                document1.add(new Paragraph("Staff ID : " + new StaffMaintenance().getLoginUser()));
                document1.add(new Paragraph("Date : " + dateF.format(today)));
                document1.add(new Paragraph("Time : " + timeF.format(today)));
                document1.add(new Paragraph("From : " + tempD + ">>>>>>>>>>>>>>>>>>" + "To : " + tempI));
                document1.add(new Paragraph("Total : " + total));
                document1.add(new Paragraph("Payment Type : Cash "));
                document1.add(new Paragraph(
                        "---------------------------------------------------------------------------------------------"));
                document1.add(new Paragraph("Contact us : "));
                document1.add(new Paragraph("(Tel)1300-88-1111          (Email)serimejubusservice@gmail.com"));
                document1.close();
                JOptionPane.showMessageDialog(null,
                        "The Ticket(s) and Receipt have been stored to the Desktop of this PC.");
            } catch (FileNotFoundException ex) {
                Logger.getLogger(PayByCash.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(PayByCash.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            JOptionPane.showMessageDialog(null, "The Ticket(s) have been stored to the Desktop of this PC.");
        }

        document.close();
        writer.close();

        new MainMenu();
        dispose();
    }

}