Example usage for com.lowagie.text Document setMargins

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

Introduction

In this page you can find the example usage for com.lowagie.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:com.qcadoo.report.api.pdf.PdfDocumentWithWriterService.java

License:Open Source License

private void generate(final Entity entity, final Locale locale, final String filename, final Rectangle pageSize)
        throws IOException, DocumentException {
    Document document = new Document(pageSize);
    try {//from  w  w  w .j av a2s. c  om
        FileOutputStream fileOutputStream = new FileOutputStream(
                fileService.createReportFile(filename + "." + ReportService.ReportType.PDF.getExtension()));
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        buildPdfMetadata(document, locale);
        writer.createXmpMetadata();
        document.open();
        buildPdfContent(writer, document, entity, locale);
        document.close();
    } catch (DocumentException e) {
        LOG.error("Problem with generating document - " + e.getMessage());
        document.close();
        throw e;
    }
}

From source file:com.qcadoo.report.api.pdf.ReportPdfView.java

License:Open Source License

@Override
protected Document newDocument() {
    Document doc = super.newDocument();

    doc.setMargins(40, 40, 60, 60);

    return doc;/*w ww.  java 2s .c  o m*/
}

From source file:com.songbook.pc.exporter.PdfExporter.java

License:Open Source License

private PageStats generatePDF(List<SongNode> songList, File outputFile) throws IOException, DocumentException {
    logger.info("Starting export to PDF file {}.", outputFile.getAbsolutePath());

    // Initialize Writer
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
    PageStats pageStats = new PageStats();
    writer.setPageEvent(pageStats);/*from   w  w w.  j  a  v  a2 s . c o m*/

    // Initialize document
    document.setPageSize(PageSize.A4);
    document.setMargins(35 * POINTS_PER_MM, 10 * POINTS_PER_MM, 7 * POINTS_PER_MM, 7 * POINTS_PER_MM);
    document.setMarginMirroring(true);

    document.open();

    // Add QR codes
    Element qrCodeSection = buildQrCodeSection();
    document.add(qrCodeSection);

    // Line separator
    document.add(verseSpacing);
    document.add(new LineSeparator());
    document.add(verseSpacing);

    // Build TOC
    Chunk tocTitle = new Chunk("SONG BOOK - TABLE OF CONTENTS", songTitleFont);
    tocTitle.setLocalDestination("TOC");
    document.add(new Paragraph(tocTitle));
    for (int i = 0; i < songList.size(); i++) {
        SongNode songNode = songList.get(i);
        int chapterNumber = i + 1;
        Chunk tocEntry = new Chunk(chapterNumber + ". " + songNode.getTitle(), textFont);
        tocEntry.setLocalGoto("SONG::" + chapterNumber);
        document.add(new Paragraph(tocEntry));
    }
    document.newPage();
    pageStats.setSectionLength("TOC", pageStats.getCurrentPage() - 1);

    // Build document
    for (int i = 0; i < songList.size(); i++) {
        // Get song node
        SongNode songNode = songList.get(i);

        // Mark song start
        int songStartPage = pageStats.getCurrentPage();

        // Write song
        document.add(buildChapter(songNode, i + 1));
        document.newPage();

        // Record song length
        pageStats.setSectionLength(songNode.getTitle(), pageStats.getCurrentPage() - songStartPage);
    }

    // Close document
    document.close();

    logger.info("COMPLETED export to PDF file {}.", outputFile.getAbsolutePath());

    return pageStats;
}

From source file:com.tsp.gespro.bo.DegustacionBO.java

/**
 * Representacin impresa PDF/* w w w . java2 s. c o  m*/
 */
public ByteArrayOutputStream toPdf(UsuarioBO user) throws Exception {

    SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat hora = new SimpleDateFormat("HH:mm:ss");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    PdfITextUtil obj = new PdfITextUtil();

    //Tamao de documento (Tamao Carta)
    com.lowagie.text.Document doc = new com.lowagie.text.Document(PageSize.LETTER);

    //Definicin de Fuentes a usar
    Font letraOcho = new Font(Font.HELVETICA, 8, Font.NORMAL);
    Font letraOchoBold = new Font(Font.HELVETICA, 8, Font.BOLD);
    Font letraNueve = new Font(Font.HELVETICA, 9, Font.NORMAL);
    Font letraNueveBold = new Font(Font.HELVETICA, 9, Font.BOLD);
    Font letraNueveBoldRojo = new Font(Font.TIMES_ROMAN, 9, Font.BOLD, Color.red);
    Font letraNueveBoldAzul = new Font(Font.TIMES_ROMAN, 9, Font.BOLD, Color.blue);
    Font letraOchoVerde = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL, Color.green);
    Font letra14Bold = new Font(Font.HELVETICA, 14, Font.BOLD);

    String msgError = "";

    File fileImageLogo = null;
    try {
        if (user != null)
            fileImageLogo = new ImagenPersonalBO(this.conn)
                    .getFileImagenPersonalByEmpresa(user.getUser().getIdEmpresa());
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        //Preparamos writer de PDF
        PdfWriter writer = PdfWriter.getInstance(doc, baos);
        EventPDF eventPDF = new EventPDF(doc, user, ReportBO.DEGUSTACION_REPRESENTACION_IMPRESA, fileImageLogo);
        writer.setPageEvent(eventPDF);

        //Ajustamos margenes de pgina
        //doc.setMargins(50, 50, 120, 50);
        //doc.setMargins(20, 20, 80, 20);
        doc.setMargins(10, 10, 150, 40);

        //Iniciamos documento
        doc.open();

        //Creamos tabla principal
        PdfPTable mainTable = new PdfPTable(1);
        mainTable.setTotalWidth(550);
        mainTable.setLockedWidth(true);

        //CONTENIDO -------------

        //SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        //Cabecera (Datos Generales)---------------------
        PdfPTable tAux = new PdfPTable(1);

        Cliente clienteDto = null;
        DatosUsuario datosUsuarioVendedor = null;

        try {
            if (this.degustacion.getIdCliente() > 0)
                clienteDto = new ClienteBO(this.degustacion.getIdCliente(), this.conn).getCliente();
            if (this.degustacion.getIdUsuario() > 0)
                datosUsuarioVendedor = new UsuarioBO(this.degustacion.getIdUsuario()).getDatosUsuario();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //Datos informativos generales
        PdfPTable tInfoGeneral = new PdfPTable(1);
        tInfoGeneral.setTotalWidth(160);
        tInfoGeneral.setLockedWidth(true);

        obj.agregaCelda(tInfoGeneral, letraNueveBold, Color.lightGray, "ID Degustacin",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueveBoldRojo, "" + this.degustacion.getIdDegustacion(),
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);

        obj.agregaCelda(tInfoGeneral, letraNueveBold, Color.lightGray, "Fecha Degustacin",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueve,
                DateManage.dateToStringEspanol(this.degustacion.getFechaApertura()),
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueveBold, Color.lightGray, "Promotor",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);
        obj.agregaCelda(tInfoGeneral, letraNueve,
                datosUsuarioVendedor != null
                        ? (datosUsuarioVendedor.getNombre() + " " + datosUsuarioVendedor.getApellidoPat())
                        : "Sin vendedor asignado",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 1);

        //Pintamos datos informativos Generales en la esquina superior derecha
        PdfContentByte cb = writer.getDirectContent();
        tInfoGeneral.writeSelectedRows(0, -1, doc.right() - 180, doc.top() + 100, cb);

        //Datos de Cliente/Prospecto
        PdfPTable tCliente = new PdfPTable(2);
        tCliente.setTotalWidth(550);
        tCliente.setLockedWidth(true);

        obj.agregaCelda(tCliente, letraNueveBold, Color.lightGray, "Cliente",
                new boolean[] { false, false, false, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0,
                new int[0], 2);

        tAux = new PdfPTable(1);
        tAux.setTotalWidth(275);
        tAux.setLockedWidth(true);

        try {
            obj.agregaCelda(tAux, letraOcho,
                    "Nombre Comercial: " + (clienteDto != null ? clienteDto.getNombreComercial() : ""),
                    new boolean[] { false, true, false, false }, Element.ALIGN_LEFT, Element.ALIGN_TOP, 0,
                    new int[0], 1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        obj.agregaTabla(tCliente, tAux, new boolean[] { false, false, false, false }, Element.ALIGN_LEFT,
                Element.ALIGN_TOP, 0, new int[0], 1);

        obj.agregaCelda(tCliente, letraOcho,
                "" + "DOMICILIO: \n" + (clienteDto != null ? "Calle: " + clienteDto.getCalle() : "") + " "
                        + (clienteDto != null ? clienteDto.getNumero() : "") + " "
                        + (clienteDto != null ? clienteDto.getNumeroInterior() : "")
                        + (clienteDto != null ? " Col: " + clienteDto.getColonia() : "")
                        + (clienteDto != null ? " \nDeleg./Municipio: " + clienteDto.getMunicipio() : "")
                        + (clienteDto != null ? " Estado: " + clienteDto.getEstado() : "")
                        + (clienteDto != null ? " \nC.P. " + clienteDto.getCodigoPostal() : ""),
                new boolean[] { false, true, false, true }, Element.ALIGN_LEFT, Element.ALIGN_TOP, 0,
                new int[0], 1);

        obj.agregaTabla(mainTable, tCliente, new boolean[] { true, true, true, true }, Element.ALIGN_CENTER,
                Element.ALIGN_TOP, 0, new int[0], 1);

        //FIN Cabecera (Datos Generales)-----------------

        //DOBLE SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        int colsDetalles = 6;
        PdfPTable tDetalles = new PdfPTable(colsDetalles);//6);
        tDetalles.setTotalWidth(550);
        tDetalles.setWidths(new int[] { 200, 70, 70, 70, 70, 70 });
        tDetalles.setLockedWidth(true);

        /*CABECERA*/
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Producto Degustado",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Hr Inicio",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Hr Termino",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Inventario Inicial",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Inventario Final",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);
        obj.agregaCelda(tDetalles, letraNueveBold, Color.lightGray, "Piezas Degustadas",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 1);

        /*FIN DE CABECERA*/
        Degustacion[] degustacionDtos = new Degustacion[0];
        try {
            degustacionDtos = this.findDegustaciones(this.degustacion.getIdDegustacion(),
                    this.degustacion.getIdEmpresa(), -1, -1, "");
        } catch (Exception e) {
        }

        //Listado de Productos
        for (Degustacion item : degustacionDtos) {

            if (item != null) {

                Concepto conceptoDto = null;

                try {
                    ConceptoBO conceptoBO = new ConceptoBO(item.getIdConcepto(), this.conn);
                    conceptoDto = conceptoBO.getConcepto();
                } catch (Exception e) {
                }

                //Producto
                obj.agregaCelda(tDetalles, letraOcho, null, conceptoDto.getNombreDesencriptado(),
                        new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED, Element.ALIGN_TOP,
                        15, new int[] { 5, 5, 5, 5 }, 1);

                //Inicio
                obj.agregaCelda(tDetalles, letraOcho, null, hora.format(item.getFechaApertura()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED, Element.ALIGN_TOP,
                        15, new int[] { 5, 5, 5, 5 }, 1);

                //Termino
                obj.agregaCelda(tDetalles, letraOcho, null, hora.format(item.getFechaCierre()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

                //Inv inicial 
                obj.agregaCelda(tDetalles, letraOcho, null, "" + (item.getCantidad()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

                //inv final 
                obj.agregaCelda(tDetalles, letraOcho, null, "" + (item.getCantidadCierre()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

                //Piezas 
                obj.agregaCelda(tDetalles, letraOcho, null,
                        "" + (item.getCantidad() - item.getCantidadCierre()),
                        new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP, 15,
                        new int[] { 5, 5, 5, 5 }, 1);

            }
        }

        obj.agregaTabla(mainTable, tDetalles, new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_TOP, 0, new int[0], 1);

        //DOBLE SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        /*prods Vendidos durante degustacion*/

        PdfPTable tVenta = new PdfPTable(4);
        tVenta.setTotalWidth(550);
        tVenta.setWidths(new int[] { 70, 140, 170, 120 });
        tVenta.setLockedWidth(true);

        obj.agregaCelda(tVenta, letraNueveBold, Color.lightGray, "Producto Vendido durante Degutacin",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 4);

        Productosvendidos[] pedidoProductoDto = new Productosvendidos[0];

        String filtroBusqueda = " ID_PEDIDO IN ( SELECT ID_PEDIDO FROM sgfens_pedido WHERE ID_EMPRESA = '"
                + this.degustacion.getIdEmpresa() + "' AND ID_TIPO_PEDIDO = 2 AND ID_USUARIO_VENDEDOR = "
                + this.degustacion.getIdUsuario() + " AND " + " ID_ESTATUS_PEDIDO<>2 AND FECHA_PEDIDO BETWEEN '"
                + this.degustacion.getFechaApertura() + "'  AND '" + this.degustacion.getFechaCierre() + "') ";

        try {
            pedidoProductoDto = new ProductosvendidosDaoImpl().findByDynamicWhere(filtroBusqueda, null);
        } catch (Exception e) {
        }

        if (pedidoProductoDto.length > 0) {

            obj.agregaCelda(tVenta, letraOchoBold, null, "Cdigo", new boolean[] { true, true, true, true },
                    Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15, new int[] { 5, 5, 5, 5 }, 1);
            obj.agregaCelda(tVenta, letraOchoBold, null, "Nombre", new boolean[] { true, true, true, true },
                    Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15, new int[] { 5, 5, 5, 5 }, 1);
            obj.agregaCelda(tVenta, letraOchoBold, null, "Descripcin",
                    new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                    new int[] { 5, 5, 5, 5 }, 1);
            obj.agregaCelda(tVenta, letraOchoBold, null, "Unidades Vendidas",
                    new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                    new int[] { 5, 5, 5, 5 }, 1);

            for (Productosvendidos pedidoProd : pedidoProductoDto) {

                if (pedidoProd != null) {

                    Concepto conceptoDto = null;
                    try {
                        ConceptoBO conceptoBO = new ConceptoBO(pedidoProd.getIdConcepto(), this.conn);
                        conceptoDto = conceptoBO.getConcepto();
                    } catch (Exception e) {
                    }

                    //Cdigo
                    obj.agregaCelda(tVenta, letraOcho, null, conceptoDto.getIdentificacion(),
                            new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED,
                            Element.ALIGN_TOP, 15, new int[] { 5, 5, 5, 5 }, 1);

                    //Nombre
                    obj.agregaCelda(tVenta, letraOcho, null, conceptoDto.getNombreDesencriptado(),
                            new boolean[] { true, true, true, true }, Element.ALIGN_JUSTIFIED,
                            Element.ALIGN_TOP, 15, new int[] { 5, 5, 5, 5 }, 1);

                    //Descripcin
                    obj.agregaCelda(tVenta, letraOcho, null, conceptoDto.getDescripcion(),
                            new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP,
                            15, new int[] { 5, 5, 5, 5 }, 1);

                    //Unidades Vendidas 
                    obj.agregaCelda(tVenta, letraOcho, null, "" + (pedidoProd.getCantidad()),
                            new boolean[] { true, true, true, true }, Element.ALIGN_RIGHT, Element.ALIGN_TOP,
                            15, new int[] { 5, 5, 5, 5 }, 1);

                }

            }
        } else {

            obj.agregaCelda(tVenta, letraOcho, null, "No se registrarn datos.",
                    new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                    new int[] { 5, 5, 5, 5 }, 4);

        }

        obj.agregaTabla(mainTable, tVenta, new boolean[] { true, true, true, true }, Element.ALIGN_CENTER,
                Element.ALIGN_TOP, 0, new int[0], 1);

        //DOBLE SALTO DE L?NEA
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);
        obj.agregaCelda(mainTable, letraOcho, null, " ", new boolean[] { false, false, false, false },
                Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 0, new int[0], 1);

        /*Comentarios Adicionales*/
        PdfPTable tComenst = new PdfPTable(1);
        tComenst.setTotalWidth(550);
        tComenst.setWidths(new int[] { 550 });
        tComenst.setLockedWidth(true);

        obj.agregaCelda(tComenst, letraNueveBold, Color.lightGray, "Comentarios",
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 2);

        obj.agregaCelda(tComenst, letraOcho, null, this.degustacion.getComentariosCierre(),
                new boolean[] { true, true, true, true }, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, 15,
                new int[] { 5, 5, 5, 5 }, 2);

        obj.agregaTabla(mainTable, tComenst, new boolean[] { true, true, true, true }, Element.ALIGN_CENTER,
                Element.ALIGN_TOP, 0, new int[0], 1);

        //FIN DE CONTENIDO --------

        //Aadimos tabla principal construida al documento
        doc.add(mainTable);
        mainTable.flushContent();

    } catch (Exception ex) {
        msgError = "No se ha podido generar la representacin impresa de la Degustacion en formato PDF:<br/>"
                + ex.toString();
    } finally {
        if (doc.isOpen())
            doc.close();
    }

    if (!msgError.equals("")) {
        throw new Exception(msgError);
    }

    return baos;

}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

private Document prepareDocument(String filename, final String title, final String author, final String creator,
        final Rectangle pageSize) {

    System.out.println("DEBUG(PDFExporter): Creating document: " + filename);

    Document d = new Document();

    d.setPageSize(pageSize);/*from ww  w  . j a va2  s  . c  om*/
    // TODO alter page orientation?  maybe useful for seed order worksheet

    d.addTitle(title);
    d.addAuthor(author);
    //        d.addSubject( );
    //        d.addKeywords( );
    d.addCreator(creator);

    // left, right, top, bottom - scale in points (~72 points/inch)
    d.setMargins(35, 35, 35, 44);

    try {
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename));
        // add header and footer
        writer.setPageEvent(new PdfPageEventHelper() {
            public void onEndPage(PdfWriter writer, Document document) {
                try {
                    Rectangle page = document.getPageSize();

                    PdfPTable head = new PdfPTable(3);
                    head.getDefaultCell().setBorderWidth(0);
                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    head.addCell(new Phrase(author, fontHeadFootItal));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    head.addCell(new Phrase(title, fontHeadFootReg));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    head.addCell("");

                    head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    head.writeSelectedRows(0, -1, document.leftMargin(),
                            page.getHeight() - document.topMargin() + head.getTotalHeight(),
                            writer.getDirectContent());

                    PdfPTable foot = new PdfPTable(3);

                    foot.getDefaultCell().setBorderWidth(0);
                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    foot.addCell(new Phrase(creator, fontHeadFootItal));

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    foot.addCell("");

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg));

                    foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                            writer.getDirectContent());
                } catch (Exception e) {
                    throw new ExceptionConverter(e);
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    return d;
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/******************************************************************************************************
 * Adds the all pages./*from   w w  w  .  j  a  va 2 s  . c o m*/
 * 
 * @param pagesizemode {@link PdfPageSize}
 * @param writer {@link PdfWriter}
 * @param pdfdoc {@link Document}
 * @return {@link PdfPageLabels}
 * 
 * 
 * @throws ImageInterpreterException the image interpreter exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MalformedURLException the malformed url exception
 * @throws PDFManagerException the PDF manager exception
 * @throws ImageManagerException
 *******************************************************************************************************/
private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc,
        Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException,
        PDFManagerException, ImageManagerException {

    PdfPageLabels pagelabels = new PdfPageLabels();
    int pageadded = 0;

    // sort the HashMap by the KeySet (pagenumber)
    Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs);

    float scalefactor = 1; // scaling factor of the image
    int page_w = PaperSize.A4.width;
    int page_h = PaperSize.A4.height;
    LOGGER.debug("iterate over " + imageURLs.size() + " pages.");
    for (Integer imageKey : sortedMap.keySet()) {

        Watermark watermark = myWatermark;
        Image pdfImage = null; // PDF-Image
        LOGGER.debug("Writing page " + imageKey);

        boolean errorPage = false; // true if the image does not exists
        URL errorUrl = null; // url of the image that does not exists

        // ------------------------------------------------------------------------------------------------
        // Title page available. Render it in pdftitlepage
        // ------------------------------------------------------------------------------------------------
        if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) {
            // title page
            PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey);
            // create new PDF page
            try {
                pdfdoc.setPageSize(PageSize.A4);
                pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(),
                        pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin());
                pageadded++;
                pdfdoc.newPage(); // create new page
                // set page name
                pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-");
            } catch (Exception e1) {
                throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1);
            }
            // render title page
            pdftitlepage.render(pdfdoc);
        }

        // ------------------------------------------------------------------------------------------------
        // Process image with imageKey
        // ------------------------------------------------------------------------------------------------
        UrlImage pdfpage = imageURLs.get(imageKey);
        if (pdfpage.getURL() != null) {
            boolean added = false;
            boolean scaled = false;
            URL url = pdfpage.getURL();
            // pdf hack
            if (ContentServerConfiguration.getInstance().getUsePdf()) {
                LOGGER.debug("trying to find original pdf");
                PdfContentByte pdfcb = null;
                PdfReader pdfreader = null;
                PdfImportedPage importpage = null;
                try {
                    String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf()
                            .replace("file:///", "");
                    LOGGER.debug("looking in " + pdfpath + " for pdf file");
                    String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages()
                            .replace("file:///", "");
                    // String urlString = url.toString();
                    int pageNumber = pdfpage.getPageNumber();
                    // UrlImage copy = new PDFPage(pdfpage);
                    URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath)
                            .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf"));
                    LOGGER.debug("pdfurl = " + pdfurl);

                    if (new File(pdfurl.toURI()).exists()) {
                        LOGGER.debug("found pdf " + pdfurl.toURI());
                        // copy.setURL(pdfurl);
                        pdfcb = writer.getDirectContent();
                        pdfreader = new PdfReader(pdfurl);
                        importpage = writer.getImportedPage(pdfreader, pageNumber);

                        LOGGER.debug("creating orig pdf page");
                        Rectangle rect = pdfreader.getPageSize(pageNumber);
                        try {
                            pdfdoc.setPageSize(rect);
                            pdfdoc.newPage(); // create new page
                        } catch (Exception e1) {
                            throw new PDFManagerException("Exception occured while creating new page in PDF",
                                    e1);
                        }
                        pageadded++;
                        pdfcb.addTemplate(importpage, 0, 0);
                        added = true;
                        LOGGER.debug("page:" + imageKey + "  url: " + pdfurl.toString());

                    }
                } catch (URISyntaxException e) {
                    LOGGER.debug(e);
                    added = false;
                } finally {
                    if (writer != null) {
                        writer.freeReader(pdfreader);
                        writer.flush();
                    }
                    if (pdfreader != null) {
                        pdfreader.close();
                    }
                }
            }
            if (!added) {
                // image file
                LOGGER.debug("using image to create pdf page");
                // try to get ImageInterpreter from url
                ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost,
                        httpproxyport, httpproxyuser, httpproxypassword);

                try {
                    // check preferred compression type depending on color depth
                    Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM;
                    if (myInterpreter.getColordepth() == 1) {
                        // bitonal image
                        preferredEmbeddingType = embeddBitonalImage;
                    } else if ((myInterpreter.getColordepth() > 1)
                            && (myInterpreter.getSamplesperpixel() == 1)) {
                        // greyscale image
                        preferredEmbeddingType = embeddGreyscaleImage;
                    } else {
                        // color image
                        preferredEmbeddingType = embeddColorImage;
                    }

                    // -------------------------------------------------------------------------------------
                    // Try to generate image
                    // -------------------------------------------------------------------------------------
                    pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage,
                            watermark, errorUrl);

                    // -------------------------------------------------------------------------------------
                    // image couldn't be embedded yet (emergencyCase)
                    // -------------------------------------------------------------------------------------
                    if (pdfImage == null) {
                        LOGGER.warn(
                                "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage");

                        // Get Interpreter and rendered Image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        RenderedImage ri = null;
                        if (preferredEmbeddingType == embeddBitonalImage) {
                            ImageManager sourcemanager = new ImageManager(url);
                            boolean watermarkscale = ContentServerConfiguration.getInstance()
                                    .getScaleWatermark(); // should we scale
                            // the watermark ?
                            ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null,
                                    null, watermark, watermarkscale, ImageManager.BOTTOM);
                            myInterpreter = sourcemanager.getMyInterpreter();
                        } else {
                            ri = myInterpreter.getRenderedImage();
                            if (watermark != null) {
                                ri = addwatermark(ri, watermark, 2);
                                myInterpreter.setHeight(
                                        myInterpreter.getHeight() + watermark.getRenderedImage().getHeight());
                            }
                        }

                        // scale rendered image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // float scalefactorX = 1;
                        // float scalefactorY = 1;
                        // switch (pagesizemode) {
                        // case ORIGINAL:
                        // scalefactorX = 72f / myInterpreter.getXResolution();
                        // scalefactorY = 72f / myInterpreter.getYResolution();
                        // break;
                        // default:
                        // /*
                        // * check, if the image needs to be scaled, because
                        // * it's bigger than A4 calculate the new scalefactor
                        // */
                        // float page_w_pixel = (float) (page_w *
                        // myInterpreter.getXResolution() / 25.4);
                        // float page_h_pixel = (float) (page_h *
                        // myInterpreter.getYResolution() / 25.4);
                        //
                        // float res_x = myInterpreter.getXResolution();
                        // float res_y = myInterpreter.getYResolution();
                        //
                        // long w = myInterpreter.getWidth(); // get height and
                        // // width
                        // long h = myInterpreter.getHeight();
                        //
                        // if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        // LOGGER.debug("scale image to fit the page");
                        // float scalefactor_w = page_w_pixel / w;
                        // float scalefactor_h = page_h_pixel / h;
                        // if (scalefactor_h < scalefactor_w) {
                        // scalefactor = scalefactor_h;
                        // } else {
                        // scalefactor = scalefactor_w;
                        // }
                        // w = (long) (w * scalefactor);
                        // h = (long) (h * scalefactor);
                        // }
                        // scalefactorX = (72f / res_x) * scalefactor;
                        // scalefactorY = (72f / res_y) * scalefactor;
                        // break;
                        // }
                        // //scalefactorX = 0.2f;
                        // //scalefactorY = 0.2f;
                        // if (preferredEmbeddingType == embeddBitonalImage) {
                        // ImageManager sourcemanager = new ImageManager(url);
                        // ri = sourcemanager.scaleImageByPixel((int)
                        // (scalefactorX*100), (int) (scalefactorY*100),
                        // ImageManager.SCALE_BY_PERCENT, 0, null, null,
                        // watermark, true, ImageManager.BOTTOM);
                        // }else{
                        // ri = ImageManipulator.scaleInterpolationBilinear(ri,
                        // scalefactorX, scalefactorY);
                        // }
                        // myInterpreter.setHeight(ri.getHeight());
                        // myInterpreter.setWidth(ri.getWidth());
                        // scaled = true;

                        // add Watermark
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // ri = addwatermark(ri, watermark,
                        // ImageManager.BOTTOM);
                        // myInterpreter.setHeight(myInterpreter.getHeight() +
                        // watermark.getRenderedImage().getHeight());

                        // Try to write into pdfImage
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        if (myInterpreter.getColordepth() > 1) {
                            // compress image if greyscale or color
                            ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                            // JpegInterpreter jpint = new JpegInterpreter(ri);
                            // jpint.setXResolution(myInterpreter.getXResolution());
                            // jpint.setYResolution(myInterpreter.getYResolution());
                            // jpint.writeToStream(null, bytesoutputstream);
                            LOGGER.error("WritingJPEGImage");
                            writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter);
                            byte[] returnbyteArray = bytesoutputstream.toByteArray();
                            if (bytesoutputstream != null) {
                                bytesoutputstream.flush();
                                bytesoutputstream.close();
                            }
                            pdfImage = Image.getInstance(returnbyteArray);
                            returnbyteArray = null;
                        } else {
                            // its bitonal, but can't be embedded directly,
                            // need to go via RenderedImage
                            BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri);
                            pdfImage = Image.getInstance(buffImage, null, false);
                            if (myWatermark != null) {
                                // create Image for Watermark
                                JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage());
                                ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                                jpint.setXResolution(myInterpreter.getXResolution());
                                jpint.setYResolution(myInterpreter.getYResolution());
                                jpint.writeToStream(null, bytesoutputstream);
                                byte[] returnbyteArray = bytesoutputstream.toByteArray();
                                jpint.clear();
                                if (bytesoutputstream != null) {
                                    bytesoutputstream.flush();
                                    bytesoutputstream.close();
                                }
                                Image blaImage = Image.getInstance(returnbyteArray);
                                returnbyteArray = null;
                                // set Watermark as Footer at fixed position
                                // (200,200)
                                Chunk c = new Chunk(blaImage, 200, 200);
                                Phrase p = new Phrase(c);
                                HeaderFooter hf = new HeaderFooter(p, false);
                                pdfdoc.setFooter(hf);
                            }
                            // pdfdoc.setPageSize(arg0)
                            // TODO das scheint nicht zu funktionieren... sollte
                            // dieser Code entfernt werden?

                        }
                    } // end of : if (pdfImage == null) {
                } catch (BadElementException e) {
                    throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e);
                } catch (ImageManipulatorException e) {
                    LOGGER.warn(e);
                }

                // ---------------------------------------------------------------------------------------------------------
                // place the image on the page
                // ---------------------------------------------------------------------------------------------------------
                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    // calculate the image width and height in points, create
                    // the rectangle in points

                    Rectangle rect = null;
                    if (!scaled) {
                        float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72;
                        float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution())
                                * 72;
                        rect = new Rectangle(image_w_points, image_h_points);
                    } else {
                        rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight());
                    }

                    // create the pdf page according to this rectangle
                    LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x "
                            + rect.getHeight());
                    pdfdoc.setPageSize(rect);

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.newPage();
                    } catch (Exception e1) {
                        throw new PDFManagerException(
                                "DocumentException occured while creating page " + pageadded + " in PDF", e1);
                    }

                    // scale image and place it on page; scaling the image does
                    // not scale the images bytestream
                    if (!scaled) {
                        pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100),
                                (72f / myInterpreter.getYResolution() * 100));
                    }
                    pdfImage.setAbsolutePosition(0, 0); // set image to lower
                                                        // left corner

                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage); // add it to PDF
                        if (!result) {
                            throw new PDFManagerException("Image \"" + url.toString()
                                    + "\" can's be added to PDF! Error during placing image on page");
                        }
                    } catch (DocumentException e) {
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                } else {
                    /*
                     * it is not the original page size PDF will contain only A4 pages
                     */
                    LOGGER.debug("creating A4 pdf page");

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4);
                    float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4);

                    float res_x = myInterpreter.getXResolution();
                    float res_y = myInterpreter.getYResolution();

                    long w = myInterpreter.getWidth(); // get height and width
                    long h = myInterpreter.getHeight();

                    /*
                     * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated
                     */
                    if (w > h) {
                        LOGGER.debug("rotate image");
                        // must be rotated
                        pdfImage.setRotationDegrees(90);
                        // change width and height
                        long dummy = w;
                        w = h;
                        h = dummy;
                        // change the resolutions x and y
                        float dummy2 = res_x;
                        res_x = res_y;
                        res_y = dummy2;
                    }

                    /*
                     * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor
                     */
                    if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        LOGGER.debug("scale image to fit the page");
                        float scalefactor_w = page_w_pixel / w;
                        float scalefactor_h = page_h_pixel / h;
                        if (scalefactor_h < scalefactor_w) {
                            scalefactor = scalefactor_h;
                        } else {
                            scalefactor = scalefactor_w;
                        }
                        w = (long) (w * scalefactor);
                        h = (long) (h * scalefactor);
                    }
                    if (!scaled) {
                        pdfImage.scalePercent((72f / res_x * 100) * scalefactor,
                                (72f / res_y * 100) * scalefactor);
                    }

                    // center the image on the page
                    // ---------------------------------------------------------------
                    float y_offset = 0; // y - offset
                    // get image size in cm; height
                    float h_cm = (float) (h / (res_x / 2.54));
                    // float w_cm = (float) (w / (res_y / 2.54)); // and width
                    if ((h_cm + 2) < (page_h / 10)) {
                        y_offset = 2 * 72f / 2.54f;
                    }
                    float freespace_x = ((page_w_pixel - w) / res_x * 72f);
                    float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset);
                    // set position add image
                    pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y);
                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage);
                    } catch (DocumentException e) {
                        LOGGER.error(e);
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                    if (!result) {
                        // placing the image in the PDF was not successful
                        throw new PDFManagerException("Image \"" + url.toString()
                                + "\" can's be added to PDF! Error during placing image on page");
                    }

                    // draw box around the image page
                    // ------------------------------------------------------------------------------------------------
                    if (pagesizemode == PdfPageSize.A4BOX) {
                        LOGGER.debug("draw box around the image page");

                        // draw a black frame around the image
                        PdfContentByte pcb = writer.getDirectContent();

                        // calculate upper left corner of the box (measurment is
                        // in points)
                        float left_x = (freespace_x / 2);
                        float left_y = freespace_y;

                        // calculate the lower right corner of the box
                        // (measurement is in points)
                        float image_w_points = (w / res_x) * 72;
                        float image_h_points = (h / res_y) * 72;

                        pcb.setLineWidth(1f);
                        pcb.stroke();
                        pcb.rectangle(left_x, left_y, image_w_points, image_h_points);

                        pcb.stroke();
                    }

                } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) {
                pdfImage = null;
                myInterpreter.clear();
                // writer.freeReader(new PdfReader(pdfpage.getURL()));
            } // end of : if (pdfpage.getURL() != null) {

            // ------------------------------------------------------------------------------------------------
            // it is a page from a PDF file which should be inserted
            // ------------------------------------------------------------------------------------------------
            else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) {

                PdfContentByte pdfcb = writer.getDirectContent();

                PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader();
                PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber());

                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    LOGGER.debug("creating orig pdf page");
                    Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber());
                    try {
                        pdfdoc.setPageSize(rect);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }
                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                } else {
                    LOGGER.debug("creating A4 pdf page");
                    try {
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                    // draw box
                    // if (pagesizemode == PdfPageSize.A4BOX) {
                    // FIXME: nichts implementiert ?
                    // }
                }

            }
            // handle pagename
            if (imageNames != null) {
                String pagename = imageNames.get(imageKey);

                if (pagename != null) {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename);
                } else {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered");
                }
            }
            // handle bookmarks and set destinator for bookmarks
            LOGGER.debug("handle bookmark(s) for page");

            PdfDestination destinator = new PdfDestination(PdfDestination.FIT);
            setBookmarksForPage(writer, destinator, imageKey); // the key in the
            writer.flush();
            // mashMap is the pagenumber

        } // end of while iterator over all pages

    }
    return pagelabels;

}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/**
 * Sets the default size of the page and creates the pdf document (com.lowagie.text.Document) instance.
 * //from   w w  w  .j  a v  a 2s.  c  o m
 * @param pagesizemode the pagesizemode
 * @param pagesize the pagesize
 * 
 * @return the pdf-document instance
 * 
 * @throws ImageInterpreterException the image interpreter exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Document setPDFPageSizeForFirstPage(PdfPageSize pagesizemode, Rectangle pagesize)
        throws ImageInterpreterException, IOException {

    Document pdfdoc;
    boolean isTitlePage = false;

    // set page size of the PDF
    if ((pagesizemode == PdfPageSize.ORIGINAL) && (pdftitlepage == null)) {
        LOGGER.debug("Page size of the first page is size of first image");

        // GDZ: Check if this changes the order of the Pages
        // What if 0000002 ist intentionaly before 00000001 ?

        // page size is set to size of first page of the document
        // (first image of imageURLs)
        Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs);
        for (Integer key : sortedMap.keySet()) {

            // do the image exists ?
            while (key < sortedMap.size()
                    && sortedMap.get(key).getURL().openConnection().getContentLength() == 0) {
                key++;
            }

            if ((pdftitlepages != null) && (pdftitlepages.get(key) != null)) {
                // title page for Document Part available; set pagesize to
                // A4
                pagesize = setA4pagesize();
                isTitlePage = true;
                break;
            }

            // no title page, so get the size of the first page
            UrlImage pdfpage = imageURLs.get(key);

            if (pdfpage.getURL() != null) {
                // it's an image file
                URL url = pdfpage.getURL();
                LOGGER.debug("Using image" + pdfpage.getURL().toString());
                ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost,
                        httpproxyport, httpproxyuser, httpproxypassword);

                float xres = myInterpreter.getXResolution();
                float yres = myInterpreter.getYResolution();

                int height = myInterpreter.getHeight();
                int width = myInterpreter.getWidth();

                int image_w_points = (width * 72) / ((int) xres);
                int image_h_points = (height * 72) / ((int) yres);

                pagesize = new Rectangle(image_w_points, image_h_points); // set
                // a retangle in the size of the image
                break; // get out of loop
            } else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) {
                // a pdf page, not an image file

                PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader();
                pagesize = pdfreader.getPageSize(pdfpage.getPageNumber());

            }
        }

    } else if (pdftitlepage != null) {
        isTitlePage = true;
        LOGGER.debug("Page size of the first page is A4, cause it is a title page");
        pagesize = setA4pagesize();
    } else {
        // page size is set to A4, because either the whole
        // PDF is in A4 or we will have a title page which is
        // in A4
        LOGGER.debug("Page size of the first page is A4, page size mode is " + pagesizemode);
        pagesize = setA4pagesize();
    }

    if (pagesize != null) { // pagesize is a rectangle; pagesize sets the
        // page for the first page
        pdfdoc = new Document(pagesize, 2.5f * 72f / 2.54f, 2.5f * 72f / 2.54f, 2.5f * 72f / 2.54f,
                3f * 72f / 2.54f);
        if (isTitlePage) {
            pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(),
                    pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin());
        }
    } else {
        LOGGER.warn("No pagesize available.... strange!");
        pdfdoc = new Document();
    }
    return pdfdoc;
}

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

@Override
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //inicializar documento: tamano de pagina, orientacion, margenes
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);
    doc.setPageSize(PageSize.LETTER.rotate());
    doc.setMargins(30, 30, 30, 40);

    doc.open();/*from  www. j a  v a  2  s.c om*/

    //crear fonts por defecto
    tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD);
    tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL);

    //definir pie de pagina del lado izquierdo
    String footerText = this.getFooter(); //read it from config.xml or web.xml
    String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm");

    //crear template (objeto interno de IText) y manejador de evento 
    //para imprimir el pie de pagina
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb = docWriter.getDirectContent();
    tpl = cb.createTemplate(20, 14);
    docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate));

    //titulo - lo lee de config.xml por defecto
    reportTitle = getReportTitle();
    Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD));
    t.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.add(t);

    //logo
    img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false));
    img.scalePercent(100);
    float imgY = doc.top() - img.getHeight();
    float imgX = doc.left();
    img.setAbsolutePosition(imgX, imgY);
    doc.add(img);

    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));

    //for each master record print a master/detail section
    MasterDetailReader dataobj = (MasterDetailReader) data;
    Recordset master = dataobj.getRecordset("master");
    master.top();
    while (master.next()) {
        //blank line
        doc.add(new Paragraph(" "));

        //print master section
        doc.add(getGroupMaster(master));

        //print detail section
        doc.add(getGroupDetail(master, dataobj.getDetail(master)));

    }

    //print grand total
    doc.add(new Paragraph(" "));

    doc.close();
    docWriter.close();

}

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * configure le document pdf./*  w w w . ja  v a  2s  .  c om*/
 * @param width
 * @param height
 * @param margin
 * @return doc
 */
private Document configureDocument(final float margin) {

    Document document = new Document();

    document.setPageSize(PageSize.A4.rotate());
    float marginPage = (margin / 2.54f) * 72f;
    document.setMargins(marginPage, marginPage, marginPage, marginPage);

    return document;
}

From source file:fr.univlorraine.mondossierweb.controllers.InscriptionController.java

License:Apache License

/**
 * configure le document pdf./* w  w  w . j av  a 2s  .com*/
 * @param width
 * @param height
 * @param margin
 * @return doc
 */
private Document configureDocument() {

    Document document = new Document();

    document.setPageSize(PageSize.A4);
    float marginTop = (MARGIN_TOP / 2.54f) * 72f;
    float marginRight = (MARGIN_RIGHT / 2.54f) * 72f;
    float marginBottom = (MARGIN_BOTTOM / 2.54f) * 72f;
    float marginLeft = (MARGIN_LEFT / 2.54f) * 72f;
    document.setMargins(marginLeft, marginRight, marginTop, marginBottom);

    return document;
}