Example usage for com.itextpdf.text Chunk Chunk

List of usage examples for com.itextpdf.text Chunk Chunk

Introduction

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

Prototype

private Chunk(final Float tabInterval, final boolean isWhitespace) 

Source Link

Document

Creates a tab Chunk.

Usage

From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java

License:Open Source License

private Element getSorteringDesc(Sortering sortering) {
    Paragraph def = new Paragraph(VALD_SORTERING_PA_TABELLEN, PdfExportConstants.FRONTPAGE_H2);

    Paragraph kolumn = new Paragraph();
    kolumn.add(new Chunk(SORTERING_KOLUMN, PdfExportConstants.FRONTPAGE_NORMAL_BOLD));

    Paragraph riktning = new Paragraph();
    riktning.add(new Chunk(SORTERING_RIKTNING, PdfExportConstants.FRONTPAGE_NORMAL_BOLD));

    if (sortering == null || StringUtil.isNullOrEmpty(sortering.getKolumn())) {
        kolumn.add(new Chunk(SORTERING_INGEN, PdfExportConstants.FRONTPAGE_NORMAL));
        riktning.add(new Chunk("-", PdfExportConstants.FRONTPAGE_NORMAL));
    } else {//www .  j  av  a2 s  .c  o m
        kolumn.add(new Phrase(sortering.getKolumn(), PdfExportConstants.FRONTPAGE_NORMAL));
        riktning.add(new Chunk(sortering.getOrder(), PdfExportConstants.FRONTPAGE_NORMAL));
    }
    def.add(kolumn);
    def.add(riktning);
    return def;

}

From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java

License:Open Source License

private Element getAntalDesc(Urval urval, int showing, int total) {
    Paragraph def = new Paragraph(ANTAL_VISAR_ANTAL_PAGAENDE_SJUKFALL, PdfExportConstants.FRONTPAGE_H2);

    Paragraph kolumn = new Paragraph();
    kolumn.add(new Chunk(ANTAL_EXPORTEN_VISAR, PdfExportConstants.FRONTPAGE_NORMAL_BOLD));
    kolumn.add(new Phrase(String.valueOf(showing), PdfExportConstants.FRONTPAGE_NORMAL));

    Paragraph riktning = new Paragraph();
    riktning.add(new Chunk(urval == Urval.ISSUED_BY_ME ? ANTAL_TOTALT_MINA : ANTAL_TOTALT_PA_ENHETEN,
            PdfExportConstants.FRONTPAGE_NORMAL_BOLD));
    riktning.add(new Chunk(String.valueOf(total), PdfExportConstants.FRONTPAGE_NORMAL));

    def.add(kolumn);//from w w  w  .  ja  v  a 2s .c o  m
    def.add(riktning);
    return def;

}

From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java

License:Open Source License

private Phrase getGrader(SjukfallEnhet is) {
    boolean first = true;
    Phrase grader = new Phrase();
    for (Integer grad : is.getGrader()) {
        if (!first) {
            grader.add(new Chunk(UNICODE_RIGHT_ARROW_SYMBOL + " ", unicodeCapableFont));
        }/*from  ww  w  .j av a2  s  .c om*/
        if (grad == is.getAktivGrad()) {
            grader.add(new Chunk(grad.toString() + "% ", PdfExportConstants.TABLE_CELL_BOLD));
        } else {
            grader.add(new Chunk(grad.toString() + "% ", PdfExportConstants.TABLE_CELL_NORMAL));
        }
        first = false;
    }
    return grader;
}

From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java

License:Open Source License

private Phrase getPersonnummerColumn(SjukfallEnhet is) {
    Phrase p = new Phrase();
    p.add(new Chunk(is.getPatient().getId() != null ? is.getPatient().getId() : "",
            PdfExportConstants.TABLE_CELL_NORMAL));
    return p;/*from w  w  w . j a va 2 s .  co  m*/
}

From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java

License:Open Source License

private Phrase getlangdText(SjukfallEnhet is) {
    Phrase p = new Phrase();
    p.add(new Chunk(String.format(FORMAT_ANTAL_DAGAR, is.getDagar()), PdfExportConstants.TABLE_CELL_NORMAL));
    return p;/*from   w  ww . j  ava  2s.co m*/
}

From source file:Servlets.ReportsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w  . j a  va2  s.co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        Paragraph pp;
        Paragraph palaglapgh, signParagraph, dateParagrapgh;
        Chunk chk;
        Paragraph underText;
        Chunk chuk1;
        Chunk chuk2;
        Paragraph regionText;
        String x;
        ResultSet dir;
        Paragraph regionTexts;
        String repLot;
        repLot = request.getParameter("report");

        String repNum = request.getParameter("ITLot");
        Paragraph newDate;
        response.setContentType("application/pdf");
        OutputStream out = response.getOutputStream();

        //Create document for pdf
        Document doc = new Document();

        //PDF writer to write into document
        PdfWriter docwriter = null;

        DecimalFormat df = new DecimalFormat("0.00");

        switch (repLot) {
        default:

            break;
        case "IT Report":

            //Copied code start from here
            try {
                // //file path
                //String path = "docs/" + "Name";
                docwriter = PdfWriter.getInstance(doc, out);
            } catch (DocumentException ex) {
                Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
            }

            //document header attributes
            doc.addAuthor("CHED CU");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Grant Monitor");
            doc.addTitle(repLot);
            doc.setPageSize(PageSize.A4.rotate()); //This sets page size to A4 and orientation to Landscape
            //doc.setPageSize(PageSize.A4);
            doc.setMargins(20f, 20f, 10f, 10f);

            //open document
            doc.open();

            //Creating a paragraphs and chunks
            pp = new Paragraph("Cocoa Health And Extension Division", forTitle);
            pp.setAlignment(Element.ALIGN_CENTER);

            palaglapgh = new Paragraph("(Cocobod)", bfBold12);
            palaglapgh.setAlignment(Element.ALIGN_CENTER);

            signParagraph = new Paragraph("Sign: ..............", bfBold12);
            signParagraph.setAlignment(Element.ALIGN_LEFT);

            dateParagrapgh = new Paragraph("Date: ...........", bfBold12);

            chk = new Chunk("From GIS Office, Accra", bfBold12);
            chk.setUnderline(.1f, -2f); // 0.1 thickness and -2 position
            underText = new Paragraph(chk);
            underText.setAlignment(Element.ALIGN_CENTER);

            chuk1 = new Chunk("Lot No:", forTitle2);
            chuk1.setUnderline(.1f, -2f);
            chuk2 = new Chunk(repNum.toUpperCase(), forTitle2);

            regionText = new Paragraph(repLot, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            x = "";
            dir = manager.PDFdemos(repNum);
            try {
                if (dir.next()) {
                    x = dir.getString(12);

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

            regionTexts = new Paragraph(x, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            //add the PDF table to the paragraph
            //palaglapgh.add(table);
            //Table Generation block
            regionText.add(reports(repNum, repLot, .25f));

            //SECTION TO ADD ELEMENTS TO PDF
            // add the paragraph to the document
            doc.add(pp);
            //doc.add(Chunk.NEWLINE);       //Adds a new blank line
            doc.add(palaglapgh);
            doc.add(underText);

            doc.add(chuk1);
            doc.add(chuk2);

            //Current Date and time insertion
            newDate = new Paragraph(date, bf12);
            newDate.setAlignment(Element.ALIGN_RIGHT);
            doc.add(newDate);
            doc.add(regionTexts);
            doc.add(regionText);

            doc.add(Chunk.NEWLINE); //Adds a new blank line
            doc.add(Chunk.NEWLINE);

            doc.add(signParagraph);
            doc.add(dateParagrapgh);

            //close the document
            doc.close();

            //close the writer
            docwriter.close();

            out.close();

            break;

        case "TR Report":

            //Copied code start from here
            try {
                // //file path
                //String path = "docs/" + "Name";
                docwriter = PdfWriter.getInstance(doc, out);
            } catch (DocumentException ex) {
                Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
            }

            //document header attributes
            doc.addAuthor("CHED CU");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Grant Monitor");
            doc.addTitle(repLot);
            //doc.setPageSize(PageSize.A4.rotate());      //This sets page size to A4 and orientation to Landscape
            doc.setPageSize(PageSize.A4);
            doc.setMargins(30f, 30f, 20f, 20f);

            //open document
            doc.open();

            //Creating a paragraphs and chunks
            pp = new Paragraph("Cocoa Health And Extension Division", forTitle);
            pp.setAlignment(Element.ALIGN_CENTER);

            palaglapgh = new Paragraph("(Cocobod)", bfBold12);
            palaglapgh.setAlignment(Element.ALIGN_CENTER);

            signParagraph = new Paragraph("Sign: ..............", bfBold12);
            signParagraph.setAlignment(Element.ALIGN_LEFT);

            dateParagrapgh = new Paragraph("Date: ...........", bfBold12);

            chk = new Chunk("From GIS Office, Accra", bfBold12);
            chk.setUnderline(.1f, -2f); // 0.1 thickness and -2 position
            underText = new Paragraph(chk);
            underText.setAlignment(Element.ALIGN_CENTER);

            chuk1 = new Chunk("Lot No:", forTitle2);
            chuk1.setUnderline(.1f, -2f); // 0.1 thickness and -2 position
            chuk2 = new Chunk(repNum.toUpperCase(), forTitle2);

            regionText = new Paragraph(repLot, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);

            x = "";
            dir = manager.PDFdemos(repNum);
            try {
                if (dir.next()) {
                    x = dir.getString(12);

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

            regionTexts = new Paragraph(x, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            //add the PDF table to the paragraph
            //palaglapgh.add(table);
            //Table Generation block
            regionText.add(reports(repNum, repLot, .1f));

            //SECTION TO ADD ELEMENTS TO PDF
            // add the paragraph to the document
            doc.add(pp);
            //doc.add(Chunk.NEWLINE);       //Adds a new blank line
            doc.add(palaglapgh);
            doc.add(underText);

            doc.add(chuk1);
            doc.add(chuk2);

            //Current Date and time insertion
            newDate = new Paragraph(date, bf12);
            newDate.setAlignment(Element.ALIGN_RIGHT);
            doc.add(newDate);
            doc.add(regionTexts);
            doc.add(regionText);

            doc.add(Chunk.NEWLINE); //Adds a new blank line
            doc.add(Chunk.NEWLINE);

            doc.add(signParagraph);
            doc.add(dateParagrapgh);

            //close the document
            doc.close();

            //close the writer
            docwriter.close();

            out.close();

            break;

        case "RP Report":

            //Copied code start from here
            try {
                // //file path
                //String path = "docs/" + "Name";
                docwriter = PdfWriter.getInstance(doc, out);
            } catch (DocumentException ex) {
                Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
            }

            //document header attributes
            doc.addAuthor("CHED CU");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Grant Monitor");
            doc.addTitle(repLot);
            doc.setPageSize(PageSize.A4.rotate()); //This sets page size to A4 and orientation to Landscape
            //doc.setPageSize(PageSize.A4);
            doc.setMargins(30f, 30f, 20f, 20f);

            //open document
            doc.open();

            //Creating a paragraphs and chunks
            pp = new Paragraph("Cocoa Health And Extension Division", forTitle);
            pp.setAlignment(Element.ALIGN_CENTER);

            palaglapgh = new Paragraph("(Cocobod)", bfBold12);
            palaglapgh.setAlignment(Element.ALIGN_CENTER);

            signParagraph = new Paragraph("Sign: ..............", bfBold12);
            signParagraph.setAlignment(Element.ALIGN_LEFT);

            dateParagrapgh = new Paragraph("Date: ...........", bfBold12);

            chk = new Chunk("From GIS Office, Accra", bfBold12);
            chk.setUnderline(.1f, -2f); // 0.1 thickness and -2 position
            underText = new Paragraph(chk);
            underText.setAlignment(Element.ALIGN_CENTER);

            chuk1 = new Chunk("RP Lot No:", forTitle2);
            chuk1.setUnderline(.1f, -2f);
            chuk2 = new Chunk(repNum.toUpperCase(), forTitle2);

            regionText = new Paragraph(repLot, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            x = "";
            dir = manager.PDFreplants(repNum);
            try {
                if (dir.next()) {
                    x = dir.getString(22);

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

            regionTexts = new Paragraph(x, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            //add the PDF table to the paragraph
            //palaglapgh.add(table);
            //Table Generation block
            regionText.add(RPreport(repNum));

            //SECTION TO ADD ELEMENTS TO PDF
            // add the paragraph to the document
            doc.add(pp);
            //doc.add(Chunk.NEWLINE);       //Adds a new blank line
            doc.add(palaglapgh);
            doc.add(underText);

            doc.add(chuk1);
            doc.add(chuk2);

            //Current Date and time insertion
            newDate = new Paragraph(date, bf12);
            newDate.setAlignment(Element.ALIGN_RIGHT);
            doc.add(newDate);
            doc.add(regionTexts);
            doc.add(regionText);

            doc.add(Chunk.NEWLINE); //Adds a new blank line
            doc.add(Chunk.NEWLINE);

            doc.add(signParagraph);
            doc.add(dateParagrapgh);

            //close the document
            doc.close();

            //close the writer
            docwriter.close();

            out.close();

            break;

        case "Rehab Report":

            //Copied code start from here
            try {
                // //file path
                //String path = "docs/" + "Name";
                docwriter = PdfWriter.getInstance(doc, out);
            } catch (DocumentException ex) {
                Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
            }

            //document header attributes
            doc.addAuthor("CHED CU");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Grant Monitor");
            doc.addTitle(repLot);
            doc.setPageSize(PageSize.A4.rotate()); //This sets page size to A4 and orientation to Landscape
            //doc.setPageSize(PageSize.A4);
            doc.setMargins(5f, 5f, 3f, 3f);

            //open document
            doc.open();

            //Creating a paragraphs and chunks
            pp = new Paragraph("Cocoa Health And Extension Division", forTitle);
            pp.setAlignment(Element.ALIGN_CENTER);

            palaglapgh = new Paragraph("(Cocobod)", bfBold12);
            palaglapgh.setAlignment(Element.ALIGN_CENTER);

            signParagraph = new Paragraph("Sign: ..............", bfBold12);
            signParagraph.setAlignment(Element.ALIGN_LEFT);

            dateParagrapgh = new Paragraph("Date: ...........", bfBold12);

            chk = new Chunk("Component 1 Rehabilitation Tree Removal Cost From GIS Office, Accra", bfBold12);
            chk.setUnderline(.1f, -2f); // 0.1 thickness and -2 position
            underText = new Paragraph(chk);
            underText.setAlignment(Element.ALIGN_CENTER);

            chuk1 = new Chunk("RP Lot No:", bfBold12);
            chuk1.setUnderline(.1f, -2f);
            chuk2 = new Chunk(repNum, bfBold12);

            regionText = new Paragraph(repLot, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            x = "";
            dir = manager.PDFRehab(repNum);//SHOULD BE CHANGED!!!!
            try {
                if (dir.next()) {
                    x = dir.getString(21);

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

            regionTexts = new Paragraph(x, forTitle2);
            regionText.setAlignment(Element.ALIGN_CENTER);
            //add the PDF table to the paragraph
            //palaglapgh.add(table);
            //Table Generation block
            regionText.add(reports(repNum));

            //SECTION TO ADD ELEMENTS TO PDF
            // add the paragraph to the document
            doc.add(pp);
            //doc.add(Chunk.NEWLINE);       //Adds a new blank line
            doc.add(palaglapgh);
            doc.add(underText);

            doc.add(chuk1);
            doc.add(chuk2);

            //Current Date and time insertion
            newDate = new Paragraph(date, bf12);
            newDate.setAlignment(Element.ALIGN_RIGHT);
            doc.add(newDate);
            doc.add(regionTexts);
            doc.add(regionText);

            doc.add(Chunk.NEWLINE); //Adds a new blank line
            doc.add(Chunk.NEWLINE);

            doc.add(signParagraph);
            doc.add(dateParagrapgh);

            //close the document
            doc.close();

            //close the writer
            docwriter.close();

            out.close();

            //Copied CODES
            break;

        }

    } catch (DocumentException ex) {
        Logger.getLogger(ReportsServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:src.servlets.ManageAdmin.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  w ww  .  j a va2  s. co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Map m = request.getParameterMap();
    if (m.containsKey("GetPDF")) {
        try {
            String Report = getServletContext().getRealPath("") + "admin\\PDF_Report.pdf";

            FileOutputStream file = new FileOutputStream(Report);
            Document document = new Document();
            document.addAuthor("K00140908");
            PdfWriter.getInstance(document, file);
            ///////////////////////ADDING THE FILES TO PDF////////////////////
            //Inserting Image in PDF
            String uploadPath = getServletContext().getRealPath("") + "images\\logo.gif";

            Image img = Image.getInstance(uploadPath);

            img.scaleAbsolute(120f, 60f);// width,height of image in float

            //            Inserting Title in PDF  ORIGINAL
            //            Font fontTitle=new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.WHITE);
            //            Chunk title=new Chunk("PDF GENERATION in Java with iText", fontTitle);
            //            title.setBackground(new BaseColor(255,102,0), 1f, 1f, 1f, 3f);
            //            title.setLineHeight(30f);
            //            title.setUnderline(BaseColor.BLACK,5f,0.5f,2f,0.5f,PdfContentByte.LINE_CAP_ROUND);
            Font fontTitle = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);
            Chunk title = new Chunk("Lit Realty System Report", fontTitle);
            title.setLineHeight(30f);

            //Inserting Table in PDF
            PdfPTable table = new PdfPTable(3);
            table.setWidthPercentage(100); // Sets the width percentage that the table will occupy in the page
            table.setSpacingAfter(10f);
            table.setSpacingBefore(15f);
            table.setWidths(new float[] { 2f, 2f, 2f }); // Sets relative width of table

            Font fontHeader = new Font(Font.FontFamily.HELVETICA, 15, Font.BOLD, BaseColor.BLUE);
            PdfPCell headercell = new PdfPCell(new Phrase("Property Photo", fontHeader)); // Creates new cell in table
            headercell.setBackgroundColor(new BaseColor(230, 230, 243));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            headercell = new PdfPCell(new Phrase("Property ID", fontHeader));
            headercell.setBackgroundColor(new BaseColor(233, 233, 233));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            headercell = new PdfPCell(new Phrase("Price", fontHeader));
            headercell.setBackgroundColor(new BaseColor(233, 233, 233));
            headercell.setPaddingBottom(5f);
            table.addCell(headercell);

            PdfPCell cell1 = new PdfPCell(img, false);

            table.addCell(cell1);
            table.addCell("134000");
            table.addCell("213445");
            table.addCell("134000");

            //Inserting List
            com.itextpdf.text.List list = new com.itextpdf.text.List(true, 30);
            list.add(new ListItem("Example1"));
            list.add(new ListItem("Example2"));
            list.add(new ListItem("Example3"));

            //Adding elements into PDF Document
            document.open();

            document.add(img);
            document.add(title);

            document.add(Chunk.NEWLINE);
            document.add(table);

            document.newPage();
            document.add(new Chunk("List of Examples").setUnderline(+1f, -5f));
            document.add(list);

            document.newPage();
            document.add(new Chunk("List of Examples").setUnderline(+1f, -5f));
            document.add(list);

            document.newPage();
            document.add(new Chunk("List of Properts By Agent X").setUnderline(+1f, -5f));
            //////////////////////GET Propertys From Entity///////////////
            List<Properties> allPropertiesList = PropertiesDB.getAllProperties();

            PdfPTable propertyTable = new PdfPTable(3);
            PdfPCell propertyHeadingcell1 = new PdfPCell(new Phrase("Photo"));
            PdfPCell propertyHeadingcell2 = new PdfPCell(new Phrase("Property ID"));
            PdfPCell propertyHeadingcell3 = new PdfPCell(new Phrase("Price"));

            propertyHeadingcell1.setBorder(Rectangle.NO_BORDER);
            propertyHeadingcell2.setBorder(Rectangle.NO_BORDER);
            propertyHeadingcell3.setBorder(Rectangle.NO_BORDER);

            propertyTable.addCell(propertyHeadingcell1);
            propertyTable.addCell(propertyHeadingcell2);
            propertyTable.addCell(propertyHeadingcell3);

            document.add(Chunk.NEWLINE);

            String uploadPathforPropertyPhoto = getServletContext().getRealPath("")
                    + "images\\properties\\thumbnails\\";

            Image propertyThumbnail;

            img.scaleAbsolute(120f, 60f);// width,height of image in float

            for (Properties anProperty : allPropertiesList) {
                propertyThumbnail = Image.getInstance(uploadPathforPropertyPhoto + anProperty.getPhoto());
                PdfPCell propertycell1 = new PdfPCell(propertyThumbnail, false);
                propertycell1.setPaddingBottom(20);
                PdfPCell propertycell2 = new PdfPCell(new Phrase(anProperty.getListingNum().toString()));
                PdfPCell propertycell3 = new PdfPCell(new Phrase(anProperty.getPrice().toString()));

                propertycell1.setBorder(Rectangle.NO_BORDER);
                propertycell2.setBorder(Rectangle.NO_BORDER);
                propertycell3.setBorder(Rectangle.NO_BORDER);

                propertyTable.addCell(propertycell1);
                propertyTable.addCell(propertycell2);
                propertyTable.addCell(propertycell3);

            }
            document.add(Chunk.NEWLINE);
            document.add(propertyTable);
            //////////////////////GET Propertys From Entity///////////////

            document.close();
            file.close();

            System.out.println("Pdf created successfully ! :)");

            String filePath = Report;
            File downloadFile = new File(filePath);
            FileInputStream inStream = new FileInputStream(downloadFile);

            // if you want to use a relative path to context root:
            String relativePath = getServletContext().getRealPath("");
            System.out.println("relativePath = " + relativePath);

            // obtains ServletContext
            ServletContext context = getServletContext();

            // gets MIME type of the file
            String mimeType = context.getMimeType(filePath);
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }
            System.out.println("MIME type: " + mimeType);

            // modifies response
            response.setContentType(mimeType);
            response.setContentLength((int) downloadFile.length());

            // forces download
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
            response.setHeader(headerKey, headerValue);

            // obtains response's output stream
            OutputStream outStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }

            inStream.close();
            outStream.close();
            /////////////////

            processRequest(request, response);
        } catch (DocumentException ex) {
            Logger.getLogger(ManageAdmin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ui.MainDriver.java

public void printTicket() {

    for (int t = 0; t < currentTicketList.size(); t++) {
        String myCodeText = currentTicketList.get(t).getTicketID() + " %0A "
                + currentTicketList.get(t).getBooking().getBookingID() + " - "
                + currentTicketList.get(t).getSchedule().getRoute().getDestination() + " - "
                + currentTicketList.get(t).getPassengerName() + " - "
                + currentTicketList.get(t).getPassengerContactNo() + " - "
                + currentTicketList.get(t).getSeatNo();
        String filePath = "src/ticket/" + currentTicketList.get(t).getTicketID() + ".png";
        int size = 165;
        String fileType = "png";
        File myFile = new File(filePath);
        try {//w  ww  .  j a  v a2  s  . c  o  m
            Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix byteMatrix = qrCodeWriter.encode(myCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
            int width = byteMatrix.getWidth();
            BufferedImage image = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB);
            image.createGraphics();

            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, width);
            graphics.setColor(Color.BLACK);

            for (int i = 0; i < width; i++)
                for (int j = 0; j < width; j++)
                    if (byteMatrix.get(i, j))
                        graphics.fillRect(i, j, 1, 1);

            ImageIO.write(image, fileType, myFile);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Document document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("src/ticketpdf/" + currentTicketList.get(t).getTicketID() + "DATE"
                            + new SimpleDateFormat("ddMMyyHHmmss").format(new Date()) + ".pdf"));
            document.open();

            Phrase p1 = new Phrase();
            Paragraph para = new Paragraph();
            com.itextpdf.text.Font font = new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.COURIER,
                    32, com.itextpdf.text.Font.BOLDITALIC);
            com.itextpdf.text.Font timesRomanfont = new com.itextpdf.text.Font(
                    com.itextpdf.text.Font.FontFamily.TIMES_ROMAN, 16, com.itextpdf.text.Font.BOLD);
            Chunk cc = new Chunk("#################################################################",
                    timesRomanfont);
            p1.add(cc);
            p1.add(Chunk.NEWLINE);
            p1.add(Chunk.NEWLINE);
            Chunk c = new Chunk("CJH BUS EXPRESS SDN. BHD.", font);
            p1.add(c);
            p1.add(Chunk.NEWLINE);
            p1.add(Chunk.NEWLINE);
            p1.add(cc);
            para.setAlignment(Element.ALIGN_CENTER);
            para.add(p1);
            document.add(para);

            Image image1 = Image.getInstance(filePath);
            document.add(image1);

            Phrase phrase = new Phrase();
            Paragraph paragraph = new Paragraph();

            Chunk c1 = new Chunk("Ticket ID                       : " + currentTicketList.get(t).getTicketID(),
                    timesRomanfont);
            phrase.add(c1);
            phrase.add(Chunk.NEWLINE);

            Chunk c2 = new Chunk(
                    "Booking ID                    : " + currentTicketList.get(t).getBooking().getBookingID(),
                    timesRomanfont);
            phrase.add(c2);
            phrase.add(Chunk.NEWLINE);

            Chunk c3 = new Chunk(
                    "Destination                    : "
                            + currentTicketList.get(t).getSchedule().getRoute().getDestination(),
                    timesRomanfont);
            phrase.add(c3);
            phrase.add(Chunk.NEWLINE);

            Chunk cDate = new Chunk(
                    "Departure Date             : " + currentTicketList.get(t).getSchedule().getDepartureDate(),
                    timesRomanfont);
            phrase.add(cDate);
            phrase.add(Chunk.NEWLINE);

            Chunk cTime = new Chunk(
                    "Departure Time            : " + currentTicketList.get(t).getSchedule().getDepartureTime(),
                    timesRomanfont);
            phrase.add(cTime);
            phrase.add(Chunk.NEWLINE);

            Chunk c4 = new Chunk("Passenger Name            : " + currentTicketList.get(t).getPassengerName(),
                    timesRomanfont);
            phrase.add(c4);
            phrase.add(Chunk.NEWLINE);

            Chunk c5 = new Chunk("Passenger Contact No   : " + currentTicketList.get(t).getPassengerContactNo(),
                    timesRomanfont);
            phrase.add(c5);
            phrase.add(Chunk.NEWLINE);

            Chunk c6 = new Chunk("Seat No                           : " + currentTicketList.get(t).getSeatNo(),
                    timesRomanfont);
            phrase.add(c6);
            phrase.add(Chunk.NEWLINE);

            if (reprintCounter == true) {
                Chunk cR = new Chunk("--- REPRINT ---", timesRomanfont);
                phrase.add(cR);
                phrase.add(Chunk.NEWLINE);
            }

            Chunk c7 = new Chunk("#################################################################",
                    timesRomanfont);
            phrase.add(c7);

            paragraph.add(phrase);
            document.add(paragraph);

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

        //            try {
        //                PdfReader reader = new PdfReader("src/ticketpdf/" + currentTicketList.get(t).getTicketID() + "DATE" + new SimpleDateFormat("ddMMyyHHmmss").format(new Date()) + ".pdf");
        //                int n = reader.getNumberOfPages();
        //                PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("src/ticketpdfWM/" + currentTicketList.get(t).getTicketID() + "WMDATE" + new SimpleDateFormat("ddMMyyHHmmss").format(new Date()) + ".pdf"));
        //                int i = 0;
        //                PdfContentByte under;
        //                Image img = Image.getInstance("src/images/b1.jpg");
        //                img.setAbsolutePosition(200, 400);
        //                while (i < n) {
        //                  i++;
        //                  under = stamp.getUnderContent(i);
        //                  under.addImage(img);
        //                }
        //                stamp.close();
        //            }
        //            catch (Exception de) {
        //                de.printStackTrace();
        //            }
    }
}

From source file:util.ImageExample.java

public ImageExample(Calendar date, int settings, ArrayList<String> courses, String time, String eventAddress,
        int totalPrice, String comments, boolean kunde) throws Exception {
    this.date = date;
    this.settings = settings;
    this.courses = courses;
    this.time = time;
    this.eventAddress = eventAddress;
    this.totalPrice = totalPrice;
    this.comments = comments;
    this.fileName = "";
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.getAllFonts();//from   w ww.  j av  a2 s.  c om
    FontFactory.register("C:/Windows/Fonts/ARLRDBD.TTF", "Arial Rounded");
    Font font = FontFactory.getFont("Arial Rounded", 22, Font.NORMAL, new BaseColor(51, 102, 102));
    Document document = new Document();

    System.out.println("Pdf creation startet");
    try {
        if (kunde) {
            fileName = "grill" + new SimpleDateFormat("dd. MMMMM yyyy hhmm").format(date.getTime()) + ".pdf";
        } else {
            fileName = "grill" + new SimpleDateFormat("dd. MMMMM yyyy hhmm").format(date.getTime())
                    + "Prisliste.pdf";
        }

        FileOutputStream file = new FileOutputStream(new File("C:/Users/Mark/Desktop", fileName));
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();

        Image img = Image.getInstance("src/pictures/cirkles.png");
        img.scaleToFit(277, 277);
        img.setAbsolutePosition(40, PageSize.A4.getHeight() - img.getHeight());
        document.add(img);
        Chunk chunk = new Chunk("Grillmester 'Frankie'", font);
        chunk.setCharacterSpacing(3);
        Paragraph header = new Paragraph(chunk);
        header.setAlignment(Element.ALIGN_RIGHT);
        header.setSpacingBefore(15);
        document.add(header);
        Paragraph title = new Paragraph(
                "Tilbud angende d. " + new SimpleDateFormat("dd. MMMMM yyyy").format(date.getTime()) + ".",
                new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD));
        title.setAlignment(Element.ALIGN_LEFT);
        title.setIndentationLeft(235);
        title.setSpacingBefore(100);
        title.setLeading(17);
        document.add(title);
        Paragraph subtitle = new Paragraph("(Arrangement til " + settings + " personer).",
                new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.ITALIC));
        subtitle.setAlignment(Element.ALIGN_LEFT);
        subtitle.setIndentationLeft(235);
        subtitle.setLeading(17);
        document.add(subtitle);
        Paragraph body = new Paragraph("\n\nDer er aftalt:\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 18));
        body.setAlignment(Element.ALIGN_LEFT);
        body.setIndentationLeft(235);
        body.setLeading(17);
        for (String course : courses) {
            body.add(course + "\n\n");
        }
        body.add("\nServeres klokken " + time + " i " + eventAddress + ".");
        document.add(body);
        Paragraph ending = new Paragraph("\n\n\nPris: " + totalPrice + ",-kr.",
                new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD));
        ending.setAlignment(Element.ALIGN_LEFT);
        ending.setIndentationLeft(235);
        ending.setLeading(17);
        document.add(ending);
        if (!comments.equals("null")) {
            if (!comments.equals("")) {
                Paragraph comment = new Paragraph("\n\nKommentarer\n" + comments,
                        new Font(Font.FontFamily.TIMES_ROMAN, 18));
                comment.setAlignment(Element.ALIGN_LEFT);
                comment.setIndentationLeft(235);
                comment.setLeading(17);
                document.add(comment);
            }
        }

        Image footerImg = Image.getInstance("src/pictures/grillmester.png");
        footerImg.scaleToFit(210, 210);
        footerImg.setAbsolutePosition(40, 40);
        document.add(footerImg);

        Image img2 = Image.getInstance("src/pictures/Contact.png");
        img2.scaleToFit(250, 250);
        img2.setAbsolutePosition(20, PageSize.A4.getHeight() - img.getHeight() - 250);
        document.add(img2);

        document.close();

        System.out.println("Pdf finish");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getLocalizedMessage());
    }
}

From source file:Utility.PDFDemo.java

public void cretePDF(String name, String rpor) throws FileNotFoundException {

    try {//  w  ww .  jav  a 2s  .  c o m

        //Create document for pdf
        Document doc = new Document();

        //PDF writer to write into document
        PdfWriter docwriter = null;

        DecimalFormat df = new DecimalFormat("0.00");

        try {
            // //file path
            //String path = "docs/" + name;
            docwriter = PdfWriter.getInstance(doc, new FileOutputStream(rpor + ".pdf"));
        } catch (DocumentException ex) {
            Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
        }

        //document header attributes
        doc.addAuthor("CHED CU");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("Grant Monitor");
        doc.addTitle(rpor);
        doc.setPageSize(PageSize.A4.rotate()); //This sets page size to A4 and orientation to Landscape
        //doc.setPageSize(PageSize.A4);
        doc.setMargins(30f, 30f, 20f, 20f);

        //open document
        doc.open();

        //Creating a paragraphs and chunks
        Paragraph pp = new Paragraph("Cocoa Health And Extension", forTitle);
        pp.setAlignment(Element.ALIGN_CENTER);

        Paragraph palaglapgh = new Paragraph("(Cocobod)", bfBold12);
        palaglapgh.setAlignment(Element.ALIGN_CENTER);

        Chunk chk = new Chunk("From GIS Office, Accra", bfBold12);
        chk.setUnderline(.1f, -2f); // 0.1 thickness and -2 position
        Paragraph underText = new Paragraph(chk);
        underText.setAlignment(Element.ALIGN_CENTER);

        Chunk chuk1 = new Chunk("Lot No:", bfBold12);
        chuk1.setUnderline(.1f, -2f);
        Chunk chuk2 = new Chunk(name, bfBold12);

        Paragraph regionText = new Paragraph(rpor, bfBold12);
        regionText.setAlignment(Element.ALIGN_CENTER);
        String rporx = "";
        //            ResultSet dir = manager.PDFdemos(name);
        //            try {
        //                if (dir.next()) {
        //                    rporx = dir.getString(12);
        //
        //                }
        //            } catch (SQLException ex) {
        //                Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
        //            }

        Paragraph regionTexts = new Paragraph(rporx, bfBold12);
        regionText.setAlignment(Element.ALIGN_CENTER);
        //add the PDF table to the paragraph
        //palaglapgh.add(table);
        //Table Generation block
        regionText.add(reports());

        //SECTION TO ADD ELEMENTS TO PDF
        // add the paragraph to the document
        doc.add(pp);
        //doc.add(Chunk.NEWLINE);       //Adds a new blank line
        doc.add(palaglapgh);
        doc.add(underText);

        doc.add(chuk1);
        doc.add(chuk2);

        //Current Date and time insertion
        Paragraph newDate = new Paragraph(new Date().toString(), bf12);
        newDate.setAlignment(Element.ALIGN_RIGHT);
        doc.add(newDate);
        doc.add(regionTexts);
        doc.add(regionText);

        //close the document
        doc.close();

        //close the writer
        docwriter.close();

    } catch (DocumentException ex) {
        Logger.getLogger(PDFDemo.class.getName()).log(Level.SEVERE, null, ex);
    }

}