Example usage for com.itextpdf.text Document getPageSize

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

Introduction

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

Prototype


public Rectangle getPageSize() 

Source Link

Document

Gets the pagesize.

Usage

From source file:ImagetoPDF.java

public void convertToPDF(String folderName, String fileName, float compressionFactor)
        throws DocumentException, FileNotFoundException, BadElementException, IOException {
    File folder = new File(folderName);
    File[] listOfFiles = folder.listFiles();
    Image img = Image.getInstance(listOfFiles[0].getAbsolutePath());
    float width, height, temp;
    width = img.getWidth();//www  .j a v a2  s  . co  m
    height = img.getHeight();
    if (height < width) {
        temp = height;
        height = width;
        width = height;
    }
    Rectangle pageSize = new Rectangle(width, height);
    Document document = new Document(pageSize, 0, 0, 0, 0);

    for (int i = 0; i < listOfFiles.length; i++) {
        enhance(listOfFiles[i].getAbsolutePath());
    }
    float scalar;
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writer.open();
    writer.setCompressionLevel(5);
    document.open();

    for (int i = 0; i < listOfFiles.length; i++) {
        img = Image.getInstance(listOfFiles[i].getAbsolutePath());
        if (img.getWidth() > img.getHeight()) {
            img.setRotationDegrees(270f);
        }
        scalar = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - 0)
                / img.getWidth()) * 100;
        img.scalePercent(scalar);

        document.add(img);
    }
    document.close();
    writer.close();

}

From source file:adams.gui.print.PDFWriter.java

License:Open Source License

/**
 * generates the actual output.//from ww  w .j  av  a2 s.co  m
 *
 * @throws Exception   if something goes wrong
 */
@Override
public void generateOutput() throws Exception {
    BufferedImage bi;
    Document doc;
    Image image;
    float scale;
    FileOutputStream fos;

    // render image
    bi = createBufferedImage();

    // generate PDF
    scale = (float) m_ImageScale;
    doc = new Document();
    fos = new FileOutputStream(getFile().getAbsoluteFile());
    PdfWriter.getInstance(doc, fos);
    doc.open();
    image = Image.getInstance(Toolkit.getDefaultToolkit().createImage(bi.getSource()), null);
    if (m_ImageRotation != 0) {
        image.setRotationDegrees(m_ImageRotation);
        image.rotate();
    }
    image.scaleToFit(doc.getPageSize().getWidth() * scale, doc.getPageSize().getHeight() * scale);
    doc.add(image);
    doc.close();
    FileUtils.closeQuietly(fos);
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report for the given list of bouts.
 * It is assumed that the list is in the desired order (no sorting is done here).
 *
 * @param list/*w  ww  .j a v  a2 s.  com*/
 * @return True if the report was generated.
 */
public boolean generateReport(Dao dao, List<Bout> list) {

    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

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

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 0;
        for (Bout b : list) {
            boolean rightSide = false;
            if ((count++ % 2) == 0) {
                if (count > 2) {
                    // We could put this after Bout 2 is added, but
                    // that could leave a blank last page.
                    document.newPage();
                }

                // Bout 1 (Left side)
                drawBout(cb, bf, 35, midPage - 35, b);
            } else {
                // Bout 2 (Right side)
                drawBout(cb, bf, midPage + 35, pageWidth - 35, b);
                rightSide = true;
            }

            // Print the watermark, if necessary
            boolean doWatermark = false;
            String gClass = b.getGroup().getClassification();
            String wmValues = dao.getBoutsheetWatermarkValues();
            if ((wmValues != null) && !wmValues.isEmpty()) {
                String[] tokens = wmValues.split(",");
                for (String s : tokens) {
                    if (s.trim().equalsIgnoreCase(gClass)) {
                        doWatermark = true;
                        break;
                    }
                }
            }
            if (doWatermark) {
                int rotation = 45;
                PdfContentByte ucb = writer.getDirectContentUnder();
                BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                ucb.saveState();
                ucb.setColorFill(BaseColor.LIGHT_GRAY);
                ucb.beginText();
                ucb.setFontAndSize(helv, 86);
                float centerWidth = document.getPageSize().getWidth() / 4;
                if (rightSide) {
                    centerWidth = centerWidth * 3;
                }
                ucb.showTextAligned(Element.ALIGN_CENTER, gClass, centerWidth,
                        document.getPageSize().getHeight() / 2, rotation);
                ucb.endText();
                ucb.restoreState();
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

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

    return true;
}

From source file:bouttime.report.bracketsheet.BracketSheetReport.java

License:Open Source License

public static boolean generateReport(Dao dao, List<Group> list, String outputFile, boolean doBoutNumbers,
        boolean doTimestamp) {

    if (list.isEmpty()) {
        return false;
    }/*from  ww  w .  j a va2s . c o m*/

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

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile(outputFile);
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);

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

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        String timestamp = "";
        if (doTimestamp) {
            timestamp = DateFormat.getInstance().format(new Date());
        }

        int rv;
        int i = 0;
        int size = list.size();
        for (Group g : list) {
            rv = addBracket(cb, dao, g, doBoutNumbers);
            if (rv != PAGE_ERROR) {
                // Print the watermark, if necessary
                boolean doWatermark = false;
                String gClass = g.getClassification();
                String wmValues = dao.getBracketsheetWatermarkValues();
                if ((wmValues != null) && !wmValues.isEmpty()) {
                    String[] tokens = wmValues.split(",");
                    for (String s : tokens) {
                        if (s.trim().equalsIgnoreCase(gClass)) {
                            doWatermark = true;
                            break;
                        }
                    }
                }

                int rotation = (rv == PAGE_ROUNDROBIN) ? 45 : 135;

                if (doWatermark) {
                    PdfContentByte ucb = writer.getDirectContentUnder();
                    BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                    ucb.saveState();
                    ucb.setColorFill(BaseColor.LIGHT_GRAY);
                    ucb.beginText();
                    ucb.setFontAndSize(helv, 86);
                    ucb.showTextAligned(Element.ALIGN_CENTER, gClass, document.getPageSize().getWidth() / 2,
                            document.getPageSize().getHeight() / 2, rotation);
                    ucb.endText();
                    ucb.restoreState();
                }

                if (doTimestamp) {
                    rotation -= 45;
                    float width = cb.getPdfWriter().getPageSize().getWidth();
                    int x = (rv == PAGE_ROUNDROBIN) ? 15 : (int) (width - 15);
                    int y = 15;
                    BracketSheetUtil.drawTimestamp(cb, null, x, y, 10, timestamp, rotation);
                }

                // If not doing bout numbers, this is an 'award' type of
                // bracket.  So print an image/logo, if configured.
                if (!doBoutNumbers && (dao.getBracketsheetAwardImage() != null)
                        && !dao.getBracketsheetAwardImage().isEmpty()) {
                    Image image = Image.getInstance(Image.getInstance(dao.getBracketsheetAwardImage()));
                    image.setRotationDegrees((rv == PAGE_ROUNDROBIN) ? 0 : 90);
                    PositionOnPage positionOnPage = dao.getBracketsheetAwardImagePosition();
                    if (PositionOnPage.UPPER_RIGHT == positionOnPage) {
                        float x = (rv == PAGE_ROUNDROBIN)
                                ? document.getPageSize().getWidth() - 10 - image.getWidth()
                                : 10;
                        float y = document.getPageSize().getHeight() - 10 - image.getHeight();
                        image.setAbsolutePosition(x, y);
                        cb.addImage(image);
                    } else if (PositionOnPage.CENTER == positionOnPage) {
                        // put the image in the background, in the middle of the page
                        PdfContentByte ucb = writer.getDirectContentUnder();
                        float pageX = document.getPageSize().getWidth() / 2;
                        float pageY = document.getPageSize().getHeight() / 2;
                        float imageX = image.getWidth() / 2;
                        float imageY = image.getHeight() / 2;
                        image.setAbsolutePosition(pageX - imageX, pageY - imageY);
                        ucb.addImage(image);
                    }
                }

                if (++i < size) {
                    document.newPage();
                }
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

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

    return true;
}

From source file:co.ordinate.printer.NewJFrame.java

private void A4BTNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_A4BTNActionPerformed

    new SwingWorker<Object, Object>() {
        String filename;//from   w  w w. j  a  va 2 s.  c om

        @Override
        protected void done() {

            ConsoleMsg("Printing PROFILE SHEET IN PROGRESS.. ");

        }

        @Override
        protected Object doInBackground() throws Exception {

            Document doc = new Document();
            try {
                PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("A4.pdf"));
                doc.open();
                doc.addTitle("Recruitment PET Sheett - " + "Created By SOS : ");
                doc.addSubject("Confidential Report Eyes Only");
                doc.addKeywords("");
                doc.addAuthor("SOS");
                doc.addCreator("SOS");

                // A4 = 210mm x 297mm ~ 605points x 855points
                doc.setPageSize(PageSize.A4);
                doc.setMargins(10f, 10f, 10f, 10f);

                /////////////////////////////////////////////////////////////
                int pageno = 1;

                for (int i = 0; i == pageno; i++) {

                    //    doc.add(imageRight);
                }

                PdfContentByte cb = writer.getDirectContent();

                int i = 1;
                while (i <= pageno) {
                    doc.newPage();

                    i++;
                }
                BaseFont labelFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                float width = doc.getPageSize().getWidth();
                float height = doc.getPageSize().getHeight();
                for (float h = 0; h <= height; h++) {
                    for (float w = 0; w <= width; w++) {
                        cb.beginText();
                        // cb.setColorFill(TITLE_COLOR);
                        cb.setFontAndSize(labelFont, 2);
                        cb.setTextMatrix(w, h);

                        cb.showText(String.valueOf(h) + ":" + String.valueOf(w));
                        cb.endText();
                        w += 15;
                    }
                    h += 2;
                }
                cb.beginText();
                // cb.setColorFill(TITLE_COLOR);
                cb.setFontAndSize(labelFont, 4);
                cb.setTextMatrix(20f, 220f);
                cb.showText("abcd");
                cb.endText();

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

                ConsoleMsg(e.getMessage());
            } finally {
                doc.close();
            }

            ConsoleMsg("PDF... GENERATED");

            return null;
            //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }.execute();

    // TODO add your handling code here:
}

From source file:co.ordinate.printer.NewJFrame.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    new SwingWorker<Object, Object>() {
        String filename;//from w ww .j  a  va 2 s . c o  m

        @Override
        protected void done() {

            ConsoleMsg("Printing PROFILE SHEET IN PROGRESS.. ");

        }

        @Override
        protected Object doInBackground() throws Exception {

            Document doc = new Document();
            try {
                PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("letter.pdf"));
                doc.open();
                doc.addTitle("Recruitment PET Sheett - " + "Created By SOS : ");
                doc.addSubject("Confidential Report Eyes Only");
                doc.addKeywords("");
                doc.addAuthor("SOS");
                doc.addCreator("SOS");

                // A4 = 210mm x 297mm ~ 605points x 855points
                doc.setPageSize(PageSize.LETTER);
                doc.setMargins(10f, 10f, 10f, 10f);

                /////////////////////////////////////////////////////////////
                int pageno = 1;

                for (int i = 0; i == pageno; i++) {

                    //    doc.add(imageRight);
                }

                PdfContentByte cb = writer.getDirectContent();

                int i = 1;
                while (i <= pageno) {
                    doc.newPage();

                    i++;
                }
                BaseFont labelFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                float width = doc.getPageSize().getWidth();
                float height = doc.getPageSize().getHeight();
                for (float h = 0; h <= height; h++) {
                    for (float w = 0; w <= width; w++) {
                        cb.beginText();
                        // cb.setColorFill(TITLE_COLOR);
                        cb.setFontAndSize(labelFont, 4);
                        cb.setTextMatrix(w, h);

                        cb.showText(String.valueOf(h) + ":" + String.valueOf(w));
                        cb.endText();
                        w += 25;
                    }
                    h += 5;
                }
                cb.beginText();
                // cb.setColorFill(TITLE_COLOR);
                cb.setFontAndSize(labelFont, 4);
                cb.setTextMatrix(20f, 220f);
                cb.showText("abcd");
                cb.endText();

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

                ConsoleMsg(e.getMessage());
            } finally {
                doc.close();
            }

            ConsoleMsg("PDF... GENERATED");

            return null;
            //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }.execute();

    // TODO add your handling code here:
}

From source file:co.ordinate.printer.NewJFrame.java

private void printA6Sheet() {
    new SwingWorker<Object, Object>() {
        String filename;/*from  w w  w .j a  v  a 2 s .  c  o m*/

        @Override
        protected void done() {

            ConsoleMsg("Printing PROFILE SHEET IN PROGRESS.. ");
            System.err.println("Printing Done");
        }

        @Override
        protected Object doInBackground() throws Exception {

            Document doc = new Document();
            try {
                PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("A6.pdf"));
                doc.open();
                doc.addTitle("Recruitment PET Sheett - " + "Created By SOS : ");
                doc.addSubject("Confidential Report Eyes Only");
                doc.addKeywords("");
                doc.addAuthor("SOS");
                doc.addCreator("SOS");

                // A4 = 210mm x 297mm ~ 605points x 855points
                doc.setPageSize(PageSize.A5);
                doc.setMargins(10f, 10f, 10f, 10f);

                /////////////////////////////////////////////////////////////
                int pageno = 1;

                for (int i = 0; i == pageno; i++) {

                    //    doc.add(imageRight);
                }

                PdfContentByte cb = writer.getDirectContent();

                int i = 1;
                while (i <= pageno) {
                    doc.newPage();

                    i++;
                }
                BaseFont labelFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                float width = doc.getPageSize().getWidth();
                float height = doc.getPageSize().getHeight();
                for (float h = 0; h <= height; h++) {
                    for (float w = 0; w <= width; w++) {
                        cb.beginText();
                        // cb.setColorFill(TITLE_COLOR);
                        cb.setFontAndSize(labelFont, 4);
                        cb.setTextMatrix(w, h);

                        cb.showText(String.valueOf(h) + ":" + String.valueOf(w));
                        cb.endText();
                        w += 30;
                    }
                    h += 8;
                }
                cb.beginText();
                // cb.setColorFill(TITLE_COLOR);
                cb.setFontAndSize(labelFont, 4);
                cb.setTextMatrix(20f, 220f);
                cb.showText("abcd");
                cb.endText();

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

                ConsoleMsg(e.getMessage());
            } finally {
                doc.close();
            }

            ConsoleMsg("PDF... GENERATED");
            System.err.println("Printing Done");
            return null;
            //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }.execute(); // TODO add your handling code here:

}

From source file:com.atacadao.almoxarifado.model.GerandoPDF.java

public void pdfImpressaoBarraDeCodigo(String codigo) {
    Document documento = new Document(new Rectangle(90, 65));
    documento.setMargins(0, 0, 0, 0);/*from  w w  w  . j av a 2 s . c om*/

    PdfWriter pdf;

    try {
        pdf = PdfWriter.getInstance(documento, new FileOutputStream("codigodebarras.pdf"));
        documento.open();
        PdfContentByte contB = pdf.getDirectContent();
        Barcode128 barCode = new Barcode128();
        barCode.setCode(codigo);
        barCode.setCodeType(Barcode128.CODE128);

        Image image = barCode.createImageWithBarcode(contB, BaseColor.BLACK, BaseColor.BLACK);
        Paragraph titulo = new Paragraph("ATCADO DOS PISOS\n",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 5));
        titulo.setPaddingTop(0);
        titulo.setAlignment(Element.ALIGN_CENTER);

        float scaler = ((documento.getPageSize().getWidth() - documento.leftMargin() - documento.rightMargin()
                - 0) / image.getWidth()) * 60;

        image.scalePercent(scaler);
        image.setPaddingTop(0);
        image.setAlignment(Element.ALIGN_CENTER);

        documento.add(titulo);
        documento.add(image);

        documento.close();

        Desktop.getDesktop().open(new File("codigodebarras.pdf"));

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

}

From source file:com.centurylink.mdw.pdf.PdfExportHelper.java

License:Apache License

public byte[] exportProcess(Process process, File outputFile) throws Exception {
    new ActivityNodeSequencer(process).assignNodeSequenceIds();
    Document document = new Document();
    DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
    document.open();/*from   ww w .  j  a v a2s.  co  m*/
    document.setPageSize(PageSize.LETTER);
    Rectangle pageSize = document.getPageSize();
    Chapter chapter = printProcessPdf(writer, 1, process, pageSize);
    document.add(chapter);
    document.close();

    return Files.readAllBytes(Paths.get(outputFile.getPath()));
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void addImage(final Image image, final Document document, final PdfWriter writer) throws Exception {
    if (image.getWidth() > image.getHeight()) {
        document.setPageSize(new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()));
    } else {//from  www.  j a  v  a2  s . c om
        document.setPageSize(new Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight()));
    }
    image.scaleToFit(document.getPageSize().getWidth() - this.margin * 2f,
            document.getPageSize().getHeight() - this.margin * 2f);
    float px = (document.getPageSize().getWidth() - image.getScaledWidth()) / 2f;
    float py = (document.getPageSize().getHeight() - image.getScaledHeight()) / 2f;
    image.setAbsolutePosition(px, py);
    document.newPage();
    document.add(image);
    writePageNumber(writer);
}