Example usage for com.itextpdf.text Image getInstance

List of usage examples for com.itextpdf.text Image getInstance

Introduction

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

Prototype

public static Image getInstance(final Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:pdfextract.ExtractInfo.java

public void extractImagesInfo() {
    try {//w  w  w . ja v  a 2s .c om
        PdfReader chartReader = new PdfReader("vv.pdf");
        for (int i = 0; i < chartReader.getXrefSize(); i++) {
            PdfObject pdfobj = chartReader.getPdfObject(i);
            if (pdfobj != null && pdfobj.isStream()) {
                PdfStream stream = (PdfStream) pdfobj;
                PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
                //System.out.println("Stream subType: " + pdfsubtype); 
                if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
                    byte[] image = PdfReader.getStreamBytesRaw((PRStream) stream);
                    Image imageObject = Image.getInstance(image);
                    System.out.println("Resolution" + imageObject.getDpiX());
                    System.out.println("Height" + imageObject.getHeight());
                    System.out.println("Width" + imageObject.getWidth());

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

}

From source file:pdfgen.pdf_generation_try5.java

public void AllFunctions(String realpath, String sample_pdf_path) {

    try {/* www.ja  v  a  2  s .  c o m*/
        INPUTFILE = sample_pdf_path;
        // System.out.println("Inputfile: "+INPUTFILE);
        Document document = new Document();
        //PdfWriter.getInstance(document, new FileOutputStream(OUTPUTFILE));
        OUTPUTFILE = filepath(realpath);
        //System.out.println("Outputfile"+OUTPUTFILE);
        PdfReader reader = new PdfReader(INPUTFILE);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(OUTPUTFILE));
        //     writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);

        document.open();
        addTitlePage(document);

        int n = reader.getNumberOfPages();
        PdfImportedPage page;
        // Go through all pages
        for (int i = 1; i <= n; i++) {

            page = writer.getImportedPage(reader, i);
            Image instance = Image.getInstance(page);
            instance.setAlignment(Element.ALIGN_LEFT);
            //  document.add(instance);

        }

        addMetaData(document);
        pdfReaderFunction(reader);
        AddParagraph(document);
        //    addContent(document);
        // scaleImage();
        qr_generator(document);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:PDFIMG.IMAGEStoPDF.java

public static void convertToIMG(String[] RESOURCES, String result, String path, int s)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {
    System.out.println(":)");

    // step 1//from   www. j  a  v a 2  s .c  o  m
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
    // step 3
    document.open();
    // step 4
    // Adding a series of images
    Image img;
    System.out.println(":) :)");
    for (String image : RESOURCES) {
        System.out.println(image);

        img = Image.getInstance(path + image);

        document.setPageSize(img);
        document.newPage();
        img.setAbsolutePosition(0, 0);
        document.add(img);
        System.out.println(":(");
    }
    System.out.println(":) :) :) Pdf is outo");
    // step 5
    document.close();

    if (s == 1) {
        JOptionPane.showMessageDialog(null, "Converted Successfully");
        //JOptionPane.showMessageDialog(null, "Finished\nFile save in :\nC:\\DjVu++Task\\ImagestoPDF\\"+RESOURCES[0].substring(0,RESOURCES[0].lastIndexOf("."))+".pdf");
    }
}

From source file:pdfTemplates.Drillpdf.java

public void PrintPressed(jugada selectedPlay, File fileSavePath) throws DocumentException, IOException {

    // step 1//from  w w  w . ja v a2 s  . c  o m
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(fileSavePath.getPath()));
    // step 3

    document.open();
    // step 4
    document.add(new Paragraph(messages.getString("Name") + ":  " + selectedPlay.getNombreJugada()));
    document.add(new Paragraph(messages.getString("Type") + ":  " + selectedPlay.getTipoJugada()));
    document.add(new Paragraph(messages.getString("Subtype") + ": " + selectedPlay.getSubtipoJugada()));

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

    int contador = 1;
    while (contador < selectedPlay.getContadorJugada() + 1) {

        document.add(new Paragraph(messages.getString("Diagram") + " " + contador));
        document.add(new Paragraph(" "));

        Image image2 = Image.getInstance(selectedPlay.getNombreJugada() + "-" + selectedPlay.getTipoJugada()
                + "-" + selectedPlay.getSubtipoJugada() + "_" + contador);
        image2.scalePercent(50);

        PdfPTable table = new PdfPTable(2);

        table.addCell(image2);
        table.addCell(textPdf.textPdf(contador, selectedPlay.getDescripcionJugada(),
                selectedPlay.getContadorJugada()));
        document.add(table);

        contador++;

    }

    document.close();

}

From source file:pl.marcinmilkowski.hocrtopdf.Main.java

License:Open Source License

/**
 * @param args/*from w w w  .jav  a 2  s .  c  o  m*/
 */
public static void main(String[] args) {
    try {
        if (args.length < 1 || args[0] == "--help" || args[0] == "-h") {
            System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n"
                    + "\n" + "Converts hOCR files into PDF\n" + "\n"
                    + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n");
            if (args.length < 1)
                System.exit(-1);
            else
                System.exit(0);
        }
        URL inputHOCRFile = null;
        FileOutputStream outputPDFStream = null;
        try {
            File file = new File(args[0]);
            inputHOCRFile = file.toURI().toURL();
        } catch (MalformedURLException e) {
            System.out.println("The first parameter has to be a valid file.");
            System.out.println("We got an error: " + e.getMessage());
            System.exit(-1);
        }
        try {
            outputPDFStream = new FileOutputStream(args[1]);
        } catch (FileNotFoundException e) {
            System.out.println("The second parameter has to be a valid URL");
            System.exit(-1);
        }

        // The resolution of a PDF file (using iText) is 72pt per inch
        float pointsPerInch = 72.0f;

        // Using the jericho library to parse the HTML file
        Source source = new Source(inputHOCRFile);

        int pageCounter = 1;

        Document pdfDocument = null;
        PdfWriter pdfWriter = null;
        PdfContentByte cb = null;
        RandomAccessFileOrArray ra = null;

        // Find the tag of class ocr_page in order to load the scanned image
        StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE);
        while (pageTag != null) {
            int prevPos = pageTag.getEnd();
            Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
            Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
            if (!imageMatcher.find()) {
                System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
                System.exit(-1);
            }
            // Load the image
            Image pageImage = null;
            try {
                File file = new File(imageMatcher.group(1));
                pageImage = Image.getInstance(file.toURI().toURL());
            } catch (MalformedURLException e) {
                System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1)
                        + ", aborting.");
                System.exit(-1);
            }
            if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might
                                                                      // be
                                                                      // multipage
                                                                      // tiff!
                File file = new File(imageMatcher.group(1));
                if (pageCounter == 1 || ra == null) {
                    ra = new RandomAccessFileOrArray(file.toURI().toURL());
                }
                int nPages = TiffImage.getNumberOfPages(ra);
                if (nPages > 0 && pageCounter <= nPages) {
                    pageImage = TiffImage.getTiffImage(ra, pageCounter);
                }
            }
            int dpiX = pageImage.getDpiX();
            if (dpiX == 0) { // for images that don't set the resolution we assume
                             // 300 dpi
                dpiX = 300;
            }
            int dpiY = pageImage.getDpiY();
            if (dpiY == 0) { // as above for dpiX
                dpiY = 300;
            }
            float dotsPerPointX = dpiX / pointsPerInch;
            float dotsPerPointY = dpiY / pointsPerInch;
            float pageImagePixelHeight = pageImage.getHeight();
            if (pdfDocument == null) {
                pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
                pdfDocument.open();
                // Put the text behind the picture (reverse for debugging)
                // cb = pdfWriter.getDirectContentUnder();
                cb = pdfWriter.getDirectContent();
            } else {
                pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfDocument.newPage();
            }
            // first define a standard font for our text
            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font defaultFont = new Font(base, 8);
            // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,
            // CMYKColor.BLACK);

            cb.setHorizontalScaling(1.0f);

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
            pageImage.setAbsolutePosition(0, 0);
            // Put the image in front of the text (reverse for debugging)
            // pdfWriter.getDirectContent().addImage(pageImage);
            pdfWriter.getDirectContentUnder().addImage(pageImage);

            // In order to place text behind the recognised text snippets we are
            // interested in the bbox property
            Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
            // This pattern separates the coordinates of the bbox property
            Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
            // Only tags of the ocr_line class are interesting
            StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            while (ocrTag != null) {
                prevPos = ocrTag.getEnd();
                if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                    net.htmlparser.jericho.Element lineElement = ocrTag.getElement();
                    Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
                    if (bboxMatcher.find()) {
                        // We found a tag of the ocr_line class containing a bbox property
                        Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                        bboxCoordinateMatcher.find();
                        int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                                Integer.parseInt((bboxCoordinateMatcher.group(2))),
                                Integer.parseInt((bboxCoordinateMatcher.group(3))),
                                Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                        String line = lineElement.getContent().getTextExtractor().toString();
                        float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                        float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                        // Put the text into the PDF
                        cb.beginText();
                        // Comment the next line to debug the PDF output (visible Text)
                        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                        // height
                        cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1));
                        // width
                        cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false));
                        cb.moveText((coordinates[0] / dotsPerPointX),
                                ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                        cb.showText(line);
                        cb.endText();
                        cb.setHorizontalScaling(1.0f);
                    }
                } else {
                    if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                        pageCounter++;
                        pageTag = ocrTag;
                        break;
                    }
                }
                ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            }
            if (ocrTag == null) {
                pdfDocument.close();
                break;
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:presentation.frmReportForm.java

private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateActionPerformed
    Date dateNow = new Date();
    SimpleDateFormat df = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss");

    System.out.println(dtcMonthChooser.getMonth());
    System.out.println(dtcYearChooser.getYear());

    if (radInMonth.isSelected()) {
        List<Transfer> transferList = new ArrayList<>();

        transferList = empObj.searchRecordByMonth(dtcMonthChooser.getMonth() + 1, dtcYearChooser.getYear());

        Document document = new Document();
        try {// w ww .j a  v a 2  s .  c o m
            Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

            String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            Image imageLogo = Image
                    .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
            imageLogo.setAbsolutePosition(20, 750f);
            document.add(imageLogo);

            Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
            titlePara.setAlignment(Element.ALIGN_CENTER);
            titlePara.setSpacingAfter(5);
            document.add(titlePara);

            Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
            creditPara.setAlignment(Element.ALIGN_CENTER);
            creditPara.setSpacingAfter(10);
            document.add(creditPara);

            Paragraph slashPara = new Paragraph(
                    "Transfer records at " + (dtcMonthChooser.getMonth() + 1) + "/" + dtcYearChooser.getYear(),
                    FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
            slashPara.setSpacingAfter(40);
            slashPara.setAlignment(Element.ALIGN_CENTER);
            document.add(slashPara);

            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);

            Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
            Paragraph paragraphCellHeading = new Paragraph("Report", font);

            PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
            BaseColor myColor = WebColors.getRGBColor("#41a5c2");
            cellHeading.setColspan(5);
            cellHeading.setBackgroundColor(myColor);
            cellHeading.setFixedHeight(30.3f);
            cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellHeading);

            Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

            PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
            cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle1);
            PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
            cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle2);
            PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
            cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle3);
            PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
            cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle4);
            PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
            cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitleStatus);

            int cellColorCheck = 1;
            for (Transfer e : transferList) {
                PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                if (cellColorCheck % 2 == 1) {
                    cellBody1.setBackgroundColor(BaseColor.ORANGE);
                    cellBody2.setBackgroundColor(BaseColor.ORANGE);
                    cellBody3.setBackgroundColor(BaseColor.ORANGE);
                    cellBody4.setBackgroundColor(BaseColor.ORANGE);
                    cellBody5.setBackgroundColor(BaseColor.ORANGE);
                }
                table.addCell(cellBody1);
                table.addCell(cellBody2);
                table.addCell(cellBody3);
                table.addCell(cellBody4);
                table.addCell(cellBody5);
                cellColorCheck++;
            }

            document.add(table);

            JOptionPane.showMessageDialog(this, "Report saved");

            if (Desktop.isDesktopSupported()) {
                File reportFile = new File(fileName);
                Desktop.getDesktop().open(reportFile);
                ;
            }

            document.close();
        } catch (DocumentException | FileNotFoundException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (radInDateRange.isSelected()) {
        try {
            List<Transfer> transferList = new ArrayList<>();

            java.sql.Date fromDateSql = formatDateForSearching(dtcFromDate.getDate());
            java.sql.Date toDateSql = formatDateForSearching(dtcToDate.getDate());
            transferList = empObj.searchRecordByDate(fromDateSql, toDateSql);

            Document document = new Document();
            try {
                Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

                String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
                PdfWriter.getInstance(document, new FileOutputStream(fileName));

                document.open();

                Image imageLogo = Image
                        .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
                imageLogo.setAbsolutePosition(20, 750f);
                document.add(imageLogo);

                Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
                titlePara.setAlignment(Element.ALIGN_CENTER);
                titlePara.setSpacingAfter(5);
                document.add(titlePara);

                Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                        FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
                creditPara.setAlignment(Element.ALIGN_CENTER);
                creditPara.setSpacingAfter(10);
                document.add(creditPara);

                SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
                String fromDate = df2.format(dtcFromDate.getDate());
                String toDate = df2.format(dtcToDate.getDate());

                Paragraph slashPara = new Paragraph("Transfer records from " + fromDate + " to " + toDate,
                        FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
                slashPara.setSpacingAfter(40);
                slashPara.setAlignment(Element.ALIGN_CENTER);
                document.add(slashPara);

                PdfPTable table = new PdfPTable(5);
                table.setWidthPercentage(100);

                Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
                Paragraph paragraphCellHeading = new Paragraph("Report", font);

                PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
                BaseColor myColor = WebColors.getRGBColor("#41a5c2");
                cellHeading.setColspan(5);
                cellHeading.setBackgroundColor(myColor);
                cellHeading.setFixedHeight(30.3f);
                cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellHeading);

                Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

                PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
                cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle1);
                PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
                cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle2);
                PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
                cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle3);
                PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
                cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitle4);
                PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
                cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cellTitleStatus);

                int cellColorCheck = 1;
                for (Transfer e : transferList) {
                    PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                    PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                    PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                    PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                    PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                    if (cellColorCheck % 2 == 1) {
                        cellBody1.setBackgroundColor(BaseColor.ORANGE);
                        cellBody2.setBackgroundColor(BaseColor.ORANGE);
                        cellBody3.setBackgroundColor(BaseColor.ORANGE);
                        cellBody4.setBackgroundColor(BaseColor.ORANGE);
                        cellBody5.setBackgroundColor(BaseColor.ORANGE);
                    }
                    table.addCell(cellBody1);
                    table.addCell(cellBody2);
                    table.addCell(cellBody3);
                    table.addCell(cellBody4);
                    table.addCell(cellBody5);
                    cellColorCheck++;
                }

                document.add(table);
                JOptionPane.showMessageDialog(this, "Report saved");

                if (Desktop.isDesktopSupported()) {
                    File reportFile = new File(fileName);
                    Desktop.getDesktop().open(reportFile);
                    ;
                }

                document.close();
            } catch (DocumentException | FileNotFoundException ex) {
                Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParseException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (radInProject.isSelected()) {
        String fromProjectId = (String) cbxFromProject.getSelectedItem();
        String toProjectId = (String) cbxToProject.getSelectedItem();
        List<Transfer> transferList = new ArrayList<>();
        String andOr = "";
        if (cbxAndOr.getSelectedItem().equals("And")) {
            andOr = "and";
            transferList = empObj.searchRecordByFromAndToProject(fromProjectId, toProjectId, andOr);
        } else {
            andOr = "or";
            transferList = empObj.searchRecordByFromAndToProject(fromProjectId, toProjectId, andOr);
        }

        Document document = new Document();
        try {
            Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

            String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            Image imageLogo = Image
                    .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
            imageLogo.setAbsolutePosition(20, 750f);
            document.add(imageLogo);

            Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
            titlePara.setAlignment(Element.ALIGN_CENTER);
            titlePara.setSpacingAfter(5);
            document.add(titlePara);

            Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
            creditPara.setAlignment(Element.ALIGN_CENTER);
            creditPara.setSpacingAfter(10);
            document.add(creditPara);

            Paragraph slashPara = new Paragraph(
                    "Transfer records from Project ID " + fromProjectId + " " + andOr + " " + toProjectId,
                    FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
            slashPara.setSpacingAfter(40);
            slashPara.setAlignment(Element.ALIGN_CENTER);
            document.add(slashPara);

            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);

            Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
            Paragraph paragraphCellHeading = new Paragraph("Report", font);

            PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
            BaseColor myColor = WebColors.getRGBColor("#41a5c2");
            cellHeading.setColspan(5);
            cellHeading.setBackgroundColor(myColor);
            cellHeading.setFixedHeight(30.3f);
            cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellHeading);

            Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

            PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
            cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle1);
            PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
            cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle2);
            PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
            cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle3);
            PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
            cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle4);
            PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
            cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitleStatus);

            int cellColorCheck = 1;
            for (Transfer e : transferList) {
                PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                if (cellColorCheck % 2 == 1) {
                    cellBody1.setBackgroundColor(BaseColor.ORANGE);
                    cellBody2.setBackgroundColor(BaseColor.ORANGE);
                    cellBody3.setBackgroundColor(BaseColor.ORANGE);
                    cellBody4.setBackgroundColor(BaseColor.ORANGE);
                    cellBody5.setBackgroundColor(BaseColor.ORANGE);
                }
                table.addCell(cellBody1);
                table.addCell(cellBody2);
                table.addCell(cellBody3);
                table.addCell(cellBody4);
                table.addCell(cellBody5);
                cellColorCheck++;
            }

            document.add(table);
            JOptionPane.showMessageDialog(this, "Report saved");

            if (Desktop.isDesktopSupported()) {
                File reportFile = new File(fileName);
                Desktop.getDesktop().open(reportFile);
                ;
            }

            document.close();
        } catch (DocumentException | FileNotFoundException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (radAllRecord.isSelected()) {
        List<Transfer> transferList = new ArrayList<>();
        transferList = empObj.searchAllRecord();

        Document document = new Document();
        try {
            Font fontTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);

            String fileName = "../EMPtranfermanagement/Report" + " " + df.format(dateNow) + ".pdf";
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            Image imageLogo = Image
                    .getInstance(this.getClass().getResource("/images/onlinelogomaker-afterscale2.png"));
            imageLogo.setAbsolutePosition(20, 750f);
            document.add(imageLogo);

            Paragraph titlePara = new Paragraph("EMP Transfer Application", fontTitle);
            titlePara.setAlignment(Element.ALIGN_CENTER);
            titlePara.setSpacingAfter(5);
            document.add(titlePara);

            Paragraph creditPara = new Paragraph("Created by Ly Thanh Hai + Nguyen Khanh",
                    FontFactory.getFont(FontFactory.HELVETICA, 10, Font.ITALIC));
            creditPara.setAlignment(Element.ALIGN_CENTER);
            creditPara.setSpacingAfter(10);
            document.add(creditPara);

            Paragraph slashPara = new Paragraph("All transfer records",
                    FontFactory.getFont(FontFactory.HELVETICA, 15, Font.BOLD));
            slashPara.setSpacingAfter(40);
            slashPara.setAlignment(Element.ALIGN_CENTER);
            document.add(slashPara);

            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);

            Font font = new Font(FontFamily.HELVETICA, 15, Font.BOLD);
            Paragraph paragraphCellHeading = new Paragraph("Report", font);

            PdfPCell cellHeading = new PdfPCell(paragraphCellHeading);
            BaseColor myColor = WebColors.getRGBColor("#41a5c2");
            cellHeading.setColspan(5);
            cellHeading.setBackgroundColor(myColor);
            cellHeading.setFixedHeight(30.3f);
            cellHeading.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellHeading.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellHeading);

            Font fBody = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.BLACK);

            PdfPCell cellTitle1 = new PdfPCell(new Phrase("Transfer ID", fBody));
            cellTitle1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle1);
            PdfPCell cellTitle2 = new PdfPCell(new Phrase("Emp ID", fBody));
            cellTitle2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle2);
            PdfPCell cellTitle3 = new PdfPCell(new Phrase("From Project", fBody));
            cellTitle3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle3);
            PdfPCell cellTitle4 = new PdfPCell(new Phrase("To Project", fBody));
            cellTitle4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle4.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitle4);
            PdfPCell cellTitleStatus = new PdfPCell(new Phrase("Status", fBody));
            cellTitleStatus.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitleStatus.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitleStatus);

            int cellColorCheck = 1;
            for (Transfer e : transferList) {
                PdfPCell cellBody1 = new PdfPCell(new Phrase(e.getId()));
                PdfPCell cellBody2 = new PdfPCell(new Phrase(e.getEmployeeId()));
                PdfPCell cellBody3 = new PdfPCell(new Phrase(e.getFromProjectId()));
                PdfPCell cellBody4 = new PdfPCell(new Phrase(e.getToProjectId()));
                PdfPCell cellBody5 = new PdfPCell(new Phrase(e.getStatus()));
                if (cellColorCheck % 2 == 1) {
                    cellBody1.setBackgroundColor(BaseColor.ORANGE);
                    cellBody2.setBackgroundColor(BaseColor.ORANGE);
                    cellBody3.setBackgroundColor(BaseColor.ORANGE);
                    cellBody4.setBackgroundColor(BaseColor.ORANGE);
                    cellBody5.setBackgroundColor(BaseColor.ORANGE);
                }
                table.addCell(cellBody1);
                table.addCell(cellBody2);
                table.addCell(cellBody3);
                table.addCell(cellBody4);
                table.addCell(cellBody5);
                cellColorCheck++;
            }

            document.add(table);
            JOptionPane.showMessageDialog(this, "Report saved");

            if (Desktop.isDesktopSupported()) {
                File reportFile = new File(fileName);
                Desktop.getDesktop().open(reportFile);
                ;
            }

            document.close();
        } catch (DocumentException | FileNotFoundException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(frmReportForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:principal.Informes.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w w .jav  a2s .  c o 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, DocumentException, InterruptedException {
    // SERVLET PARA LA IMPRESIN DE LOS REGISTROS DE SISTEMA
    try {
        // Ejecucion de comando que sera introducido en el pdf
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("/opt/script/owncloud/logOwncloud");
        process.waitFor();
        BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String linea;

        //Imagen para documento PDF
        Image imagen = Image.getInstance("images/owncloud.png");
        imagen.setAlignment(Element.ALIGN_CENTER); //donde estara la imagen localizada           
        imagen.setAlt("50");

        // Creo objeto document de la clase Document     
        Document document = new Document();

        // paso 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        // Abro nuevo documento PDF
        document.open();
        document.addAuthor("Administrator");

        //Nuevo parrafo con texto centrado
        Paragraph parrafo1 = new Paragraph("Informe de servidor Owncloud");
        parrafo1.setAlignment(1); //Centrar el texto
        document.add(imagen); //introduccion de la imagen en el documento pdf
        document.add(parrafo1);

        // bucle ejecutando el comando e introduciendolo en un nuevo parrafo del PDF
        while ((linea = buffer.readLine()) != null) {
            document.add(new Paragraph(linea));
        }

        // Cierre del documento PDF
        document.close();

        // Response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // Tipo de contenido que ser
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        // Extrae todo el PDF para introducirlo en el servlet
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:Print.Print.java

private void printToPDF(BufferedImage bufferedImage) {
    // define pdfprinter and within try clause create
    for (int i = 0; i < quantity; i++) {
        PdfWriter writer = null;//from   w w w. j  a  v a2 s.  co  m
        try {
            // define fileoutputstream and within try clause create
            FileOutputStream fos = null;

            document = new Document(PageSize.A4.rotate());
            fos = new FileOutputStream(output + photoID + "-" + Integer.toString(i + 1) + ".pdf");

            // create the writer object
            try {
                writer = PdfWriter.getInstance(document, fos);
            } catch (DocumentException ex) {
                System.out.println(ex.getMessage());
            }

            // open the writer and the document and add the image into the document
            writer.open();
            document.open();
            try {
                PdfContentByte pdfCB = new PdfContentByte(writer);
                if (bufferedImage == null) {
                    Image image = Image.getInstance(input);
                    image.scaleToFit(640, 480);
                    document.add(image);
                } else {
                    Image image = Image.getInstance(pdfCB, bufferedImage, 1);
                    image.scaleToFit(640, 480);
                    document.add(Image.getInstance(image));
                }

            } catch (DocumentException ex) {
                System.out.println(ex.getMessage());
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
            // close the document and writer
            document.close();
            writer.close();

            System.out.println("Printer done.");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:Print.Print.java

public void printIndex(ArrayList<String> imagesPath, String customer) {
    try {//from w ww  .  jav  a2s . co  m
        //ArrayList<Image> images = new ArrayList<Image>();
        Map<Image, String> dict = new HashMap<Image, String>();
        for (String path : imagesPath) {
            try {
                System.out.println("path = /home/student" + path);
                int index = path.lastIndexOf("/");
                String photoId = path.substring(index + 1, path.length());
                Image newImage = Image.getInstance("/home/student" + path);
                //images.add(newImage);
                dict.put(newImage, photoId);
            } catch (BadElementException ex) {
                Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Total images = " + dict.size());
        Document index = new Document(PageSize.A4.rotate());
        FileOutputStream fos = new FileOutputStream("/home/student/Pictures/index.pdf");
        PdfWriter writer = PdfWriter.getInstance(index, fos);
        writer.open();
        index.open();

        PdfPTable adresTable = new PdfPTable(3);
        PdfPCell adresCell = new PdfPCell(new Paragraph(customer));
        adresCell.setColspan(3);
        adresTable.addCell(adresCell);
        adresTable.setHorizontalAlignment(Element.ALIGN_CENTER);
        adresTable.setWidthPercentage(100);
        index.add(adresTable);
        PdfPTable table = new PdfPTable(imagesPath.size());

        for (Map.Entry<Image, String> image : dict.entrySet()) {
            PdfPCell cell = new PdfPCell();
            table.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.setWidthPercentage(10);
            table.addCell(image.getValue());
            cell.addElement(image.getKey());
            table.addCell(cell);

        }
        index.add(table);
        //index.add(adresTable);
        index.close();
        writer.close();
        System.out.println("Index printed");

        //        // define pdfprinter and within try clause create
        //        PdfWriter writer = null;
        //        FileOutputStream fos = null;
        //        Document index = new Document(PageSize.A4.rotate());
        //        File file;
        //        try {
        //            file = new File("/home/student/Pictures/index.pdf");
        //            if(!file.exists()){
        //                file.createNewFile();
        //                
        //            }
        //            String test = "test data";
        //            fos = new FileOutputStream(file);
        //            fos.write(test.getBytes());
        //            fos.flush();
        //        } catch (FileNotFoundException ex) {
        //            Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
        //        } catch (IOException ex) {
        //            Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
        //        }
        //
        //        for (BufferedImage image : bufferedImages) {            
        //                try {
        //                    writer = PdfWriter.getInstance(index, fos);
        //                } catch (DocumentException ex) {
        //                    System.out.println(ex.getMessage());
        //                }
        //                writer.open();
        //                index.open();
        //                try {
        //                    PdfContentByte pdfCB = new PdfContentByte(writer);
        //                    Image newImage = Image.getInstance(pdfCB, image, 1);
        //                    index.add(Image.getInstance(newImage));
        //                } catch (DocumentException ex) {
        //                    System.out.println(ex.getMessage());
        //                } catch (IOException ex) {
        //                Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
        //            }
        //        }
        //        index.close();
        //        writer.close();
        //        System.out.println("Index done.");
    } catch (DocumentException ex) {
        Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:printInv.GenerateInvoice.java

public void generateLayout(Document doc, PdfContentByte cb) {

    try {//  w  w  w. j  a  v  a 2  s.  c  om

        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, "Invoice No.");
        createHeadings(cb, 422, 723, "Name");
        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(360, 50);
        cb.lineTo(360, 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, "SNo.");
        createHeadings(cb, 52, 633, "Product ID");
        createHeadings(cb, 362, 633, "Quantity");
        createHeadings(cb, 432, 633, "Unit Price");
        createHeadings(cb, 502, 633, "Line Total");

        //add the images
        Image companyLogo = Image.getInstance("src/image/icon.png");
        companyLogo.setAbsolutePosition(25, 700);
        companyLogo.scalePercent(25);
        doc.add(companyLogo);
    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}