Example usage for com.lowagie.text Document add

List of usage examples for com.lowagie.text Document add

Introduction

In this page you can find the example usage for com.lowagie.text Document add.

Prototype


public boolean add(Element element) throws DocumentException 

Source Link

Document

Adds an Element to the Document.

Usage

From source file:Controleur.CtrlImprimerOrdonnance.java

public void RemplirOrdonnance() {
    ResultSet res;/*from  ww w.j a va2  s. c om*/
    String nomEtablissement = "";
    String adresseEtablissement = "";
    int telEtablissement = 0;
    String nomPatient = "";
    String prenomPatient = "";
    String dateNaissPatient = null;
    String traitement = "";
    Etablissement etab = new Etablissement();
    try {
        res = etab.getEtablissement();
        nomEtablissement = res.getString("nomEtab");
        adresseEtablissement = res.getString("adresseEtab");
        telEtablissement = res.getInt("telEtab");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "erreur \n" + e.getMessage());
    }
    Medecin med1 = new Medecin();
    Medecin med2 = med1.getMedecinById(Fen.getIdm());
    String nomMedecin = med2.getNomMedecin();
    String prenomMedecin = med2.getPrenomMedecin();
    String specialiteMedecin = med2.getSpecialite();
    Patient patient = new Patient();
    res = patient.getPatient(Fen.getIdp());
    try {
        res.next();
        nomPatient = res.getString("nomPatient");
        prenomPatient = res.getString("prenomPatient");
        dateNaissPatient = res.getString("dateNaissance");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "erreur \n" + e.getMessage());
    }

    traitement = Fen.getTxtTraitement().getText();

    Document document = new Document(PageSize.A4);
    try {
        PdfWriter.getInstance(document, new FileOutputStream("./ordonnance.pdf"));
        document.open();
        Date d = new Date();
        Paragraph paragraph = new Paragraph(d.toLocaleString(),
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setAlignment(Element.ALIGN_RIGHT);
        paragraph.setIndentationRight(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Dr " + nomMedecin + " " + prenomMedecin,
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("SPECIALISTE EN " + specialiteMedecin);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(nomEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(adresseEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Tl : " + telEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("                      ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("nom & prenom :" + nomPatient + " " + prenomPatient,
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Ne(e) le :" + dateNaissPatient);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("                       ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);

        Chunk chunk = new Chunk("Ordonnance", FontFactory.getFont(FontFactory.COURIER, 30, Font.BOLD));
        chunk.setUnderline(Color.BLACK, 3.0f, 0.0f, 0.0f, -0.2f, PdfContentByte.LINE_CAP_BUTT);
        paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.add(chunk);
        document.add(paragraph);

        paragraph = new Paragraph("                       ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(traitement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);

        Runtime r = Runtime.getRuntime();
        r.exec("cmd /C ./ordonnance.pdf");
    } catch (DocumentException de) {
        de.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    document.close();
}

From source file:corner.orm.tapestry.pdf.components.PdfImage.java

License:Apache License

/**
 * @see corner.orm.tapestry.pdf.components.AbstractPdfComponent#renderPdf(corner.orm.tapestry.pdf.PdfWriterDelegate, com.lowagie.text.Document)
 *//*from   w w  w . j a  v a 2  s  . c o  m*/
@Override
public void renderPdf(PdfWriterDelegate writer, Document doc) {
    Defense.notNull(getRectangle(), "TextField?");
    String[] p = getRectangle().split(",");
    try {
        Image image = Image.getInstance(getValue());
        image.setAbsolutePosition(Float.valueOf(p[0]), Float.valueOf(p[1]));// ?
        if (getAutoSize()) {
            if (Constants.PDFIMAGE_COMPONENT_SCALE_TYPE_BORDER.equals(getScaleType())) {
                image.scaleAbsolute((Float.valueOf(p[2]) - Float.valueOf(p[0])),
                        (Float.valueOf(p[3]) - Float.valueOf(p[1])));// ?
            } else {
                float picHeight = image.plainHeight();// 
                float picWeight = image.plainWidth();// 
                float borderHeight = Float.valueOf(p[3]) - Float.valueOf(p[1]);// 
                float borderWeight = Float.valueOf(p[2]) - Float.valueOf(p[0]);// 

                float heightPer = borderHeight / picHeight * 100;
                float widthPer = borderWeight / picWeight * 100;

                // ????
                if (heightPer > widthPer) {
                    image.scalePercent(widthPer);
                } else {
                    image.scalePercent(heightPer);
                }
            }
        }
        doc.add(image);
    } catch (BadElementException e) {
        throw new CornerSystemException(e);
    } catch (MalformedURLException e) {
        throw new CornerSystemException(e);
    } catch (IOException e) {
        throw new CornerSystemException(e);
    } catch (DocumentException e) {
        throw new CornerSystemException(e);
    }
}

From source file:Cotizacion.ExportarPDF.java

private static void agregarContenido(Document document) throws DocumentException, Exception {

    Paragraph parrafoNormal1 = new Paragraph();
    Paragraph parrafoNormal2 = new Paragraph();
    Paragraph parrafoNormal3 = new Paragraph();
    Paragraph parrafoNormal4 = new Paragraph();
    Paragraph parrafoNormal5 = new Paragraph();
    Paragraph parrafoNormal6 = new Paragraph();
    Paragraph parrafoNormal7 = new Paragraph();
    Paragraph parrafoNormal8 = new Paragraph();
    Paragraph parrafoNormal9 = new Paragraph();
    Paragraph parrafoNormal10 = new Paragraph();

    acomodarImagenCabecera(parrafoNormal1);
    acomodarImagenLogo(parrafoNormal1);//from   w w w .j a v  a2  s  .c  om
    acomodarDatosDerecha(parrafoNormal1);
    acomodarDatosDerecha2(parrafoNormal2);
    acomodarDatosNormal(parrafoNormal3);
    acomodarDatosTablaProductos(parrafoNormal4);
    acomodarDatosEspecificaciones(parrafoNormal5);
    acomodarDatosPreciosTotales(parrafoNormal6);
    acomodarImagenFirma(parrafoNormal7);
    acomodarATTE(parrafoNormal8);
    acomodarDatosNota(parrafoNormal9);
    acomodarImagenPie(parrafoNormal10);

    document.add(parrafoNormal1);
    document.add(parrafoNormal2);
    document.add(parrafoNormal3);
    document.add(parrafoNormal4);
    document.add(parrafoNormal5);
    document.add(parrafoNormal6);
    document.add(parrafoNormal7);
    document.add(parrafoNormal8);
    document.add(parrafoNormal9);
    document.add(parrafoNormal10);
}

From source file:cz.incad.kramerius.pdf.impl.AbstractPDFRenderSupport.java

License:Open Source License

public static ScaledImageOptions insertJavaImage(Document document, float percentage, BufferedImage javaImg)
        throws IOException, BadElementException, MalformedURLException, DocumentException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    writeImageToStream(javaImg, "jpeg", bos);

    com.lowagie.text.Image img = com.lowagie.text.Image.getInstance(bos.toByteArray());

    Float ratio = ratio(document, percentage, javaImg);

    int fitToPageWidth = (int) (javaImg.getWidth(null) * ratio);
    int fitToPageHeight = (int) (javaImg.getHeight(null) * ratio);

    int offsetX = ((int) document.getPageSize().getWidth() - fitToPageWidth) / 2;
    int offsetY = ((int) document.getPageSize().getHeight() - fitToPageHeight) / 2;

    img.scaleAbsoluteHeight(ratio * img.getHeight());

    img.scaleAbsoluteWidth(ratio * img.getWidth());
    img.setAbsolutePosition((offsetX),//www  .j a  va 2 s  .c om
            document.getPageSize().getHeight() - offsetY - (ratio * img.getHeight()));

    document.add(img);

    ScaledImageOptions options = new ScaledImageOptions();
    options.setXdpi(img.getDpiX());
    options.setYdpi(img.getDpiY());

    options.setXoffset(offsetX);
    options.setYoffset(offsetY);

    options.setWidth(fitToPageWidth);
    options.setHeight(fitToPageHeight);
    options.setScaleFactor(ratio);

    return options;
}

From source file:cz.incad.kramerius.rest.api.k5.client.pdf.PDFResource.java

License:Open Source License

private static StreamingOutput streamingOutput(final File file, final String format) {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                Rectangle formatRect = formatRect(format);
                Document document = new Document(formatRect);
                PdfWriter.getInstance(document, output);
                document.open();/*from  w  w  w .ja v a2  s .  c om*/

                Image image = Image.getInstance(file.toURI().toURL());

                image.scaleToFit(
                        document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(),
                        document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin());
                document.add(image);

                document.close();

            } catch (Exception e) {
                throw new WebApplicationException(e);
            } finally {
                if (file != null)
                    file.delete();
            }
        }
    };
}

From source file:daoimpl.CustomizedDocumentsView.java

public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
    Document pdf = (Document) document;
    pdf.open();/*from w  ww.  ja va  2  s .co  m*/
    pdf.setPageSize(PageSize.A4);

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "img"
            + File.separator + "pdf.png";

    pdf.add(Image.getInstance(logo));
}

From source file:de.appplant.cordova.plugin.printer.Printer.java

License:Apache License

/**
 * Slices the screenshot into pages, merges those into a single pdf
 * and saves it in the public accessible /sdcard dir.
 */// ww  w.j av  a 2  s. c  o m
private File saveWebViewAsPdf(Bitmap screenshot) {
    try {

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/");
        dir.mkdirs();
        File file;
        FileOutputStream stream;

        double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page
        double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page
        double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3)

        Bitmap currPage;
        int totalSize = screenshot.getHeight();
        int currPos = 0;
        int currPageCount = 0;
        int sliceWidth = screenshot.getWidth();
        int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation);
        while (totalSize > currPos && currPageCount < 100) // max 100 pages
        {
            currPageCount++;

            Log.v(LOG_TAG, "Creating page nr. " + currPageCount);

            // slice bitmap
            currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth,
                    (int) Math.min(sliceHeight, totalSize - currPos));

            // save page as png
            stream = new FileOutputStream(new File(dir, "print-page-" + currPageCount + ".png"));
            currPage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.close();

            // move current position indicator
            currPos += sliceHeight;
        }

        // create pdf
        Log.v(LOG_TAG, "Creating pdf");
        Document document = new Document();
        File filePdf = new File(dir, this.printTitle + ".pdf"); // change the output name of the pdf here
        PdfWriter.getInstance(document, new FileOutputStream(filePdf));
        document.open();
        for (int i = 1; i <= currPageCount; ++i) {
            Log.v(LOG_TAG, "Adding page nr. " + i + " to the pdf file.");
            file = new File(dir, "print-page-" + i + ".png");
            Image image = Image.getInstance(file.getAbsolutePath());
            image.scaleToFit((float) pageWidth, 9999);
            image.setAlignment(Element.ALIGN_CENTER);
            document.add(image);
            document.newPage();
        }
        document.close();

        // delete tmp image files
        for (int i = 1; i <= currPageCount; ++i) {
            file = new File(dir, "print-page-" + i + ".png");
            file.delete();
        }

        return filePdf;

    } catch (IOException e) {
        Log.e(LOG_TAG, "ERROR: " + e.getMessage());
        e.printStackTrace();
        // return error answer to cordova
        PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        result.setKeepCallback(false);
        ctx.sendPluginResult(result);
    } catch (DocumentException e) {
        Log.e(LOG_TAG, "ERROR: " + e.getMessage());
        e.printStackTrace();
        // return error answer to cordova
        PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        result.setKeepCallback(false);
        ctx.sendPluginResult(result);
    }

    Log.e(LOG_TAG, "Uncaught ERROR!");

    return null;
}

From source file:de.cuseb.bilderbuch.pdf.PdfController.java

License:Open Source License

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) {

    try {//from ww  w  .  j a  v  a  2  s  .co  m
        PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest");
        httpServletResponse.setContentType("application/pdf");

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream());
        writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB);

        //document.addAuthor(pdfRequest.getAuthor());
        //document.addTitle(pdfRequest.getTitle());
        document.setPageSize(
                new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148)));
        document.open();

        FontFactory.defaultEmbedding = true;
        FontFactory.register("IndieRock.ttf", "IndieRock");
        Font font = FontFactory.getFont("IndieRock");
        BaseFont baseFont = font.getBaseFont();
        PdfContentByte cb = writer.getDirectContent();

        Iterator<PdfPage> pages = pdfRequest.getPages().iterator();
        while (pages.hasNext()) {

            PdfPage page = pages.next();
            if (page.getImage() != null) {

                Image image = Image.getInstance(new URL(page.getImage().getUrl()));
                image.setDpi(300, 300);
                image.setAbsolutePosition(0f, 0f);
                image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                document.add(image);

                cb.saveState();
                cb.beginText();
                cb.setColorFill(Color.WHITE);
                cb.moveText(10f, 10f);
                cb.setFontAndSize(baseFont, 18);
                cb.showText(page.getSentence());
                cb.endText();
                cb.restoreState();

                if (pages.hasNext()) {
                    document.newPage();
                }
            }
        }
        document.close();

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

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Set the logo of Humboldt on the left corner and the current date on the
 * right corner/*from ww w  . j  ava2s  .  c  om*/
 * 
 * @param document
 *            reference of the pdfDocument object
 */
protected void addHeading(Document document) {
    Paragraph paragraph = new Paragraph();
    PdfPTable table = createMyStandardTable(2);

    table.setTotalWidth(TABLEWIDTH);
    PdfPCell cell;

    Image img = new ResourceLoader("pdf/humboldt_logo.png").getImage();
    img.setAlignment(Element.ALIGN_BOTTOM);
    img.scaleToFit(205f, 65f);
    cell = new PdfPCell(img);

    cell.setBorder(0);
    table.addCell(cell);

    String date = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).format(Calendar.getInstance().getTime());

    cell = new PdfPCell(new Phrase(date));
    cell.setBorder(0);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(""));
    cell.setBorder(Rectangle.BOTTOM);
    table.addCell(cell);
    cell = new PdfPCell(new Phrase(""));
    cell.setBorder(Rectangle.BOTTOM);
    table.addCell(cell);

    paragraph.add(table);
    addEmptyLine(paragraph, 1);

    try {
        document.add(paragraph);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Adds a signature field with a date field to the document. Should be the
 * last part that is added to the document.
 * //from   w  w  w.  j a va 2  s  . com
 * @param document
 *            represents the PDF before it is saved
 * @param role
 *            word for the kind of person that shall sign the paper
 */
protected void addSignatureField(Document document, String role) {
    Paragraph paragraph = new Paragraph();

    //this table contains the signatureTable and the dataTable.
    // this purpose makes it easier to format
    PdfPTable table = createMyStandardTable(2);

    //the first column is double times greater than the second column
    try {
        table.setWidths(new float[] { 10f, 20f });
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    //create and fill date table
    PdfPTable dateTable = new PdfPTable(1);

    PdfPCell cell = new PdfPCell(new Phrase(""));
    //just the bottom border will be displayed (line for date)
    cell.setBorderWidthTop(0);
    cell.setBorderWidthLeft(0);
    cell.setBorderWidthRight(0);

    dateTable.addCell(cell);

    cell = new PdfPCell(new Phrase("Datum"));
    cell.setBorder(0);

    dateTable.addCell(cell);

    //put date table into the 'parent' table
    cell = new PdfPCell(dateTable);
    cell.setBorder(0);
    table.addCell(cell);

    //create and fill signature table
    PdfPTable signatureTable = new PdfPTable(1);
    cell = new PdfPCell(new Phrase(""));
    //just the bottom border will be displayed (line for signature)
    cell.setBorderWidthTop(0);
    cell.setBorderWidthLeft(0);
    cell.setBorderWidthRight(0);

    signatureTable.addCell(cell);

    cell = new PdfPCell(new Phrase("Unterschrift " + role));
    cell.setBorder(0);

    signatureTable.addCell(cell);

    //put signature table into the 'parent' table
    cell = new PdfPCell(signatureTable);
    cell.setBorder(0);
    table.addCell(cell);

    paragraph.add(table);
    try {
        document.add(paragraph);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}