Example usage for com.itextpdf.text Document setMargins

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

Introduction

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

Prototype


public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) 

Source Link

Document

Sets the margins.

Usage

From source file:nl.infosys.hartigehap.barSystem.domain.Bon.java

/**
 * Creates a PDF document.//w  w w . ja  v  a  2 s. co m
 *
 * @param filename the path to the new PDF document
 * @throws DocumentException
 * @throws IOException
 */
private void create() {
    try {

        Document document = new Document(PageSize.A4);

        PdfWriter.getInstance(document, new FileOutputStream(file));

        document.open();

        document.add(header());

        document.add(Chunk.NEWLINE);

        document.add(table());

        document.setMargins(0, 0, 0, 100);

        document.close();

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

From source file:nl.infosys.hartigehap.barSystem.presentation.BonGui.java

/**
 * Creates a PDF document./*  w w w  . j a  v a 2 s  .  c  o m*/
 *
 * @param filename the path to the new PDF document
 * @throws DocumentException
 * @throws IOException
 */
private void createPdf() {
    try {

        Document document = new Document(PageSize.A4);

        PdfWriter.getInstance(document, new FileOutputStream(file));

        document.open();

        document.add(header());

        document.add(Chunk.NEWLINE);

        document.add(table());

        document.setMargins(0, 0, 0, 100);

        document.close();

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

From source file:objects.manipulate.java

public static void createPDF(String filename, String[] RESOURCES)
        throws DocumentException, FileNotFoundException, IOException {
    Document document = new Document();
    document.setMargins(0, 0, 0, 0);
    Rectangle rectangle = new Rectangle(0, 0, 742, 960);
    document.setPageSize(rectangle);/*from w  ww . j a v a2s. c om*/
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();

    Image img;
    for (int i = 0; i < RESOURCES.length; i++) {
        //img = Image.getInstance(String.format("resources/img/%s", RESOURCES[i]));
        img = Image.getInstance(RESOURCES[i]);
        if (img.getScaledWidth() > 742 || img.getScaledHeight() > 960) {
            img.scaleToFit(742, 960);
        }

        document.add(img);
    }

    document.close();
}

From source file:org.alex73.skarynka.scan.process.pdf.PdfCreator.java

License:Open Source License

public static void create(File outFile, File[] jpegs) throws Exception {
    Document pdf = new Document();
    pdf.setMargins(0, 0, 0, 0);

    Image image0 = Jpeg.getInstance(jpegs[0].getPath());
    pdf.setPageSize(new Rectangle(0, 0, image0.getScaledWidth(), image0.getScaledHeight()));

    PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(outFile));

    pdf.open();//from  www  .j  a  va 2 s  .  c om
    float minWidth = Float.MAX_VALUE, maxWidth = Float.MIN_VALUE, minHeight = Float.MAX_VALUE,
            maxHeight = Float.MIN_VALUE;
    for (File jpeg : jpegs) {

        Image image = Jpeg.getInstance(jpeg.getPath());

        float width, height;

        width = image.getScaledWidth();
        height = image.getScaledHeight();
        minWidth = Math.min(minWidth, width);
        maxWidth = Math.max(maxWidth, width);
        minHeight = Math.min(minHeight, height);
        maxHeight = Math.max(maxHeight, height);

        pdf.setPageSize(new Rectangle(0, 0, width, height));
        pdf.newPage();
        pdf.add(image);
    }

    pdf.close();
    writer.flush();
    writer.close();
}

From source file:org.jaqpot.core.service.data.ReportService.java

public void report2PDF(Report report, OutputStream os) {

    Document document = new Document();
    document.setPageSize(PageSize.A4);//w  w w.  ja  v  a  2s  .  c om
    document.setMargins(50, 45, 80, 40);
    document.setMarginMirroring(false);

    try {
        PdfWriter writer = PdfWriter.getInstance(document, os);
        TableHeader event = new TableHeader();
        writer.setPageEvent(event);

    } catch (DocumentException ex) {
        throw new InternalServerErrorException(ex);
    }

    document.open();

    /** setup fonts for pdf */
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 9, Font.ITALIC);
    Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC);
    Font paragraphFontBold = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
    Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
    Font tableFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);

    /** print link to jaqpot*/
    Chunk chunk = new Chunk(
            "This report has been automatically created by the JaqpotQuatro report service. Click here to navigate to our official webpage",
            ffont);
    chunk.setAnchor("http://www.jaqpot.org");

    Paragraph paragraph = new Paragraph(chunk);
    paragraph.add(Chunk.NEWLINE);

    Chapter chapter = new Chapter(paragraph, 1);
    chapter.setNumberDepth(0);

    /** get title */
    String title = null;
    if (report.getMeta() != null && report.getMeta().getTitles() != null
            && !report.getMeta().getTitles().isEmpty())
        title = report.getMeta().getTitles().iterator().next();

    /** print title aligned centered in page */
    if (title == null)
        title = "Report";
    chunk = new Chunk(title, chapterFont);
    paragraph = new Paragraph(chunk);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    paragraph.add(Chunk.NEWLINE);
    paragraph.add(Chunk.NEWLINE);

    chapter.add(paragraph);

    /** report Description */
    if (report.getMeta() != null && report.getMeta().getDescriptions() != null
            && !report.getMeta().getDescriptions().isEmpty()
            && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) {
        paragraph = new Paragraph();
        paragraph.add(new Chunk("Description: ", paragraphFontBold));
        paragraph.add(new Chunk(report.getMeta().getDescriptions().toString().replaceAll(":http", ": http"),
                paragraphFont));
        chapter.add(paragraph);
        chapter.add(Chunk.NEWLINE);
    }

    /** report model, algorithm and/or dataset id */
    if (report.getMeta() != null && report.getMeta().getHasSources() != null
            && !report.getMeta().getHasSources().isEmpty() && !report.getMeta().getDescriptions().isEmpty()
            && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) {
        Iterator<String> sources = report.getMeta().getHasSources().iterator();
        sources.forEachRemaining(o -> {
            if (o != null) {
                String[] source = o.split("/");
                if (source[source.length - 2].trim().equals("model")
                        || source[source.length - 2].trim().equals("algorithm")
                        || source[source.length - 2].trim().equals("dataset")) {
                    Paragraph paragraph1 = new Paragraph();
                    paragraph1.add(new Chunk(source[source.length - 2].substring(0, 1).toUpperCase()
                            + source[source.length - 2].substring(1) + ": ", paragraphFontBold));
                    paragraph1.add(new Chunk(source[source.length - 1], paragraphFont));
                    chapter.add(paragraph1);
                    chapter.add(Chunk.NEWLINE);
                }
            }
        });
    }

    /** report single calculations */
    report.getSingleCalculations().forEach((key, value) -> {
        Paragraph paragraph1 = new Paragraph();
        paragraph1 = new Paragraph();
        paragraph1.add(new Chunk(key + ": ", paragraphFontBold));
        paragraph1.add(new Chunk(value.toString().trim().replaceAll(" +", " "), paragraphFont));
        chapter.add(paragraph1);
        chapter.add(Chunk.NEWLINE);
    });

    /** report date of completion */
    if (report.getMeta() != null && report.getMeta().getDate() != null) {
        Paragraph paragraph1 = new Paragraph();
        paragraph1.add(new Chunk("Procedure completed on: ", paragraphFontBold));
        paragraph1.add(new Chunk(report.getMeta().getDate().toString(), paragraphFont));
        chapter.add(paragraph1);
        chapter.add(Chunk.NEWLINE);
    }

    try {
        document.add(chapter);
    } catch (DocumentException ex) {
        throw new InternalServerErrorException(ex);
    }

    Integer chapterNumber = 0;

    /** report all_data */
    for (Entry<String, ArrayCalculation> entry : report.getArrayCalculations().entrySet()) {
        String label = entry.getKey();
        ArrayCalculation ac = entry.getValue();
        PdfPTable table = new PdfPTable(ac.getColNames().size() + 1);
        for (Entry<String, List<Object>> row : ac.getValues().entrySet()) {

            try {
                XMLWorkerHelper.getInstance().parseXHtml(w -> {
                    if (w instanceof WritableElement) {
                        List<Element> elements = ((WritableElement) w).elements();
                        for (Element element : elements) {
                            PdfPCell pdfCell = new PdfPCell();
                            pdfCell.addElement(element);
                            table.addCell(pdfCell);
                        }
                    }
                }, new StringReader(row.getKey()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            for (Object o : row.getValue()) {
                table.addCell(o.toString());
            }
            table.completeRow();
        }
        try {
            Chunk tableChunk = new Chunk(label, tableFont);
            Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber);
            tableChapter.add(Chunk.NEWLINE);
            tableChapter.add(table);
            document.newPage();
            document.add(tableChapter);
        } catch (DocumentException ex) {
            throw new InternalServerErrorException(ex);
        }
    }

    /** report plots */
    for (Entry<String, String> entry : report.getFigures().entrySet()) {
        try {
            byte[] valueDecoded = Base64.decodeBase64(entry.getValue());
            Image l = Image.getInstance(valueDecoded);
            document.newPage();
            //image starts at the half's half of pdf page
            l.setAbsolutePosition(0, (document.getPageSize().getHeight() / 2 / 2));
            l.scaleToFit(document.getPageSize());

            Chunk tableChunk = new Chunk(entry.getKey(), tableFont);
            Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber);
            tableChapter.add(l);
            document.add(tableChapter);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
    document.close();
}

From source file:org.javad.stamp.pdf.PdfGenerator.java

License:Apache License

public void setMargins(Document document) {
    document.setMargins(PdfUtil.convertFromMillimeters(config.getMarginLeft()),
            PdfUtil.convertFromMillimeters(config.getMarginRight()),
            PdfUtil.convertFromMillimeters(config.getMarginTop()),
            PdfUtil.convertFromMillimeters(config.getMarginBottom()));
}

From source file:org.opensrp.web.utils.PdfUtil.java

License:Open Source License

public static ByteArrayOutputStream generatePdf(List<String> data, int width, int height, int copiesImage,
        int columnLimit) {
    try {//from w ww .ja  v a  2  s.  co m
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Document document = new Document();
        document.setMargins(MARGINS[0], MARGINS[1], MARGINS[2], MARGINS[3]);

        PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();

        PdfPTable table = new PdfPTable(columnLimit);
        table.setTotalWidth(TABLE_WIDTH);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);

        int length = 0;
        int count = 0;

        for (String str : data) {
            if (str.length() > 0 && str.length() <= 5) {
                length = 54;
            } else if (str.length() >= 6 && str.length() <= 9) {
                length = 44;
            } else if (str.length() >= 10 && str.length() <= 11) {
                length = 36;
            } else if (str.length() >= 12 && str.length() <= 14) {
                length = 27;
            } else if (str.length() >= 15 && str.length() <= 17) {
                length = 22;
            } else {
                length = 15;
            }
            Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix byteMatrix = null;

            byteMatrix = qrCodeWriter.encode(str, BarcodeFormat.QR_CODE, width, height, hintMap);

            int matrixWidth = byteMatrix.getWidth();
            int matrixHeight = byteMatrix.getHeight();
            BufferedImage image = new BufferedImage(matrixWidth, matrixHeight, BufferedImage.TYPE_INT_RGB);
            image.createGraphics();
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, matrixWidth + 5, matrixHeight + 5);
            graphics.setFont(graphics.getFont().deriveFont(13f));
            graphics.setColor(Color.BLACK);
            graphics.drawString(str, length, height - 10);
            for (int i = 0; i < matrixHeight; i++) {
                for (int j = 0; j < matrixHeight; j++) {
                    if (byteMatrix.get(i, j)) {
                        graphics.fillRect((i), j, 1, 1);
                    }
                }
            }
            Image itextImage = null;
            itextImage = Image.getInstance(Toolkit.getDefaultToolkit().createImage(image.getSource()), null);

            for (int i = 0; i < copiesImage; i++) {
                PdfPCell cell = new PdfPCell(itextImage);
                cell.setBorder(Rectangle.NO_BORDER);
                count++;
                table.addCell(cell);
            }
        }
        for (int i = 0; i < 6; i++) {
            if (count % columnLimit != 0) {
                PdfPCell cell = new PdfPCell(new Phrase());
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
                count++;
            }
        }
        document.add(table);
        document.close();

        return byteArrayOutputStream;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.sharegov.cirm.utils.PDFViewReport.java

License:Apache License

public void generateReport(OutputStream out, List<Long> boids) {
    if (DBG)/*from  w w  w. j ava2s .  co  m*/
        System.out.println("Start: PDFgenerateReport: for nrOfBoids: " + boids.size());
    Document doc = null;
    try {
        Date date = new Date();
        setTime(formatDate(date, true, false));
        doc = new Document(PageSize.A4);
        doc.setMargins(9, 9, doc.topMargin(), doc.bottomMargin());
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        writer.setPageEvent(new TableHeader());
        doc.open();
        //addMetaData(doc);
        LegacyEmulator le = new LegacyEmulator();
        int i = 1;
        for (Long boid : boids) {
            ThreadLocalStopwatch.getWatch().time("PDFViewReport loading " + i + " of " + boids.size());
            Json data = le.findServiceCaseOntology(boid).toJSON();
            addContent(doc, data);
            i++;
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        doc.close();
    }
    if (DBG)
        System.out.println("Done: PDFgenerateReport: for nrOfBoids: " + boids.size());
}

From source file:org.sharegov.cirm.utils.PDFViewReport.java

License:Apache License

/**
 * Generates the HET Rebate letter based on the given input parameters
 * @param out : OutputStream to which the letter is written to
 * @param applicant : ServiceCaseActor of type Applicant
 * @param hasCaseNumber : Service Request's Case Number 
 * @param isEnglish : A Flag denoting the language of the letter
 */// w w w  .  j  a v  a2 s  .  c o  m
public void generateHETRebateLetter(OutputStream out, Json applicant, String hasCaseNumber, boolean isEnglish) {
    if (DBG)
        System.out.println("Start : generateHETRebateLetter");
    Document doc = null;
    try {
        doc = new Document(PageSize.A4);
        doc.setMargins(9, 9, doc.topMargin(), doc.bottomMargin());
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        doc.open();

        addWASDContent(doc, applicant, hasCaseNumber, isEnglish);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        doc.close();
        if (DBG)
            System.out.println("End : generateHETRebateLetter");
    }
}

From source file:org.sharegov.cirm.utils.PDFViewReport.java

License:Apache License

public void errorReport(OutputStream out) {
    if (DBG)/* w  w  w.  j ava  2  s  .  c o m*/
        System.out.println("Start: PDF errorReport");
    try {
        Date date = new Date();
        setTime(formatDate(date, true, false));
        Document doc = new Document(PageSize.A4);
        doc.setMargins(9, 9, doc.topMargin(), doc.bottomMargin());
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        TableHeader th = new TableHeader();
        writer.setPageEvent(th);
        doc.open();

        Chapter chapter = new Chapter(new Paragraph(), 1);
        chapter.setNumberDepth(0);
        addSection(chapter).add(new Phrase(" "));
        addSection(chapter).add(new Phrase(" "));
        addSection(chapter).add(new Phrase(genericErrorMsg));
        doc.add(chapter);
        doc.close();
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    if (DBG)
        System.out.println("Done: PDF errorReport");
}