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:com.kohmiho.mpsr.export.PDFGenerator.java

private void generatePageHeader(Document document, PdfContentByte directContentUnder, Image image,
        Phrase[] headerTexts) {/*from w w  w . ja  v a  2  s .c  o  m*/

    float left = document.getPageSize().getLeft(36);
    float top = document.getPageSize().getTop(36);
    float right = document.getPageSize().getRight(36);

    try {
        image.setAbsolutePosition(right - 150, top - 20);
        // image.setAlignment(Element.ALIGN_RIGHT);
        image.scalePercent(25);
        directContentUnder.addImage(image);
    } catch (DocumentException e) {
    }

    int i = 0;
    for (Phrase headerText : headerTexts) {
        ColumnText.showTextAligned(directContentUnder, Element.ALIGN_LEFT, headerText, left + 36,
                top - 10 * (i++), 0);
    }
}

From source file:com.masscustsoft.service.ToPdf.java

License:Open Source License

private Image getImage(Map row) throws Exception {
    Image image = null;/* w w w . j  av  a2s.c o  m*/
    String url = (String) row.get("url");
    if (url != null) {
        image = Image.getInstance(url);
    }
    String externalId = (String) row.get("externalId");
    if (externalId != null) {
        File tmp = File.createTempFile("tmp", ".image");
        InputStream is = getFs().getResource(externalId);
        FileOutputStream os = new FileOutputStream(tmp);
        StreamUtil.copyStream(is, os, 0);
        is.close();
        os.close();
        image = Image.getInstance(tmp.toURL());
        ThreadHelper.postponeDelete(tmp);
    }
    String img = (String) row.get("image");
    if (img != null) {
        byte[] bytes = LightStr.getHexContent(img);
        image = Image.getInstance(bytes);
    }
    if (image != null) {
        MapUtil.setIfFloat(row, "spacingAfter", image);
        MapUtil.setIfFloat(row, "spacingBefore", image);
        MapUtil.setIfFloat(row, "scalePercent", image);
        MapUtil.setIfFloat(row, "scaleDegree", image);
        Float fitPer = MapUtil.getFloat(row, "fitPercent", null);
        if (fitPer != null) {
            Document doc = this.getDoc();
            image.scaleToFit(
                    (doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin()) * fitPer / 100f,
                    (doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin()) * fitPer / 100f);
        }
        Float fitWidth = MapUtil.getFloat(row, "fitWidth", null);
        if (fitWidth != null) {
            Float fitHeight = MapUtil.getFloat(row, "fitHeight", fitWidth);
            image.scaleToFit(fitWidth, fitHeight);
        }
        image.setAlignment(getAlignment(row, "alignment"));
    }
    return image;
}

From source file:com.masscustsoft.service.ToPdf.java

License:Open Source License

@Override
public Image createImage(String src, final Map<String, String> attrs, final ChainedProperties chain,
        final DocListener document, final ImageProvider img_provider, final HashMap<String, Image> img_store,
        final String img_baseurl) throws DocumentException, IOException {
    Image img = null;/*from w  w  w  .j  a va 2 s. c om*/
    // getting the image using an image provider
    if (img_provider != null)
        img = img_provider.getImage(src, attrs, chain, document);
    // getting the image from an image store
    if (img == null && img_store != null) {
        Image tim = img_store.get(src);
        if (tim != null)
            img = Image.getInstance(tim);
    }
    if (img != null)
        return img;
    ////if src start with data: it's dataUri and parse it imme.
    if (src.startsWith("remote?")) {
        BeanFactory bf = BeanFactory.getBeanFactory();
        String pp = src.substring(7);
        String[] ss = pp.split("\\&");
        try {
            String id = "~", fsId = LightUtil.getRepository().getFsId();
            for (String s : ss) {
                String[] sss = s.split("=");
                if (sss[0].equals("id"))
                    id = sss[1];
                if (sss[0].equals("fsId"))
                    fsId = sss[1];
            }
            IRepository fs = bf.getRepository(fsId);

            InputStream is = fs.getResource(id);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            StreamUtil.copyStream(is, os, 0);
            is.close();
            os.close();
            img = Image.getInstance(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (src.startsWith("data:")) {
        int i = src.indexOf(",");
        byte[] bits = Base64.decode(src.substring(i + 1));
        img = Image.getInstance(bits);
    } else {
        ////
        // introducing a base url
        // relative src references only
        if (!src.startsWith("http") && img_baseurl != null) {
            src = img_baseurl + src;
        } else if (img == null && !src.startsWith("http")) {
            String path = chain.getProperty(HtmlTags.IMAGEPATH);
            if (path == null)
                path = "";
            src = new File(path, src).getPath();
        }
        img = Image.getInstance(src);
    }

    if (img == null)
        return null;

    float actualFontSize = HtmlUtilities.parseLength(chain.getProperty(HtmlTags.SIZE),
            HtmlUtilities.DEFAULT_FONT_SIZE);
    if (actualFontSize <= 0f)
        actualFontSize = HtmlUtilities.DEFAULT_FONT_SIZE;
    String width = attrs.get(HtmlTags.WIDTH);
    float widthInPoints = HtmlUtilities.parseLength(width, actualFontSize);
    String height = attrs.get(HtmlTags.HEIGHT);

    float heightInPoints = HtmlUtilities.parseLength(height, actualFontSize);

    if (widthInPoints == 0 && heightInPoints == 0) {
        Document doc = (Document) document;
        widthInPoints = doc.getPageSize().getWidth();
    }

    if (widthInPoints > 0 && heightInPoints > 0) {
        img.scaleAbsolute(widthInPoints, heightInPoints);
    } else if (widthInPoints > 0) {
        heightInPoints = img.getHeight() * widthInPoints / img.getWidth();
        img.scaleAbsolute(widthInPoints, heightInPoints);
    } else if (heightInPoints > 0) {
        widthInPoints = img.getWidth() * heightInPoints / img.getHeight();
        img.scaleAbsolute(widthInPoints, heightInPoints);
    }

    String before = chain.getProperty(HtmlTags.BEFORE);
    if (before != null)
        img.setSpacingBefore(Float.parseFloat(before));
    String after = chain.getProperty(HtmlTags.AFTER);
    if (after != null)
        img.setSpacingAfter(Float.parseFloat(after));
    img.setWidthPercentage(0);
    return img;
}

From source file:com.mobicage.rogerthat.enterprise.samples.hr.bizz.GenerateExpenseNote.java

License:Open Source License

public int handle(final User user, final User manager, final ExpenseNote en)
        throws MalformedURLException, IOException, DocumentException {

    log.info("Building list of expenses ...");
    List<Expense> expenses = Expense.list(en);
    log.info("Retrieved " + expenses.size() + " expenses from the datastore");

    log.info("Creating ExpenseNoteDocOutputStream");
    ExpenseNoteDocOutputStream stream = new ExpenseNoteDocOutputStream(en);

    Document document = new Document();
    PdfWriter.getInstance(document, stream);
    document.open();//from w ww . ja va 2 s  .c  om

    document.addTitle("Expense note " + en.id + " of " + user.name);
    document.addSubject("Expense note generated by Rogerthat Enterprise!");
    document.addKeywords("expense note");
    document.addAuthor(user.name);
    document.addCreator("Rogerthat OneApp Enterprise Mobility");

    Paragraph preface = new Paragraph();

    preface.add(new Paragraph("TP Vision expense note", titleFont));
    preface.add(new Paragraph(" "));

    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = new Date();
    preface.add(new Paragraph("Date: " + dateFormat.format(date)));
    preface.add(new Paragraph("Requestor: " + user.name));
    preface.add(new Paragraph("Approver: " + manager.name));
    preface.add(new Paragraph(" "));

    PdfPTable table = new PdfPTable(7);
    table.setWidthPercentage(110);
    table.setWidths(new int[] { 5, 15, 15, 35, 10, 15, 10 });
    addHeader(table, "Id");
    addHeader(table, "Date");
    addHeader(table, "Nature");
    addHeader(table, "Description");
    addHeader(table, "Account");
    addHeader(table, "Amount");
    addHeader(table, "Voucher");
    table.setHeaderRows(1);

    Collections.sort(expenses, new Comparator<Expense>() {
        @Override
        public int compare(Expense e1, Expense e2) {
            return (int) (e1.date - e2.date);
        }
    });
    int i = 0;
    double total = 0;
    for (Expense expense : expenses) {
        PdfPCell c1 = new PdfPCell(new Phrase("" + ++i));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.addCell(dateFormat.format(new Date(expense.date * 1000)));
        table.addCell(expense.nature);
        table.addCell(expense.description);
        table.addCell("" + expense.account);
        c1 = new PdfPCell(new Phrase(DECIMAL_FORMAT.format(expense.amount) + " " + expense.currency));
        c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(c1);
        table.addCell(expense.voucher);
        total += expense.amount;
    }

    preface.add(table);

    preface.add(new Paragraph(" "));
    preface.add(new Paragraph("Total: " + DECIMAL_FORMAT.format(total), titleFont));

    document.add(preface);

    i = 0;
    for (Expense expense : expenses) {
        i++;
        if (expense.receipt == null)
            continue;

        document.newPage();
        Paragraph receipt = new Paragraph();
        receipt.add(new Paragraph("Attachment " + i, titleFont));
        document.add(receipt);
        Image image = Image.getInstance(new URL(expense.receipt));
        image.setRotationDegrees(-90);
        float scaler = (document.getPageSize().getWidth() / image.getWidth()) * 100;

        image.scalePercent(scaler);
        document.add(image);
    }

    document.close();
    stream.close();

    return stream.getSize();

}

From source file:com.norbsoft.pdfconverter.helpers.PDFHelper.java

License:Open Source License

public int generate(String saveUrl, SerializableBitmap sign, Form form, ArrayList<String> photos,
        ArrayList<String> workers) {
    try {/*from   w  ww . j av  a 2s  .  co  m*/
        Document document = new Document();

        url = saveUrl;
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(url));
        document.setMargins(20, 20, 20, 20);
        document.open();

        Bitmap inputLogo = BitmapFactory.decodeStream(context.getAssets().open("logo.jpg"));
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        inputLogo.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
        Image logo = Image.getInstance(outstream.toByteArray());

        Bitmap inputQR = BitmapFactory.decodeStream(context.getAssets().open("qr.jpg"));
        outstream = new ByteArrayOutputStream();
        inputQR.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
        Image qr = Image.getInstance(outstream.toByteArray());

        outstream = new ByteArrayOutputStream();
        sign.getImage().compress(Bitmap.CompressFormat.JPEG, 100, outstream);
        Image sgn = Image.getInstance(outstream.toByteArray());

        qr.scaleAbsolute(90f, 90f);
        qr.setAbsolutePosition(340f, 705f);

        logo.scaleAbsolute(150f, 50f);
        logo.setAbsolutePosition(50f, 750f);

        sgn.scaleAbsolute(130f, 30f);
        sgn.setAbsolutePosition(25f, 75f);

        Paragraph p = new Paragraph("\r\n\r\n\r\nMPWiK S.A.\r\n50-421 Wrocaw\r\nul.Na Grobli 14-16", normal);
        p.setIndentationLeft(420f);
        document.add(p);

        p = new Paragraph("RAPORT WYMIANY WODOMIERZA", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingBefore(60f);
        document.add(p);

        document.add(table(form));

        p = new Paragraph(form.getInformations(), normal);
        p.setAlignment(Element.ALIGN_LEFT);
        p.setIndentationLeft(50f);
        p.setSpacingBefore(20f);
        document.add(p);

        document.add(signTable(form, sgn, workers));

        document.add(logo);
        document.add(qr);

        if (photos != null && photos.size() > 0) {
            document.newPage();
            for (int i = 0; i < photos.size(); i++) {
                try {
                    if (photos.get(i) != null && !photos.get(i).equals("")) {
                        Log.d(TAG, photos.get(i));
                        Bitmap temp = PictureHelper.bitmapFromUrl(photos.get(i));
                        outstream = new ByteArrayOutputStream();
                        temp.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
                        Image photo = Image.getInstance(outstream.toByteArray());
                        photo.scaleToFit(document.getPageSize().getWidth() - 50,
                                document.getPageSize().getHeight());
                        document.add(photo);
                    }
                } catch (Exception e) {

                }
            }
        }
        document.close();
        writer.close();
        return 1;
    } catch (FileNotFoundException e) {
        Log.e(TAG, e.getMessage());
        return 0;
    } catch (DocumentException e) {
        Log.e(TAG, e.getMessage());
        return 0;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        return 0;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return 0;
    }
}

From source file:com.raghav.plot.ImageIntoPDF.java

public static void main(String[] args) throws Exception {
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/raghav/zzzzz.pdf"));
    document.open();//from   w w w  .ja  va 2  s.c o  m
    document.newPage();

    //for 4 photo
    //        for (int i=0;i<2;i++) {
    //            Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png");
    //            image1.setAbsolutePosition(40,80+(350*i));
    //          image1.scaleAbsolute(200, 260);
    //            document.add(image1);
    //        }
    //          for (int i=0;i<2;i++) {
    //            Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png");
    //            image1.setAbsolutePosition(300, 80+(350*i));
    //          image1.scaleAbsolute(260, 200);
    //            document.add(image1);
    //        }
    //for 6

    float margin = 10;

    float docHeight = ((document.getPageSize().getHeight()) / 3) - (2 * margin);
    float docwidth = ((document.getPageSize().getWidth()) / 2) - (2 * margin);

    for (int i = 0; i < 3; i++) {
        Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg");

        image1.setAbsolutePosition(margin, margin * (i + 1) + (docHeight * i));
        image1.scaleToFit(docwidth, docHeight);
        //image1.scaleAbsolute(190, 130);
        document.add(image1);
    }
    for (int i = 0; i < 3; i++) {
        Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg");
        image1.setAbsolutePosition(docwidth + (2 * margin), margin * (i + 1) + (docHeight * i));
        image1.scaleToFit(docwidth, docHeight);
        document.add(image1);
    }
    document.close();
}

From source file:com.semfapp.adamdilger.semf.Pdf.java

License:Open Source License

private void createPDFNew(String filePath, String htmlString, @Nullable ArrayList<ImageFile> images) {

    File file = null;/*from  w ww  .  j  ava  2  s  .  co  m*/
    try {
        file = new File(filePath);

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        // step 4

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssFile cssFile = XMLWorkerHelper.getCSS(activity.getAssets().open("styles.css"));
        cssResolver.addCss(cssFile);

        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // Pipelines

        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        Drawable d = activity.getResources().getDrawable(R.drawable.logo_icon);
        Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapData = stream.toByteArray();

        Image image = Image.getInstance(bitmapData);
        image.setAbsolutePosition(35, 763);
        image.scalePercent(12);
        document.add(image);

        p.parse(new ByteArrayInputStream(htmlString.getBytes(StandardCharsets.UTF_8)));

        if (images != null) {
            System.out.println("Adding IMage");

            for (int x = 0; x < images.size(); x++) {
                Image cursor = images.get(x).getImage();

                float ratio = cursor.getPlainHeight() / cursor.getPlainWidth();

                float imgWidth = document.getPageSize().getWidth() - 100;
                float imgHeight = document.getPageSize().getHeight() - 100;

                cursor.scaleToFit(new Rectangle(imgWidth, imgHeight));

                document.add(cursor);
            }
        }

        // step 5
        document.close();

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

From source file:com.shiyq.itext.PdfUtil.java

private static void addDescribe(Document document, String describe, FontSelector selector)
        throws DocumentException {
    Paragraph descP = new Paragraph(selector.process(describe));
    descP.setAlignment(Element.ALIGN_JUSTIFIED);
    descP.setIndentationLeft(document.getPageSize().getRight() * 3 / 7);
    document.add(descP);//from   w w w  .j a v a 2  s .  c  om
    document.add(Chunk.NEWLINE);
}

From source file:com.softwaremagico.tm.pdf.complete.events.SheetAlternatedBackgroundEvent.java

License:Open Source License

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    try {/*from  w w w.j  a  v a2 s .  c  o  m*/
        rightCorner = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.RIGHT_CORNER_IMAGE));
        rightCorner.setAbsolutePosition(document.getPageSize().getWidth() - IMAGE_WIDTH,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_TOP_BORDER);
        rightCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        leftCorner = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.LEFT_CORNER_IMAGE));
        // leftCorner.setAbsolutePosition(IMAGE_BORDER,
        // document.getPageSize().getHeight() - IMAGE_HEIGHT -
        // IMAGE_BORDER);
        leftCorner.setAbsolutePosition(IMAGE_BORDER,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_TOP_BORDER);
        leftCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        mainTitleRight = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.MAIN_TITLE_IMAGE));
        // leftCorner.setAbsolutePosition(IMAGE_BORDER,
        // document.getPageSize().getHeight() - IMAGE_HEIGHT -
        // IMAGE_BORDER);
        float barWidth = document.getPageSize().getWidth() - IMAGE_WIDTH - IMAGE_BORDER * 2;
        mainTitleRight.setAbsolutePosition(IMAGE_HEIGHT + IMAGE_BORDER * 2 + 3,
                document.getPageSize().getHeight() - BAR_HEIGHT - IMAGE_TOP_BORDER - 2);
        mainTitleRight.scaleAbsolute(barWidth, BAR_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        mainTitleLeft = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.MAIN_TITLE_IMAGE));
        // leftCorner.setAbsolutePosition(IMAGE_BORDER,
        // document.getPageSize().getHeight() - IMAGE_HEIGHT -
        // IMAGE_BORDER);
        float barWidth = document.getPageSize().getWidth() - IMAGE_WIDTH - IMAGE_BORDER * 2;
        mainTitleLeft.setAbsolutePosition(IMAGE_BORDER * 2 + 3,
                document.getPageSize().getHeight() - BAR_HEIGHT - IMAGE_TOP_BORDER - 2);
        mainTitleLeft.scaleAbsolute(barWidth, BAR_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

}

From source file:com.softwaremagico.tm.pdf.complete.events.SheetBackgroundEvent.java

License:Open Source License

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    try {// w w  w. ja  v  a2 s  .c o  m
        rightCorner = Image
                .getInstance(SheetBackgroundEvent.class.getResource("/" + FadingSunsTheme.RIGHT_CORNER_IMAGE));
        rightCorner.setAbsolutePosition(document.getPageSize().getWidth() - IMAGE_WIDTH,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_BORDER);
        rightCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        leftCorner = Image
                .getInstance(SheetBackgroundEvent.class.getResource("/" + FadingSunsTheme.LEFT_CORNER_IMAGE));
        leftCorner.setAbsolutePosition(IMAGE_BORDER,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_BORDER);
        leftCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        mainTitle = Image
                .getInstance(SheetBackgroundEvent.class.getResource("/" + FadingSunsTheme.MAIN_TITLE_IMAGE));
        float barWeight = document.getPageSize().getWidth() - IMAGE_WIDTH * 2;
        mainTitle.setAbsolutePosition(IMAGE_HEIGHT + IMAGE_BORDER * 2 + 3,
                document.getPageSize().getHeight() - BAR_HEIGHT - IMAGE_BORDER);
        mainTitle.scaleAbsolute(barWeight, BAR_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

}