Example usage for com.itextpdf.text Document rightMargin

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

Introduction

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

Prototype


public float rightMargin() 

Source Link

Document

Return the right margin.

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.com
    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: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. jav  a  2s  .  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.masscustsoft.service.ToPdf.java

License:Open Source License

private Image getImage(Map row) throws Exception {
    Image image = null;/*from   w ww  .j  a  va 2  s.  com*/
    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.vectorprint.report.itext.EventHelper.java

License:Open Source License

/**
 * prepares template for printing header and footer
 *
 * @param writer/*from ww w.j  a  v  a2 s. co m*/
 * @param document
 */
@Override
public final void onOpenDocument(PdfWriter writer, Document document) {
    super.onOpenDocument(writer, document);
    template = writer.getDirectContent().createTemplate(document.getPageSize().getWidth(),
            document.getPageSize().getHeight());
    if (!getSettings().containsKey(PAGEFOOTERSTYLEKEY)) {
        getSettings().put(PAGEFOOTERSTYLEKEY, PAGEFOOTERSTYLE);
    }
    if (!getSettings().containsKey(PAGEFOOTERTABLEKEY)) {
        float tot = ItextHelper
                .ptsToMm(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin());
        getSettings().put(PAGEFOOTERTABLEKEY, new StringBuilder("Table(columns=3,widths=")
                .append(Math.round(tot * getSettings().getFloatProperty(0.85f, "footerleftwidthpercentage")))
                .append('|')
                .append(Math.round(tot * getSettings().getFloatProperty(0.14f, "footermiddlewidthpercentage")))
                .append('|')
                .append(Math.round(tot * getSettings().getFloatProperty(0.01f, "footerrightwidthpercentage")))
                .append(')').toString());
    }
}

From source file:com.vectorprint.report.itext.EventHelper.java

License:Open Source License

/**
 * prints debug info when property debug is true, calls renderHeader and renderFooter and
 * {@link Advanced#draw(com.itextpdf.text.Rectangle, java.lang.String) } with {@link Document#getPageSize() }
 * and null for {@link DefaultStylerFactory#PAGESTYLERS}.
 *
 * @param writer//from  w  w w.j  a va2  s  .  c o m
 * @param document
 */
@Override
public final void onEndPage(PdfWriter writer, Document document) {
    super.onEndPage(writer, document);
    sanitize(writer);
    try {
        if (failuresHereAfter || debugHereAfter) {
            PdfContentByte bg = writer.getDirectContentUnder();
            Rectangle rect = writer.getPageSize();
            rect.setBackgroundColor(itextHelper
                    .fromColor(getSettings().getColorProperty(new Color(240, 240, 240), "legendbackground")));
            bg.rectangle(rect);
            bg.closePathFillStroke();
        } else {
            for (Advanced a : doForAllPages) {
                try {
                    if (a.shouldDraw(null)) {
                        a.draw(document.getPageSize(), null);
                    }
                } catch (VectorPrintException ex) {
                    throw new VectorPrintRuntimeException(ex);
                }
            }
        }
        if (!debugHereAfter && getSettings().getBooleanProperty(false, DEBUG)) {

            PdfContentByte canvas = writer.getDirectContent();

            Rectangle rect = new Rectangle(document.leftMargin(), document.bottomMargin(),
                    document.right() - document.rightMargin(), document.top() - document.topMargin());

            DebugHelper.debugRect(canvas, rect, new float[] { 10, 2 }, 0.3f, getSettings(),
                    stylerFactory.getLayerManager());

        }

        renderHeader(writer, document);
        maxTagForGenericTagOnPage = ((DefaultElementProducer) elementProducer).getAdvancedTag();
        if (getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.PRINTFOOTER)) {
            renderFooter(writer, document);
        } else {
            log.warning("not printing footer, if you want page footers set " + ReportConstants.PRINTFOOTER
                    + " to true");
        }
        maxTagForGenericTagOnPage = Integer.MAX_VALUE;
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException e) {
        throw new VectorPrintRuntimeException("failed to create the report header or footer: ", e);
    }
}

From source file:com.vectorprint.report.itext.style.stylers.SimpleColumns.java

License:Open Source License

@Override
public void setDocument(Document document, com.itextpdf.text.pdf.PdfWriter writer) {
    super.setDocument(document, writer);
    setValue(LEFT, document.leftMargin());
    setValue(RIGHT, document.right() - document.rightMargin());
    setValue(BOTTOM, getDocument().bottomMargin());
    setValue(TOP, getDocument().top() - getDocument().topMargin());
}

From source file:com.vimbox.hr.LicensePDFGenerator.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www .java 2s  .  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/pdf");
    String fileName = request.getParameter("license_name");
    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
    String path = System.getProperty("user.dir") + "/documents/licenses/" + fileName;
    path = path.replaceAll("%20", " ");
    if (ext.equalsIgnoreCase("pdf")) {
        FileInputStream baos = new FileInputStream(path);

        OutputStream os = response.getOutputStream();

        byte buffer[] = new byte[8192];
        int bytesRead;

        while ((bytesRead = baos.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        os.flush();
        os.close();
    } else {
        try {
            // Document Settings //
            Document document = new Document();
            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            // Loading MC //
            PdfPTable table = new PdfPTable(1);
            table.setWidthPercentage(100);
            // the cell object
            PdfPCell cell;

            Image img = Image.getInstance(path);
            int indentation = 0;
            float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()
                    - indentation) / img.getWidth()) * 100;
            img.scalePercent(scaler);
            //img.scaleAbsolute(80f, 80f);
            cell = new PdfPCell(img);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
            document.add(table);
            //-----------------------------------//
            document.close();
        } catch (DocumentException de) {
            throw new IOException(de.getMessage());
        }
    }

}

From source file:de.jost_net.JVerein.io.HeaderFooter.java

License:Open Source License

/**
 * Adds the header and the footer./*w w w . j a v a2  s . c om*/
 * 
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = document.getPageSize();
    switch (writer.getPageNumber() % 2) {
    case 0:
        // ColumnText.showTextAligned(writer.getDirectContent(),
        // Element.ALIGN_RIGHT, header[0], rect.getRight(), rect.getTop(), 0);
        break;
    case 1:
        // ColumnText.showTextAligned(writer.getDirectContent(),
        // Element.ALIGN_LEFT,
        // header[1], rect.getLeft(), rect.getTop(), 0);
        break;
    }
    float left = rect.getLeft() + document.leftMargin();
    float right = rect.getRight() - document.rightMargin();
    float bottom = rect.getBottom() + document.bottomMargin();
    PdfContentByte pc = writer.getDirectContent();
    pc.setColorStroke(BaseColor.BLACK);
    pc.setLineWidth(0.5f);
    pc.moveTo(left, bottom - 5);
    pc.lineTo(right, bottom - 5);
    pc.stroke();
    pc.moveTo(left, bottom - 25);
    pc.lineTo(right, bottom - 25);
    pc.stroke();

    ColumnText.showTextAligned(pc, Element.ALIGN_CENTER,
            new Phrase(footer + " " + pagenumber, Reporter.getFreeSans(7)), (left + right) / 2, bottom - 18, 0);
}

From source file:eu.aniketos.wp1.ststool.report.pdfgenerator.ReportContentFactory.java

License:Open Source License

private void buildSectionSocialDiagram(Section section, Document document) {

    Image i = rsp.generateScrenshot(ViewsManager.SOCIAL_VIEW);
    float reductionScale = fitImageInArea(i,
            document.getPageSize().getWidth() - document.rightMargin() - document.leftMargin(), 310, false);
    if (reductionScale <= getMaximumReductionScale()) {
        setAppendixASocialDiagram(true);
    }/*from   www  .  j  a  v  a 2 s  . com*/

    StringBuilder sectionIntro = new StringBuilder();
    sectionIntro.append(ftc.getFigure(FigureConstant.SOCIAL_DIAGRAM)
            + " presents the graphical representation of the social view");
    if (needSocialDiagramInAppendixA()) {
        sectionIntro.append(" (a larger picture is shown in appendix A)");
    }
    sectionIntro.append(".");
    section.add(createParagraph(sectionIntro.toString()));

    section.add(decorateImage(i, ftc.getFigure(FigureConstant.SOCIAL_DIAGRAM) + " - Social View for the "
            + getProjectName() + " project"));
    section.setComplete(true);
}

From source file:eu.aniketos.wp1.ststool.report.pdfgenerator.ReportContentFactory.java

License:Open Source License

private void buildSectionInformationViewDiagram(Section section, Document document) {

    Image i = rsp.generateScrenshot(ViewsManager.RESOURCE_VIEW);
    float reductionScale = fitImageInArea(i,
            document.getPageSize().getWidth() - document.rightMargin() - document.leftMargin(), 310, false);
    if (reductionScale <= getMaximumReductionScale()) {
        setAppendixAInformationDiagram(true);
    }//  w  w  w. ja  va  2 s  .co  m

    StringBuilder sectionIntro = new StringBuilder();
    sectionIntro.append(ftc.getFigure(FigureConstant.INFORMATION_DIAGRAM)
            + " presents the graphical representation of the information view");
    if (needInformationDiagramInAppendixA()) {
        sectionIntro.append(" (a larger picture is shown in appendix A)");
    }
    sectionIntro.append(".");
    section.add(createParagraph(sectionIntro.toString()));

    section.add(decorateImage(i, ftc.getFigure(FigureConstant.INFORMATION_DIAGRAM)
            + " - Information View for the " + getProjectName() + " project"));
    section.setComplete(true);
}