Example usage for com.itextpdf.text Rectangle Rectangle

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

Introduction

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

Prototype

public Rectangle(final float urx, final float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

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();//from   w ww  . j  a  va  2 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:ca.sqlpower.wabit.report.LayoutToPDF.java

License:Open Source License

public void writePDF() throws DocumentException, FileNotFoundException, PrinterException {
    monitorableHelper.setStarted(true);//  w  ww .jav  a  2s . c  o  m
    int pageNum = 0;

    int numPages = layout.getNumberOfPages();
    monitorableHelper.setJobSize(numPages);
    Page page = layout.getPage();
    OutputStream out = fileOS;
    Rectangle pageSize;
    pageSize = new Rectangle(page.getWidth(), page.getHeight());

    Document pdfDoc = new Document(pageSize, 0f, 0f, 0f, 0f);

    PdfWriter pdfOut = PdfWriter.getInstance(pdfDoc, out);
    pdfDoc.open();
    pdfDoc.addCreator("Wabit " + WabitVersion.VERSION);
    PdfContentByte pdfContent = pdfOut.getDirectContent();
    Graphics2D pdfGraphics = null;
    try {
        while (pageNum < numPages) {
            monitorableHelper.checkCancelled();
            monitorableHelper.setProgress(pageNum);
            pdfGraphics = pdfContent.createGraphics(pageSize.getWidth(), pageSize.getHeight());
            int flag = layout.print(pdfGraphics, layout.getPageFormat(pageNum), pageNum);

            if (watermarker != null) {
                java.awt.Rectangle watermarkSize = new java.awt.Rectangle();
                watermarkSize.setSize(Math.round(pageSize.getWidth()), Math.round(pageSize.getHeight()));
                watermarker.watermark(pdfGraphics, watermarkSize);
            }

            pdfGraphics.dispose();
            pdfGraphics = null;

            if (flag == Printable.NO_SUCH_PAGE)
                break;

            pdfDoc.newPage();

            pageNum++;
        }
    } finally {
        if (pdfGraphics != null)
            pdfGraphics.dispose();
        if (pdfDoc != null)
            pdfDoc.close();
        monitorableHelper.setFinished(true);
    }
}

From source file:com.apcb.utils.utils.PdfCreator.java

public static String createPdfVoucher(APCB_PayMain aPCB_PayMain, PropertiesReader prop) throws Exception {

    String vaouche = aPCB_PayMain.getVoucher();
    vaouche = vaouche.replace("&lt;", "<");
    vaouche = vaouche.replace("&gt;", ">");
    vaouche = vaouche.replace("&quot;", "\"");
    vaouche = vaouche.replace("&#39;", "'");
    vaouche = vaouche.replace("&amp;#211;", "O");

    StringBuilder fileName = new StringBuilder();
    fileName.append(prop.getProperty("VauchersPath", false));
    fileName.append(prop.getProperty("Target", false)).append("_");
    fileName.append(aPCB_PayMain.getApproval()).append("_");
    fileName.append(aPCB_PayMain.getCardNumber()).append("_");
    fileName.append(aPCB_PayMain.getCardHolderID());

    Document document = new Document(new Rectangle(200, 315), 30f, 30f, 30f, 30f);
    String pdfFileName = createPdf(fileName.toString(), vaouche, document);
    return pdfFileName;
}

From source file:com.apcb.utils.utils.PdfCreator.java

public static String createPdfTicket(Request request, PropertiesReader prop, String fileName) throws Exception {
    String ticketsPath = prop.getProperty("ServerHTMLPath", false) + prop.getProperty("TicketsPath", false);
    String TicketsTemplatePath = prop.getProperty("ServerHTMLPath", false)
            + prop.getProperty("TicketsTemplatePath", false);
    String TicketsTemplateName = prop.getProperty("TicketsTemplateName", false);

    int ticketsWidthPage = 230;
    if (prop.getProperty("TicketsWidthPage", false) != null) {
        try {//from ww w. j a v  a 2  s .  co  m
            ticketsWidthPage = Integer.valueOf(prop.getProperty("TicketsWidthPage", false));
        } catch (Exception e) {
            log.error("Error to parse TicketsWidthPage error in value "
                    + prop.getProperty("TicketsWidthPage", false), e);
        }
    }

    int ticketsHeightPage = 800;
    if (prop.getProperty("TicketsHeightPage", false) != null) {
        try {
            ticketsHeightPage = Integer.valueOf(prop.getProperty("TicketsHeightPage", false));
        } catch (Exception e) {
            log.error("Error to parse TicketsHeightPage error in value "
                    + prop.getProperty("TicketsHeightPage", false), e);
        }
    }

    HtmlTemplateReader htmlTemplateReader = new HtmlTemplateReader(TicketsTemplateName, TicketsTemplatePath);

    Document document = new Document(new Rectangle(ticketsWidthPage, ticketsHeightPage), 30f, 30f, 30f, 30f);
    String pdfFileName = PdfCreator.createPdfWStyles(ticketsPath + fileName,
            htmlTemplateReader.process(request), document, htmlTemplateReader.getSourcesFile().get("css"),
            prop.getProperty("ServerHTMLPath", false) + prop.getProperty("ImagesSourcesPath", false));

    return pdfFileName;
}

From source file:com.app.gpo.pdf.utils.AbstractITextPdfView.java

License:Open Source License

protected Document newDocument() {

    Document document = new Document();

    Rectangle pageSize = new Rectangle(226, 141);
    //226,7206478
    //141,6984733

    document.setPageSize(pageSize);/*from  ww  w.  jav a2 s.  c  o m*/
    document.setMargins(2, 2, 2, 2);

    return document;

}

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 .ja  v  a  2s .  com*/

    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.automaster.autoview.server.servlet.TextStateOperators.java

/**
 * Creates a PDF document./*w w  w  .  jav a  2 s.  c o  m*/
 * @param filename the path to the new PDF document
 * @throws DocumentException 
 * @throws IOException
 */
public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Rectangle rect = new Rectangle(595, 842);
    Document document = new Document(rect, 30, 30, 30, 30);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    //PdfAcroForm canva = writer.getAcroForm();

    BaseFont bf = BaseFont.createFont();

    //canva.addMultiLineTextField("txtTeste", "texto de teste vamos ver se le quebra a linha", bf, 15, 300, 800, 100, 100);

    PdfContentByte canvas = writer.getDirectContent();
    String text = "AWAY again";
    String text1 = "TESTE Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto adriano";
    canvas.beginText();
    // line 1
    canvas.setFontAndSize(bf, 16);
    canvas.moveText(36, 800);
    canvas.moveTextWithLeading(0, -24);
    canvas.setTextRise(10);
    canvas.showText(text);
    // line 2
    canvas.setWordSpacing(20);
    canvas.newlineShowText(text);
    // line 3
    canvas.setCharacterSpacing(10);
    canvas.newlineShowText(text);
    canvas.setWordSpacing(0);
    canvas.setCharacterSpacing(0);
    // line 4
    canvas.setHorizontalScaling(50);
    canvas.newlineShowText(text);
    canvas.setHorizontalScaling(100);
    // line 5
    canvas.newlineShowText(text);
    canvas.setTextRise(15);
    canvas.setFontAndSize(bf, 12);
    canvas.setColorFill(BaseColor.RED);
    canvas.showText("2");
    canvas.setColorFill(GrayColor.GRAYBLACK);
    // line 6
    canvas.setLeading(56);
    canvas.setMiterLimit(5);
    canvas.newlineShowText(
            "Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto" + text);
    canvas.setLeading(24);
    canvas.newlineText();
    Paragraph paragraph = new Paragraph("teste");
    PdfWriter pdfWriter = canvas.getPdfWriter();
    PdfAcroForm pdfAcroForm = pdfWriter.getAcroForm();
    //pdfAcroForm.addMultiLineTextField("txtTeste", "Changing the adriano leading: Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto", bf, 12, 30, 650, 550, 750);
    //pdfAcroForm.addHiddenField("txtTeste", text); 
    PdfFormField pdfFormField = new PdfFormField(pdfWriter, 30, 650, 550, 750, null);
    pdfFormField.setFieldName("txtTeste");
    pdfFormField.setValueAsString(text1);
    //TextField textField = new TextField(canvas.getPdfWriter(), new Rectangle(30, 650, 550, 750), "txtTest");
    //textField.setText(text);
    pdfAcroForm.addFormField(pdfFormField);
    // line 7
    PdfTextArray array = new PdfTextArray("A");
    array.add(120);
    array.add("W");
    array.add(120);
    array.add("A");
    array.add(95);
    array.add("Y again");
    canvas.showText(array);
    canvas.endText();

    canvas.setColorFill(BaseColor.BLUE);
    canvas.beginText();
    canvas.setTextMatrix(360, 770);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 730);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 690);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    canvas.beginText();
    canvas.setTextMatrix(360, 650);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();

    PdfTemplate template = canvas.createTemplate(200, 36);
    template.setLineWidth(2);
    for (int i = 0; i < 6; i++) {
        template.moveTo(0, i * 6);
        template.lineTo(200, i * 6);
    }
    template.stroke();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 610);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 610);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 570);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 570);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 530);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 530);
    canvas.restoreState();

    canvas.saveState();
    canvas.beginText();
    canvas.setTextMatrix(360, 490);
    canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
    canvas.setFontAndSize(bf, 24);
    canvas.showText(text);
    canvas.endText();
    canvas.addTemplate(template, 360, 490);
    canvas.restoreState();

    // step 5
    //document.add((Element) pdfAcroForm);
    document.close();
}

From source file:com.coderbd.pos.pdf.OrderFileBuilder.java

public String makePdf(ShopOrder shopOrder) {
    Document document = new Document(new Rectangle(205, 800));
    String fileName = directory + "\\" + shopOrder.getCustomerOrder().getOrderBarcode() + ".pdf";
    String receiptText = receipt.getIndentedOrder(shopOrder);
    System.out.println(receiptText);

    document.setMargins(3, 2, 2, 2);// w  w  w  .  ja va 2s  . com

    Font courierFont = FontFactory.getFont("courier");
    courierFont.setSize(10f);

    try {
        PdfWriter.getInstance(document, new FileOutputStream(fileName));

        document.open();
        document.add(new Paragraph(receiptText, courierFont));
        document.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return fileName;
}

From source file:com.dev.saurabh.TiffToPdf.java

License:Open Source License

/**
 * @param args/*from  w w w. j av  a 2 s .c  o m*/
 * @throws DocumentException
 * @throws IOException
 */
public static void main(String[] args) throws DocumentException, IOException {

    String imgeFilename = "/home/saurabh/Downloads/image.tif";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream("/home/saurabh/Desktop/out" + Math.random() + ".pdf"));
    writer.setStrictImageSequence(true);
    document.open();

    document.add(new Paragraph("Multipages tiff file"));
    Image image;
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
    int pages = TiffImage.getNumberOfPages(ra);
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(ra, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.add(image);
        document.newPage();
    }

    document.close();

}

From source file:com.ephesoft.dcma.imagemagick.impl.ITextPDFCreator.java

License:Open Source License

/**
 * Converts specified tiff file into pdf.
 * /*from  ww w.  j av a  2 s  .co  m*/
 * @param tiffFile{@link File} to be converted into pdf.
 * @throws DCMAApplicationException if any error occurs while conversion.
 */
public static void convertTiffIntoPdf(final File tiffFile) throws DCMAApplicationException {
    if (null == tiffFile) {
        LOGGER.error("Unable to convert tiff file as specified file is null.");
    } else {
        com.itextpdf.text.Document document = null;
        RandomAccessFile randomAccessFile = null;
        RandomAccessFileOrArray randomAccessFileOrArray = null;
        FileChannelRandomAccessSource fileChannelRandomAccessSource = null;
        try {
            final String tiffFilePath = tiffFile.getAbsolutePath();
            if (tiffFilePath.endsWith(FileType.TIF.getExtensionWithDot())
                    || tiffFilePath.endsWith(FileType.TIFF.getExtensionWithDot())) {
                randomAccessFile = new RandomAccessFile(tiffFile, ICommonConstants.READ_MODE);
                fileChannelRandomAccessSource = new FileChannelRandomAccessSource(
                        randomAccessFile.getChannel());
                document = new com.itextpdf.text.Document();
                final int lastIndexofTiffExtension = tiffFilePath.toLowerCase()
                        .lastIndexOf(FileType.TIF.getExtensionWithDot());
                PdfWriter.getInstance(document,
                        new FileOutputStream(EphesoftStringUtil.concatenate(
                                tiffFilePath.substring(0, lastIndexofTiffExtension),
                                FileType.PDF.getExtensionWithDot())));
                document.open();
                randomAccessFileOrArray = new RandomAccessFileOrArray(fileChannelRandomAccessSource);
                final int pageCount = TiffImage.getNumberOfPages(randomAccessFileOrArray);
                Image image;
                for (int index = 1; index <= pageCount; index++) {
                    image = TiffImage.getTiffImage(randomAccessFileOrArray, index);
                    final Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
                    document.setPageSize(pageSize);
                    document.newPage();
                    document.add(image);
                }
                LOGGER.info(EphesoftStringUtil.concatenate(tiffFilePath, " successfully converted into PDF."));
            } else {
                LOGGER.error("Unable to convert as specified file is not a valid tiff file.");
            }
        } catch (final DocumentException e) {
            LOGGER.error("DocumentException is occurred while processing specified tiff file for conversion.");
            throw new DCMAApplicationException(EphesoftStringUtil
                    .concatenate("DocumentException occured while generating PDF", e.getMessage()), e);
        } catch (final IOException e) {
            LOGGER.error("IOException is occurred while processing specified tiff file for conversion.");
            throw new DCMAApplicationException(
                    EphesoftStringUtil.concatenate("IOException occured while generating PDF", e.getMessage()),
                    e);
        } finally {
            FileUtils.closeStream(randomAccessFileOrArray);
            FileUtils.closeFileChannelRandomAccessSource(fileChannelRandomAccessSource);
            FileUtils.closeResource(randomAccessFile);
            document.close();
        }

    }
}