Example usage for com.itextpdf.text Rectangle getWidth

List of usage examples for com.itextpdf.text Rectangle getWidth

Introduction

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

Prototype

public float getWidth() 

Source Link

Document

Returns the width of the rectangle.

Usage

From source file:edu.clemson.lph.pdfgen.MergePDF.java

License:Open Source License

/**
 * This version can be used stand alone or called from specific image type methods.
 * @param Image Java Image object.//from  w w w.java2  s  . c om
 * @return
 */
public static byte[] imageToPdfBytes(Image imageIn) {
    // new pdf Document
    Rectangle pagesize = PageSize.LETTER.rotate(); // Landscape letter size (11x8.5)
    Document doc = new Document(pagesize, 0f, 0f, 0f, 0f); // no margins
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter docWriter = null;
    try {
        docWriter = PdfWriter.getInstance(doc, baosPDF);
        doc.open();
        imageIn.scaleToFit(pagesize.getWidth(), pagesize.getHeight());
        doc.add(imageIn);
    } catch (DocumentException e) {
        logger.error(e);
    } finally {
        if (doc != null)
            doc.close();
        if (docWriter != null)
            docWriter.close();
    }
    return baosPDF.toByteArray();
}

From source file:edu.umn.genomics.component.SavePDF.java

License:Open Source License

/**
 *  Saves the Component to a Portable Document File, PDF, with the 
 * file location selected using the JFileChooser.
 * @param c the Component to save as a PDF
 *//*ww  w  .j  a  v a 2s  .  c  o m*/
public static boolean savePDF(Component c) throws IOException {
    System.out.println("");
    final int w = c.getWidth() > 0 ? c.getWidth() : 1;
    final int h = c.getHeight() > 0 ? c.getHeight() : 1;
    final Dimension dim = c.getPreferredSize();

    JFileChooser chooser = new JFileChooser();
    JPanel ap = new JPanel();
    ap.setLayout(new BoxLayout(ap, BoxLayout.Y_AXIS));
    JPanel sp = new JPanel(new GridLayout(0, 1));
    sp.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Image Size"));
    final JTextField iwtf = new JTextField("" + w, 4);
    iwtf.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "width"));
    final JTextField ihtf = new JTextField("" + h, 4);
    ihtf.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "height"));
    JButton curSzBtn = new JButton("As Viewed: " + w + "x" + h);
    curSzBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            iwtf.setText("" + w);
            ihtf.setText("" + h);
        }
    });
    sp.add(curSzBtn);
    if (dim != null && dim.getWidth() > 0 && dim.getHeight() > 0) {
        JButton prefSzBtn = new JButton("As Preferred: " + dim.width + "x" + dim.height);
        prefSzBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                iwtf.setText("" + dim.width);
                ihtf.setText("" + dim.height);
            }
        });
        sp.add(prefSzBtn);
    }
    sp.add(iwtf);
    sp.add(ihtf);

    ap.add(sp);

    chooser.setAccessory(ap);
    // ImageFilter filter = new ImageFilter(fmt);
    // chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(c);
    boolean status = false;
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        //Added the below code to add th .pdf extension if it is not provided by the user
        String name = file.getAbsolutePath();
        if (!(name.substring(name.length() - 4, name.length()).equalsIgnoreCase(".pdf"))) {
            name = name.concat(".pdf");
            file = new File(name);
        }
        int iw = w;
        int ih = h;
        try {
            iw = Integer.parseInt(iwtf.getText());
            ih = Integer.parseInt(ihtf.getText());
        } catch (Exception ex) {
            ExceptionHandler.popupException("" + ex);
        }
        iw = iw > 0 ? iw : w;
        ih = ih > 0 ? ih : h;
        if (iw != w || ih != h) {
            c.setSize(iw, ih);
        }

        // step 1: creation of a document-object
        Document document = new Document();

        try {
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

            // step 3: we open the document
            document.open();

            // step 4: we grab the ContentByte and do some stuff with it

            // we create a fontMapper and read all the fonts in the font directory
            DefaultFontMapper mapper = new DefaultFontMapper();

            // mapper.insertDirectory("c:\\winnt\\fonts");

            com.itextpdf.text.Rectangle pgSize = document.getPageSize();
            // we create a template and a Graphics2D object that corresponds with it
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(iw, ih);
            tp.setWidth(iw);
            tp.setHeight(ih);
            Graphics2D g2 = tp.createGraphics(iw, ih, mapper);
            g2.setStroke(new BasicStroke(.1f));
            //cb.setLineWidth(.1f);
            //cb.stroke();

            c.paintAll(g2);

            g2.dispose();

            //cb.addTemplate(tp, 0, 0);
            float sfx = (float) (pgSize.getWidth() / iw);
            float sfy = (float) (pgSize.getHeight() / ih);
            // preserve the aspect ratio
            float sf = (float) Math.min(sfx, sfy);
            cb.addTemplate(tp, sf, 0f, 0f, sf, 0f, 0f);

        } catch (DocumentException de) {
            ExceptionHandler.popupException("" + de);
        } catch (IOException ioe) {
            ExceptionHandler.popupException("" + ioe);
        } catch (Exception ex) {
            ExceptionHandler.popupException("" + ex);
        }

        // step 5: we close the document
        document.close();

        if (iw != w || ih != h) {
            c.setSize(w, h);
        }

    }
    return true;
}

From source file:ExternalNonFormClasses.PDFEnator.java

public void createPDF() {
    try {/*from  w  w w  .java 2  s  . co  m*/
        Rectangle one = new Rectangle(PageSize.LETTER);
        Document doc = new Document(one);
        PdfWriter writer = PdfWriter.getInstance(doc,
                new FileOutputStream(getDirectory() + "\\" + data_title + ".pdf"));
        //doc.setMargins(1, 1, 1, 1);
        doc.open();
        PdfContentByte canvas = writer.getDirectContent();
        Font font = new Font(Font.FontFamily.TIMES_ROMAN, 11);
        x = one.getWidth();
        y = one.getHeight();
        tableX = (x / 2) - 235;
        tableY = y - 180;

        getHeader();
        Paragraph para = new Paragraph("Province of " + formHeaderValues[0], font);
        para.setAlignment(Element.ALIGN_CENTER);
        doc.add(para);
        Paragraph para2 = new Paragraph("City/Municipality of " + formHeaderValues[1], font);
        para2.setAlignment(Element.ALIGN_CENTER);
        doc.add(para2);
        Paragraph para3 = new Paragraph("Barangay " + formHeaderValues[2], font);
        para3.setAlignment(Element.ALIGN_CENTER);
        doc.add(para3);
        doc.add(Chunk.NEWLINE);
        doc.add(Chunk.NEWLINE);
        Paragraph para4 = new Paragraph(data_title, font);
        para4.setAlignment(Element.ALIGN_CENTER);
        doc.add(para4);

        PdfPTable pdftable;

        pdftable = writeHeaders(font);

        //pdftable.writeSelectedRows(0, -1, (x / 2) - 235, y - 180, canvas);
        int counter = 1, rowCounter = 0, columnCounter = 0;
        int yIncrementor = 16;
        boolean test = true;
        while (counter <= this.totalDataSize) {
            //System.out.println("data#: " + counter + "@ (" + rowCounter + "," + (columnCounter) + ") = " + this.table.getValueAt(rowCounter, columnCounter).toString());
            PdfPCell cell1 = new PdfPCell(
                    new Paragraph(this.table.getValueAt(rowCounter, columnCounter++).toString(), font));
            cell1.setPaddingBottom(5);
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            pdftable.addCell(cell1);

            if (counter > 0 && (counter % column) == 0) { //if there are 4 columns
                //pdftable.writeSelectedRows(0, -1, (x / 2) - 235, (y - 180) - yIncrementor, canvas); //print row of 4 columns
                yIncrementor += 16; //move to next row coordinate, so y coordinate plus plus
                rowCounter++; //move to next row
                columnCounter = 0; //back to start column
                boolean newPage = false;

                if ((tableY - ((yIncrementor - 16) + 80)) <= 72) { //if it exceeds 1 inch in footer, new page
                    //                        System.out.println("(" + tableY + "-((" + yIncrementor + "-16)+" + 16 + "))");
                    //                        System.out.println("Nanobra? YES; " + (tableY - ((yIncrementor - 16) + 16)));
                    newPage = true;
                } else if ((tableY - (yIncrementor + 80)) <= 72) {
                    //                        System.out.println("(" + tableY + "-(" + yIncrementor + "+" + 16 + "))");
                    //                        System.out.println("Nanobra? YES; " + (tableY - (yIncrementor + 16)));
                    newPage = true;
                }

                if (newPage) {
                    pdftable.completeRow();
                    pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas); //print the data for the current page
                    doc.newPage(); //create new page
                    pdftable = writeHeaders(font); //write headers to new page
                    yIncrementor = 16; //restore default
                }
            }

            //                if (counter == this.totalDataSize) { //para lng mudouble ang data
            //                    if (test) {
            //                        test = false;
            //                        counter = 0;
            //                        rowCounter = 0;
            //                        columnCounter = 0;
            //                    }
            //                } else if (counter == this.totalDataSize) {
            //                    if (!test) {
            //                        break;
            //                    }
            //                }
            counter++;
        }
        pdftable.completeRow();
        pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas);
        doc.close();

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

}

From source file:ExternalNonFormClasses.PDFEnator.java

public void createProfilePDF(String id, ArrayList<String> data) {
    this.data_title = "Citizen Profile";
    this.table = null;
    this.caller = 4;
    this.row = 17;
    this.column = 2;
    this.personID = id;
    this.totalDataSize = row * column;
    tableHeaderData = new ArrayList<>();
    tableHeaderData.add("Label");
    tableHeaderData.add("Information");

    ArrayList<String> dataAll = data;

    try {//from   ww w. j a v a2  s  .c  o  m
        getHeader();
        Document doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc,
                new FileOutputStream(getDirectory() + "\\" + data_title + ".pdf"));
        Rectangle one = new Rectangle(PageSize.LETTER);
        doc.setPageSize(one);
        //doc.setMargins(1, 1, 1, 1);
        doc.open();
        PdfContentByte canvas = writer.getDirectContent();
        Font font = new Font(Font.FontFamily.TIMES_ROMAN, 11);
        x = one.getWidth();
        y = one.getHeight();
        tableX = (x / 2) - 235;
        tableY = y - 180;

        Paragraph para = new Paragraph("Province of " + formHeaderValues[0], font);
        para.setAlignment(Element.ALIGN_CENTER);
        doc.add(para);
        Paragraph para2 = new Paragraph("City/Municipality of " + formHeaderValues[1], font);
        para2.setAlignment(Element.ALIGN_CENTER);
        doc.add(para2);
        Paragraph para3 = new Paragraph("Barangay " + formHeaderValues[2], font);
        para3.setAlignment(Element.ALIGN_CENTER);
        doc.add(para3);
        Paragraph para4 = new Paragraph(data_title, font);
        para4.setAlignment(Element.ALIGN_CENTER);
        doc.add(para4);

        PdfPTable pdftable;
        pdftable = writeHeaders(font);
        int counter = 1, rowCounter = 0, columnCounter = 0;
        int yIncrementor = 16;
        String label = null, value = null;
        System.out.println(dataAll.size());
        while (counter <= this.row) {
            switch (counter - 1) {
            case 0:
                label = "Citizen ID";
                value = id;
                break;
            case 1:
                label = "Last Name";
                value = dataAll.get(counter - 2);
                break;
            case 2:
                label = "First Name";
                value = dataAll.get(counter - 2);
                break;
            case 3:
                label = "Middle Name";
                value = dataAll.get(counter - 2);
                break;
            case 4:
                label = "Name Suffix";
                value = dataAll.get(counter - 2);
                break;
            case 5:
                label = "Date of Birth";
                value = dataAll.get(counter - 2);
                break;
            case 6:
                label = "Gender";
                value = dataAll.get(counter - 2);
                break;
            case 7:
                label = "Address";
                value = dataAll.get(counter - 2);
                break;
            case 8:
                label = "Age";
                value = dataAll.get(counter - 2);
                break;
            case 9:
                label = "Place of Birth";
                value = dataAll.get(counter - 2);
                break;
            case 10:
                label = "Civil Status";
                value = dataAll.get(counter - 2);
                break;
            case 11:
                label = "Contact";
                value = dataAll.get(counter - 2);
                break;
            case 12:
                label = "Zip Code";
                value = dataAll.get(counter - 2);
                break;
            case 13:
                label = "Precinct Number";
                value = dataAll.get(counter - 2);
                break;
            case 14:
                label = "Occupation";
                value = dataAll.get(counter - 2);
                break;
            case 15:
                label = "Email Address";
                value = dataAll.get(counter - 2);
                break;
            case 16:
                label = "Religion";
                value = dataAll.get(counter - 2);
                break;
            }
            if (value.length() <= 0) {
                value = "N/A";
            }

            System.out.println(label + ": " + value);
            PdfPCell cell1 = new PdfPCell(new Paragraph(label, font));
            cell1.setPaddingBottom(5);
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            pdftable.addCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Paragraph(value, font));
            cell2.setPaddingBottom(5);
            cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
            pdftable.addCell(cell2);

            if (counter > 0 && (counter % column) == 0) { //if there are 4 columns
                yIncrementor += 16; //move to next row coordinate, so y coordinate plus plus
                rowCounter++; //move to next row
                columnCounter = 0; //back to start column
                boolean newPage = false;

                if ((tableY - ((yIncrementor - 16) + 80)) <= 72 || (tableY - (yIncrementor + 80)) <= 72) { //if it exceeds 1 inch in footer, new page
                    newPage = true;
                }

                if (newPage) {
                    pdftable.completeRow();
                    pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas); //print the data for the current page
                    doc.newPage(); //create new page
                    pdftable = writeHeaders(font); //write headers to new page
                    yIncrementor = 16; //restore default
                }
            }
            counter++;
        }
        pdftable.completeRow();
        pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas);
        doc.close();

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

}

From source file:gravabncertificado007.CarimboCertificado.java

public void aplicaCarimboBin(String BN, String caminhoarquivo)
        throws DocumentException, IOException, RuntimeException {

    PdfReader.unethicalreading = true;/*from   w w w .  ja va2  s. co  m*/
    //Cria o reader para o primeiro PDF

    PdfReader reader = new PdfReader(caminhoarquivo);
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getWidth();
    float height = psize.getHeight();

    Document document = new Document(new Rectangle(width, height));

    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));

    document.open();

    int i = 0;
    BN = BN.substring(BN.length() - 13, BN.length() - 4);
    PdfContentByte cb = writer.getDirectContent();
    while (i < reader.getNumberOfPages()) {
        i++;

        document.newPage();

        PdfContentByte under = writer.getDirectContentUnder();
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, 0, i * 0.2f);

        //CARIMBO DA BN
        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
        cb.endText();

    }

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

}

From source file:gravabncertificado007.CarimboCertificado.java

public void aplicaCariboGedi(String BN, String caminhoarquivo)
        throws DocumentException, IOException, RuntimeException {

    PdfReader.unethicalreading = true;//ww  w .ja  v  a2  s . c o  m
    //Cria o reader para o primeiro PDF

    PdfReader reader = new PdfReader(caminhoarquivo);
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getWidth();
    float height = psize.getHeight();

    Document document = new Document(new Rectangle(width, height));

    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-G.pdf"));

    document.open();

    int i = 0;
    BN = BN.substring(BN.length() - 13, BN.length() - 4);
    PdfContentByte cb = writer.getDirectContent();
    while (i < reader.getNumberOfPages()) {
        i++;

        document.newPage();

        PdfContentByte under = writer.getDirectContentUnder();
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, 0, i * 0.2f);

        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "  _________________  ", width / 6, 44, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 32, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 22, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |Copia Controlada |", width / 6, 28, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 16, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 12, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |_________________|", width / 6, 14, 0);
        cb.endText();
    }

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

}

From source file:info.longnetpro.examples.PdfLibExamples.java

public static void generatePdf()
        throws DocumentException, URISyntaxException, MalformedURLException, IOException {
    String licFile = getLicenseFilePath();
    loadLicenseFile(licFile);//from ww  w  . java  2  s  .c om

    String dest = getTargetFilePath();
    Document doc = new Document();
    PdfWriter.getInstance(doc, new FileOutputStream(dest));
    Rectangle pageSize = PageSize.LETTER;
    Rectangle rect = new Rectangle(0f, 0f, 50f, 100f);
    rect.setBorder(15);
    rect.setBorderColor(BaseColor.RED);
    rect.setBorderWidth(.5f);
    rect.setBackgroundColor(BaseColor.BLUE);
    doc.setPageSize(pageSize);
    doc.open();

    Page page = new Page(pageSize.getWidth(), pageSize.getHeight());
    ContentBox rpage = page.margin(new Float[] { 10f, 50f, 10f, 50f });

    for (Anchor anchor : Anchor.values()) {
        ContentBox box = new ContentBox(50f, 100f);
        float offx = anchor.equals(Anchor.CENTER) ? -50f : 0f;
        float offy = anchor.equals(Anchor.CENTER) ? -50f : 0f;

        ContentBox rr = anchor.anchorElement(rpage, box, offx, offy);

        if (anchor.equals(Anchor.BOTTOM_LEFT)) {
            float[] dim = box.scaleByPercentage(0.5f);
            //rr = rr.reposition(dim[0], dim[1], Anchor.TOP_RIGHT);
        }

        rect.setLeft(rr.getLeft());
        rect.setBottom(rr.getBottom());
        rect.setRight(rr.getRight());
        rect.setTop(rr.getTop());
        doc.add(rect);
    }
    String imageFile = getImageFilePath();
    Image image = Image.getInstance(imageFile);

    float width = Measurement.dotsToUserUnits(image.getWidth(), 1200);
    float height = Measurement.dotsToUserUnits(image.getHeight(), 1200);

    System.out.println(width + " " + height);

    ContentBox img = Anchor.BOTTOM_LEFT.anchorElement(rpage, width, height);

    image.scaleToFit(width, height);
    image.setAbsolutePosition(img.getLeft(), img.getBottom());

    System.out.println(image.getWidth() + " " + image.getHeight());
    System.out.println(image.getAbsoluteX() + " " + image.getAbsoluteY());

    doc.add(image);
    doc.close();
}

From source file:javaapplication1.JavaApplication1.java

public void parsePdf(String pdf, String txt) throws IOException {
    PdfReader reader = new PdfReader(pdf + ".pdf");
    //  PrintWriter out = new PrintWriter(new FileOutputStream(txt));
    // Rectangle rect = new Rectangle(0,0, 300,800);
    //  RenderFilter filter = new RegionTextRenderFilter(rect);
    // TextExtractionStrategy strategy;
    /*    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
    strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
    out.println(PdfTextExtractor.getTextFromPage(reader, i, strategy));
        }*///from   w  ww  .ja v a 2  s. c om

    int pw, ph;
    Rectangle mrect;

    //reader = new PdfReader(pdf);
    String g = new String();
    ArrayList<Integer> cutlist;
    int lastblank;
    int lastword;
    //int p=reader.getNumberOfPages();
    int p = 1;
    double f;
    BufferedImage img;
    BufferedImage img1;
    for (int k = 1; k <= p; k++) {
        cutlist = new ArrayList<Integer>();
        lastword = 0;
        lastblank = -1;
        mrect = reader.getPageSize(k);
        ph = (int) mrect.getHeight();
        pw = (int) mrect.getWidth();
        for (int i = 0; i <= (ph - fontchecksize); i += fontchecksize) {
            g = mycheckline(reader, ph, pw, i, k);
            if (g.isEmpty())
                lastblank = i;
            else {
                //  System.out.println(g);
                if (lastword == 0) {
                    if (i > 2 * fontchecksize)
                        cutlist.add(i - 2 * fontchecksize);
                    else
                        cutlist.add(0);
                    lastword = i;
                } else if (g.matches("\\d+\\..*")) {
                    cutlist.add(((lastword + i) / 2));

                }
                lastword = i;

            }
        }
        if (lastword + 3 * fontchecksize < ph) {
            cutlist.add(lastword + 3 * fontchecksize);
        } else
            cutlist.add(ph - 1);
        //  System.out.println("The arraylist contains the following elements: "+ cutlist);
        img = ImageIO.read(new File(txt + ".png"));

        //img1 = ImageIO.read(new File("prefix-1.png"));
        f = img.getHeight() / ph;
        //System.out.println(f);
        int s;
        //  ImageIO.write(img.getSubimage(0,(int)(f*(84)),(int)(f*pw),(int)(f*(156-84))), "png", new File("7.png"));
        for (s = 0; s < (cutlist.size() - 1); s++) {
            // System.out.println(cutlist.get(s));
            ImageIO.write(
                    img.getSubimage(0, (int) (f * (cutlist.get(s))), (int) (f * pw),
                            (int) (f * (cutlist.get(s + 1) - cutlist.get(s)))),
                    "png", new File(txt + s + ".png"));
        }

        /*  ImageIO.write(img.getSubimage(0,(int)(f*(84)),(int)(f*pw),(int)(f*(156-84))), "png", new File("7.png"));
            ImageIO.write(img.getSubimage(0,(int)(f*(156)),(int)(f*pw),(int)(f*(222-156))), "png", new File("8.png"));
            ImageIO.write(img1.getSubimage(0,(int)(f*(186)),(int)(f*pw),(int)(f*(225-186))), "png", new File("1.png"));
            ImageIO.write(img1.getSubimage(0,(int)(f*(225)),(int)(f*pw),(int)(f*(297-225))), "png", new File("2.png"));
            ImageIO.write(img1.getSubimage(0,(int)(f*(297)),(int)(f*pw),(int)(f*(339-297))), "png", new File("3.png"));
            ImageIO.write(img1.getSubimage(0,(int)(f*(339)),(int)(f*pw),(int)(f*(465-339))), "png", new File("4.png"));
            ImageIO.write(img1.getSubimage(0,(int)(f*(465)),(int)(f*pw),(int)(f*(585-465))), "png", new File("5.png"));
            ImageIO.write(img1.getSubimage(0,(int)(f*(585)),(int)(f*pw),(int)(f*(630-585))), "png", new File("6.png"));*/
    }
}

From source file:jdbreport.model.io.pdf.itext5.PdfWriter.java

License:Apache License

private PdfPCell writeCell(ReportModel model, jdbreport.model.Cell srcCell, int row, int col)
        throws BadElementException, IOException, SaveReportException {

    CellStyle style = model.getStyles(srcCell.getStyleId());

    java.awt.Rectangle rect = model.getCellRect(row, col, true, true);

    float h = (float) Units.PT.setYPixels((int) rect.getHeight());
    float w = (float) Units.PT.setXPixels((int) rect.getWidth());

    PdfPCell pdfCell;/*  w  ww .  j a v  a  2 s .  c o  m*/

    if (srcCell.getPicture() != null) {
        Icon icon = srcCell.getPicture().getIcon();
        java.awt.Image awtImage = ((ImageIcon) icon).getImage();

        com.itextpdf.text.Image image = awtImageToImage(awtImage, srcCell, w, h);
        pdfCell = new PdfPCell(image);
    } else {
        pdfCell = new PdfPCell();

        String text = null;

        if (srcCell.getValue() instanceof CellValue<?>) {

            StringWriter strWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(strWriter);

            if (!((CellValue<?>) srcCell.getValue()).write(printWriter, model, row, col, this,
                    ReportBook.PDF)) {
                java.awt.Image awtImage = ((CellValue<?>) srcCell.getValue()).getAsImage(model, row, col);
                if (awtImage != null) {
                    com.itextpdf.text.Image image = awtImageToImage(awtImage, srcCell, w, h);
                    pdfCell.setImage(image);
                }
            } else {
                text = strWriter.getBuffer().toString();
            }

        } else {
            if (jdbreport.model.Cell.TEXT_HTML.equals(srcCell.getContentType())) {
                writeHTMLText(model.getStyles(srcCell.getStyleId()), srcCell, pdfCell);
            } else {
                text = model.getCellText(srcCell);
            }
        }

        if (text != null && text.length() > 0) {
            com.itextpdf.text.Font font;
            if (fonts.containsKey(style.getId())) {
                font = fonts.get(style.getId());
            } else {
                font = getFontMapper().styleToPdf(style);
                fonts.put(style.getId(), font);
            }
            Paragraph p;
            if (font != null) {
                p = new Paragraph(text, font);
            } else {
                p = new Paragraph(text);
            }
            pdfCell.setPhrase(p);
        }
    }

    pdfCell.setFixedHeight(h);
    pdfCell.setPadding(1);
    pdfCell.setBackgroundColor(new BaseColor(style.getBackground().getRGB()));
    pdfCell.setHorizontalAlignment(toPdfHAlignment(style.getHorizontalAlignment()));
    pdfCell.setVerticalAlignment(toPdfVAlignment(style.getVerticalAlignment()));

    if (style.getAngle() != 0) {
        pdfCell.setRotation(roundAngle(style.getAngle()));
    }

    assignBorders(style, pdfCell);
    pdfCell.setNoWrap(!style.isWrapLine());

    if (srcCell.getColSpan() > 0) {
        pdfCell.setColspan(srcCell.getColSpan() + 1);
    }
    if (srcCell.getRowSpan() > 0) {
        pdfCell.setRowspan(srcCell.getRowSpan() + 1);
    }

    return pdfCell;
}

From source file:mkl.testarea.itext5.pdfcleanup.StrictPdfCleanUpProcessor.java

License:Open Source License

private void insertFormXObj(PdfContentByte canvas, PdfDictionary pageDict, PdfStream formXObj,
        List<Rectangle> clippingRects, Rectangle annotRect) throws IOException {
    PdfName xobjName = generateNameForXObj(pageDict);
    canvas.saveState();/*from w  ww .jav  a2s .  c  om*/

    for (Rectangle rect : clippingRects) {
        canvas.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
    }

    canvas.clip();
    canvas.newPath();

    canvas.addFormXObj(formXObj, xobjName, 1, 0, 0, 1, annotRect.getLeft(), annotRect.getBottom());

    canvas.restoreState();
}