Example usage for com.itextpdf.text Paragraph setSpacingAfter

List of usage examples for com.itextpdf.text Paragraph setSpacingAfter

Introduction

In this page you can find the example usage for com.itextpdf.text Paragraph setSpacingAfter.

Prototype

public void setSpacingAfter(float spacing) 

Source Link

Usage

From source file:com.athena.chameleon.engine.core.PDFDocGenerator.java

License:Apache License

/**
 *  ?// w w  w .ja  va2s  .com
 *
 * @param doc 
 * @param writer 
 * @param event
 * @throws Exception
 */
public static void setChapterSectionTOC(Document doc, PdfWriter writer, PDFCommonEventHelper event)
        throws Exception {

    doc.newPage();
    event.setPagingFlag(false);

    Paragraph title = new Paragraph(MessageUtil.getMessage("pdf.message.toc.title"),
            new Font(bfKorean, 13, Font.BOLD));
    title.setSpacingAfter(8);
    doc.add(title);

    int toc = writer.getPageNumber();
    for (Paragraph p : event.titles)
        doc.add(p);

    doc.newPage();
    int total = writer.reorderPages(null);

    int[] order = new int[total];
    for (int i = 0; i < total; i++) {
        order[i] = i + toc;
        if (order[i] > total)
            order[i] -= total;
    }
    // apply the new order
    writer.reorderPages(order);

}

From source file:com.athena.chameleon.engine.core.PDFDocGenerator.java

License:Apache License

public static void setLastPageInfo(Document doc, PdfWriter writer, int cNum) throws Exception {
    Chapter chapter = PDFWriterUtil.getChapter(MessageUtil.getMessage("pdf.message.chapter.confirm.title"),
            cNum);/*from   w  w  w. j  ava2 s.  co  m*/

    Paragraph preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.prepared1"),
            PDFWriterUtil.fnNormalBold));
    preP.add(new Phrase("                                                           ",
            new Font(bfKorean, 10, Font.UNDERLINE)));
    preP.setSpacingBefore(15);
    preP.setSpacingAfter(2);
    chapter.add(preP);

    preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.prepared2"),
            PDFWriterUtil.fnNormal));
    preP.setIndentationLeft(65);
    preP.setSpacingAfter(14);
    chapter.add(preP);

    preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.approved1"),
            PDFWriterUtil.fnNormalBold));
    preP.add(new Phrase("                                                           ",
            new Font(bfKorean, 10, Font.UNDERLINE)));
    preP.setSpacingBefore(15);
    preP.setSpacingAfter(2);
    chapter.add(preP);

    preP = new Paragraph();
    preP.add(new Phrase(MessageUtil.getMessage("pdf.message.chapter.confirm.approved2"),
            PDFWriterUtil.fnNormal));
    preP.setIndentationLeft(65);
    preP.setSpacingAfter(14);
    chapter.add(preP);

    cNum++;
    doc.add(chapter);

    chapter = PDFWriterUtil.getChapter(MessageUtil.getMessage("pdf.message.chapter.appendices.title"), cNum);
    Section section = PDFWriterUtil.getSection(chapter,
            MessageUtil.getMessage("pdf.message.chapter.appendices.label1"));

    Chunk url = new Chunk(MessageUtil.getMessage("pdf.message.chapter.appendices.text1"), PDFWriterUtil.fnURL);
    url.setAction(new PdfAction(new URL(MessageUtil.getMessage("pdf.message.chapter.appendices.text1"))));

    preP = new Paragraph(url);
    preP.setIndentationLeft(23);
    preP.setSpacingAfter(14);
    section.add(preP);

    section = PDFWriterUtil.getSection(chapter,
            MessageUtil.getMessage("pdf.message.chapter.appendices.label2"));

    doc.add(chapter);
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * Default  ?/*from  w w w . j a  v a  2  s.  co m*/
 *
 * @param text  text
 * @return Paragraph
 */
public static Paragraph getDefault(String text) {
    Paragraph ph = new Paragraph(text, fnNormal);
    ph.setMultipliedLeading(1.8F);
    ph.setIndentationLeft(23);
    ph.setSpacingAfter(14);
    return ph;
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * Default  ?(Bold)/*from   ww w  .j  a va 2 s . c o  m*/
 *
 * @param text  text
 * @return Paragraph
 */
public static Paragraph getDefaultPoint(String text) {
    Font font = new Font(bfKorean, 10, Font.BOLD);

    Paragraph ph = new Paragraph(" " + text, font);
    ph.setMultipliedLeading(1.8F);
    ph.setIndentationLeft(45);
    ph.setSpacingAfter(14);
    return ph;
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * Default  ?(RED)/*from  w  w  w.  j ava 2 s  . c o m*/
 *
 * @param text  text
 * @param style Font style
 * @return Paragraph
 */
public static Paragraph getDefaultRed(String text, int style) {
    Font font = new Font(bfKorean, 10, style);
    font.setColor(new BaseColor(255, 0, 0));

    Paragraph ph = new Paragraph(text, font);
    ph.setMultipliedLeading(1.8F);
    ph.setIndentationLeft(45);
    ph.setSpacingAfter(14);
    return ph;
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * Chapter  ?/* w w w. ja v  a 2  s.c  o m*/
 *
 * @param text Chapter title
 * @param chapterNo Chapter Number
 * @return Chapter
 */
public static Chapter getChapter(String text, int chapterNo) {

    Chapter chapter = new Chapter(text, chapterNo);
    String title = chapter.getTitle().getContent();

    Chunk c = new Chunk(text, fnChapter);
    c.setLocalDestination(title);
    Paragraph chapterPh = new Paragraph();
    chapterPh.add(c);
    chapterPh.setSpacingAfter(12);
    chapter.setTitle(chapterPh);
    return chapter;

}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * /* w ww  .  j a v a2  s.co  m*/
 * Section  ?
 *
 * @param chapter section?  chapter ?
 * @param text section title
 * @param sectionNo section Number
 * @return Section
 */
public static Section getSection(Section chapter, String text) {
    Section section = chapter.addSection(text);
    String title = section.getTitle().getContent();

    Chunk c;
    if (section.getDepth() >= 3) {
        c = new Chunk(text, fnSection2);
    } else {
        c = new Chunk(text, fnSection);
    }
    c.setLocalDestination(title);

    Paragraph sectionPh = new Paragraph();
    sectionPh.add(c);
    sectionPh.setSpacingBefore(8);
    sectionPh.setSpacingAfter(3);
    if (section.getDepth() >= 3)
        sectionPh.setIndentationLeft(23);

    section.setTitle(sectionPh);
    return section;
}

From source file:com.automaster.autoview.server.servlet.PdfServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   w  w w  .j a  v  a  2s  .c  o m
        this.dataAtual = new Date(System.currentTimeMillis());
        this.cnpjUn = null;

        String tempoDecorrido = " 0";
        int codVeiculo = Integer.parseInt(request.getParameter("cod"));
        String placa = request.getParameter("placa");
        Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio")));
        Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim")));

        TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3"));
        //System.out.println("Time zone : " + timeZonePadrao);

        ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO();
        VeiculoDAO veiculoDAO = new VeiculoDAO();
        TreeMap<String, String> veiculo = veiculoDAO.buscarVeiculoPorCodigo(codVeiculo);
        placa = veiculo.get("placa");
        //System.out.println("PLACA: "+veiculo.get("placa"));
        ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO
                .buscarPosicoesPorIntervaloData(placa, dataInicio, dataFim);
        int codCliente = Integer.parseInt(veiculo.get("clienteCodCliente"));
        //System.out.println("COD CLIENTE: "+codCliente);
        ClienteDAO clienteDAO = null;
        clienteDAO = new ClienteDAO();
        TreeMap<String, String> infoClienteUnidade = clienteDAO.buscarPorCodClienteSimplificado(codCliente);
        // Get the text that will be added to the PDF
        // step 1
        Document document = new Document();
        document.addHeader("Adriano", "AutoMaster");
        document.addCreator("Adriano Vale");
        document.addAuthor("Adriano Vale");
        document.addCreationDate();
        document.setPageSize(PageSize.A4.rotate());
        // step 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        TableHeader event = new TableHeader();
        writer.setPageEvent(event);
        // step 3
        document.open();
        // step 4
        //getServletContext().getRealPath("/")
        String url = getServletContext().getRealPath("/");
        //"D:\\Users\\Adriano\\Documents\\NetBeansProjects\\JRGWT\\web\\imagens\\logo.jpg"
        Image logo = Image.getInstance(url + "/imagens/logo.jpg");
        logo.setAlignment(Element.ALIGN_CENTER);

        Paragraph titulo = new Paragraph("Relatrio de Posies",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 20, Font.BOLD));
        titulo.setAlignment(Element.ALIGN_CENTER);

        Paragraph tituloPlaca = new Paragraph("Veculo: " + placa,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
        tituloPlaca.setAlignment(Element.ALIGN_CENTER);

        SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        dataFormatadaCabecalho.setTimeZone(timeZonePadrao);

        Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio")));
        Date dataHoraFim0 = new Date(Long.parseLong(request.getParameter("dataFim")));
        Paragraph periodo = new Paragraph(
                "Perodo: De: " + dataFormatadaCabecalho.format(dataHoraInicio0) + " at: "
                        + dataFormatadaCabecalho.format(dataHoraFim0),
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
        periodo.setSpacingAfter(10.0f);
        periodo.setAlignment(Element.ALIGN_CENTER);
        //PdfPTable tabela = new PdfPTable(new float[]{0.11f, 0.095f, 0.06f, 0.065f, 0.085f, 0.06f, 0.04f, 0.065f, 0.055f, 0.06f, 0.24f, 0.065f});
        PdfPTable tabela = new PdfPTable(new float[] { 0.07f, 0.045f, 0.045f, 0.27f });
        tabela.setWidthPercentage(98.0f);
        tabela.setHorizontalAlignment(Element.ALIGN_CENTER);
        PdfPCell tituloData = new PdfPCell(Phrase.getInstance("Data e Hora"));
        tituloData.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloData);
        //tabela.addCell("Data e hora");
        PdfPCell tituloVel = new PdfPCell(Phrase.getInstance("Velocidade"));
        tituloVel.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloVel);
        PdfPCell tituloIgn = new PdfPCell(Phrase.getInstance("Ignio"));
        tituloIgn.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloIgn);
        //tabela.addCell("Latitude");
        //tabela.addCell("Longitude");
        //tabela.addCell("Satlite");
        //tabela.addCell("GPS");
        //tabela.addCell("Entrada");
        //tabela.addCell("Sada");
        //tabela.addCell("Evento");
        PdfPCell tituloEnd = new PdfPCell(Phrase.getInstance("Endereo"));
        tituloEnd.setHorizontalAlignment(Element.ALIGN_CENTER);
        tabela.addCell(tituloEnd);
        //tabela.addCell("Direo");
        double latAnt = 0;
        double lonAnt = 0;
        double latAtual = 0;
        double lonAtual = 0;
        double distanciaTotal = 0;
        double distancia = 0;
        event.setHeader("AutoMaster");

        for (int i = 0; i < posicoes.size(); i++) {
            //for (int col = 0; col < posicoes.get(i).size(); col++) {
            if (i == 0) {
                distancia = 0;
                //System.out.println("linha 00 - PDF");
            } else {
                //System.out.println("linha 01 - PDF");
                latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat"));
                lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon"));
                latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
                lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
                //System.out.println("linha 02 - PDF");
                if (latAnt == latAtual && lonAnt == lonAtual) {
                    distancia = 0;
                } else {
                    distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
                    //System.out.println("linha 03 - PDF");
                }

            }
            distanciaTotal = distanciaTotal + distancia;
            //System.out.println("linha 04 - PDF");
            //TimeZone.setDefault(timeZoneMundial);
            Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora")));
            //System.out.println("dataHora0 : "+dataHora0.toString());
            //TimeZone.setDefault(timeZoneCliente);
            //Date dataHora = new Date(dataHora0.getTime());
            SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            dataFormatada.setTimeZone(timeZonePadrao);
            //System.out.println("dataFormatada : "+dataFormatada);
            PdfPCell celData = new PdfPCell(Phrase.getInstance(dataFormatada.format(dataHora0)));
            celData.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celData);
            //tabela.addCell(dataFormatada);
            PdfPCell celVel = new PdfPCell(Phrase.getInstance(posicoes.get(i).get("vel")));
            celVel.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celVel);
            PdfPCell celIgn = new PdfPCell(Phrase
                    .getInstance(posicoes.get(i).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada"));
            celIgn.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celIgn);
            //tabela.addCell(posicoes.get(i).get("lat"));
            //tabela.addCell(posicoes.get(i).get("lon"));
            //tabela.addCell(posicoes.get(i).get("sat"));
            //tabela.addCell(posicoes.get(i).get("gps"));
            //tabela.addCell(posicoes.get(i).get("entrada"));
            //tabela.addCell(posicoes.get(i).get("saida"));
            //tabela.addCell(posicoes.get(i).get("evento"));
            PdfPCell celEnd = new PdfPCell(
                    Phrase.getInstance(posicoes.get(i).get("endereco") == null ? "Sem endereo"
                            : posicoes.get(i).get("endereco")));
            celEnd.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(celEnd);
            //tabela.addCell(posicoes.get(i).get("direcao"));
            //}
        }
        //System.out.println("linha 05 - PDF");
        tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")),
                Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora")));
        //System.out.println("linha 06 - PDF");
        int index = 0;
        String kms = "0";
        String m = "";
        double metros = 0;
        //System.out.println("linha 07 - PDF");
        if (distanciaTotal > 0) {
            //System.out.println("linha 08 - PDF");
            BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN);
            //System.out.println("linha 09 - PDF");
            index = String.valueOf(decimalFormatado).indexOf(".");
            kms = String.valueOf(decimalFormatado).substring(0, index);
            m = "0" + (String.valueOf(decimalFormatado).substring(index));
            metros = Double.parseDouble(m) * 1000;
            //System.out.println("linha 10 - PDF");
        }
        /*document.add(new Paragraph(String.format(
         "You have submitted the following text using the %s method:",
         request.getMethod())));
         document.add(new Paragraph(text));*/
        //System.out.println("linha 11 - PDF");
        Paragraph kilometragem = new Paragraph(
                "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
        //System.out.println("linha 12 - PDF");
        periodo.setSpacingAfter(10.0f);
        periodo.setAlignment(Element.ALIGN_CENTER);
        // step 5
        document.add(logo);
        document.add(titulo);
        document.add(tituloPlaca);
        document.add(periodo);
        document.add(tabela);
        document.add(kilometragem);
        String dia = new SimpleDateFormat("dd").format(dataAtual);
        String ano = new SimpleDateFormat("yyyy").format(dataAtual);
        int mes = dataAtual.getMonth();
        String mesEscrito = null;
        switch (mes) {
        case 0:
            mesEscrito = "janeiro";
            break;
        case 1:
            mesEscrito = "fevereiro";
            break;
        case 2:
            mesEscrito = "maro";
            break;
        case 3:
            mesEscrito = "abril";
            break;
        case 4:
            mesEscrito = "maio";
            break;
        case 5:
            mesEscrito = "junho";
            break;
        case 6:
            mesEscrito = "julho";
            break;
        case 7:
            mesEscrito = "agosto";
            break;
        case 8:
            mesEscrito = "setembro";
            break;
        case 9:
            mesEscrito = "outubro";
            break;
        case 10:
            mesEscrito = "novembro";
            break;
        case 11:
            mesEscrito = "dezembro";
            break;
        }
        String textRodape = infoClienteUnidade.get("cidadeUnidade") + " , "
                + infoClienteUnidade.get("estadoUnidade") + "    " + dia + "  de  " + mesEscrito + "  de  "
                + ano + ".";
        Paragraph localData = new Paragraph(textRodape,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.PLAIN));
        localData.setAlignment(Element.ALIGN_RIGHT);
        localData.setSpacingBefore(30.0f);
        localData.setSpacingAfter(10.0f);
        document.add(localData);
        Image assinatura = Image.getInstance(url + "/imagens/assinatura.png");
        assinatura.setAlignment(Element.ALIGN_CENTER);
        assinatura.scaleAbsolute(185, 91);
        document.add(assinatura);
        Paragraph infoEmpresa1 = new Paragraph("AUTO MASTER LTDA",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
        infoEmpresa1.setAlignment(Element.ALIGN_CENTER);
        infoEmpresa1.setSpacingAfter(1f);
        document.add(infoEmpresa1);
        Paragraph infoEmpresa2 = new Paragraph("___________________________",
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
        infoEmpresa2.setAlignment(Element.ALIGN_CENTER);
        document.add(infoEmpresa2);
        String cnpjEmpresa = formataCNPJ(infoClienteUnidade.get("cnpjUnidade"));
        Paragraph infoEmpresa3 = new Paragraph(cnpjEmpresa,
                new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
        infoEmpresa3.setAlignment(Element.ALIGN_CENTER);
        document.add(infoEmpresa3);
        document.close();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".pdf");
        // the contentlength
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
    //        response.setContentType("text/html;charset=UTF-8");
    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet PdfServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet PdfServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.bdaum.zoom.email.internal.job.PdfJob.java

License:Open Source License

private void printPage(Document document, int pageNo, MultiStatus status, IProgressMonitor monitor)
        throws DocumentException, IOException {
    if (pageNo > 1)
        document.newPage();//from   ww  w.j  ava2s  . c o m
    document.setPageCount(pageNo);
    final Display display = Display.getDefault();
    int pageItem = 0;
    if (!layout.getTitle().isEmpty()) {
        String title = PageProcessor.computeTitle(layout.getTitle(), fileName, now, assets.size(), pageNo,
                pages, collection, meta);
        Paragraph p = new Paragraph(title,
                FontFactory.getFont(FontFactory.HELVETICA, titleSize, Font.BOLD, BaseColor.DARK_GRAY));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(layout.getSubtitle().isEmpty() ? titleLead + upperWaste : titleLead);
        document.add(p);
    }
    if (!layout.getSubtitle().isEmpty()) {
        String subtitle = PageProcessor.computeTitle(layout.getSubtitle(), fileName, now, assets.size(), pageNo,
                pages, collection, meta);
        Paragraph p = new Paragraph(subtitle,
                FontFactory.getFont(FontFactory.HELVETICA, subtitleSize, Font.NORMAL, BaseColor.DARK_GRAY));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(subtitleLead + upperWaste);
        document.add(p);
    }
    IVolumeManager vm = Core.getCore().getVolumeManager();
    PdfPTable table = new PdfPTable(layout.getColumns());
    try (Assetbox box = new Assetbox(null, status, false)) {
        for (int i = 0; i < rows; i++) {
            int ni = i * layout.getColumns();
            for (int j = 0; j < layout.getColumns(); j++) {
                int a = (pageNo - 1) * imagesPerPage + ni + j;
                PdfPCell cell;
                if (a >= assets.size() || monitor.isCanceled())
                    cell = new PdfPCell();
                else {
                    final int dpi = quality == Constants.SCREEN_QUALITY ? SCREENDPI : PRINTERDPI;
                    final int pixelWidth = (int) (imageWidth * dpi / 72);
                    final int pixelHeight = (int) (imageHeight * dpi / 72);
                    Asset asset = assets.get(a);
                    zimage = new ZImage(ImageUtilities.loadThumbnail(display, asset.getJpegThumbnail(), cms,
                            SWT.IMAGE_JPEG, true), null);
                    org.eclipse.swt.graphics.Rectangle bounds = zimage.getBounds();
                    URI uri = vm.findExistingFile(asset, false);
                    if (uri != null) {
                        boolean r = asset.getRotation() % 180 != 0;
                        double w = r ? asset.getHeight() : asset.getWidth();
                        double h = r ? asset.getWidth() : asset.getHeight();
                        double scale = w == 0 || h == 0 ? 1d : Math.min(pixelWidth / w, pixelHeight / h);
                        scale = (scale <= 0.5d) ? 0.5d : 1d;
                        File file = box.obtainFile(uri);
                        if (file != null)
                            try {
                                ZImage hzimage = CoreActivator.getDefault().getHighresImageLoader().loadImage(
                                        null, status, file, asset.getRotation(),
                                        asset.getFocalLengthIn35MmFilm(), null, scale, Double.MAX_VALUE, true,
                                        ImageConstants.SRGB, null, unsharpMask, null, fileWatcher, opId, null);
                                if (hzimage != null) {
                                    zimage.dispose();
                                    zimage = hzimage;
                                }
                            } catch (UnsupportedOperationException e) {
                                // do nothing
                            }
                    }
                    display.syncExec(() -> {
                        int kl = (keyLine > 0) ? (int) Math.max(1, (keyLine * dpi / 144)) : 0;
                        org.eclipse.swt.graphics.Rectangle ibounds = zimage.getBounds();
                        double factor = Math.min((double) pixelWidth / ibounds.width,
                                (double) pixelHeight / ibounds.height);
                        int lw = pixelWidth + 2 * kl;
                        int lh = pixelHeight + 2 * kl;
                        Image newImage = new Image(display, lw, lh);
                        GC gc = new GC(newImage);
                        try {
                            gc.setAntialias(SWT.ON);
                            gc.setInterpolation(SWT.HIGH);
                            gc.setAdvanced(true);
                            gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
                            gc.fillRectangle(0, 0, lw, lh);
                            int width = (int) (ibounds.width * factor + 2 * kl);
                            int height = (int) (ibounds.height * factor + 2 * kl);
                            int xoff = (lw - width) / 2;
                            int yoff = (lh - height) / 2;
                            if (kl > 0) {
                                gc.setBackground(display.getSystemColor(SWT.COLOR_DARK_GRAY));
                                gc.fillRectangle(xoff, yoff, width, height);
                            }
                            zimage.draw(gc, 0, 0, ibounds.width, ibounds.height, xoff + kl, yoff + kl,
                                    width - 2 * kl, height - 2 * kl, ZImage.CROPPED, pixelWidth, pixelHeight,
                                    false);
                        } finally {
                            gc.dispose();
                            zimage.dispose();
                            zimage = new ZImage(newImage, null);
                        }
                    });
                    bounds = zimage.getBounds();
                    File jpegFile = ImageActivator.getDefault().createTempFile("PdfImg", ".jpg"); //$NON-NLS-1$//$NON-NLS-2$
                    tempFiles.add(jpegFile);
                    try (FileOutputStream out = new FileOutputStream(jpegFile)) {
                        zimage.saveToStream(monitor, true, ZImage.UNCROPPED, SWT.DEFAULT, SWT.DEFAULT, out,
                                SWT.IMAGE_JPEG, jpegQuality);
                    }
                    zimage.dispose();
                    com.itextpdf.text.Image pdfImage = com.itextpdf.text.Image.getInstance(jpegFile.getPath());
                    double factor = Math.min(imageWidth / bounds.width, imageHeight / bounds.height);
                    pdfImage.setInterpolation(true);
                    pdfImage.scaleToFit((float) (bounds.width * factor), (float) (bounds.height * factor));
                    cell = new PdfPCell(pdfImage, false);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    monitor.worked(1);
                }
                cell.setFixedHeight((float) imageHeight);
                cell.setBorderWidth(0);
                table.addCell(cell);
            }
            renderCaptions(pageNo, seqNo, pageItem, table, ni, layout.getCaption1());
            renderCaptions(pageNo, seqNo, pageItem, table, ni, layout.getCaption2());
            pageItem += layout.getColumns();
            seqNo += layout.getColumns();
            if (verticalGap > 0 && i < rows - 1)
                for (int j = 0; j < layout.getColumns(); j++) {
                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(verticalGap);
                    cell.setBorderWidth(0);
                    table.addCell(cell);
                }
        }
        table.setWidthPercentage(100f);
        document.add(table);
        if (!layout.getFooter().isEmpty()) {
            String footer = PageProcessor.computeTitle(layout.getFooter(), fileName, now, assets.size(), pageNo,
                    pages, collection, meta);
            Paragraph p = new Paragraph(footer,
                    FontFactory.getFont(FontFactory.HELVETICA, subtitleSize, Font.NORMAL, BaseColor.DARK_GRAY));
            p.setAlignment(Element.ALIGN_CENTER);
            p.setSpacingBefore(upperWaste / 2 + footerLead);
            document.add(p);
        }
    }
}

From source file:com.bdaum.zoom.ui.internal.dialogs.ExhibitionEditDialog.java

License:Open Source License

private void writeDocument(Document document, File targetFile) {
    boolean frame = detailTabfolder.getSelectionIndex() == 1;
    try (FileOutputStream out = new FileOutputStream(targetFile)) {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();//from www  .  java2  s  . c  o  m
        writer.setPageEvent(new PdfPageEventHelper() {
            int pageNo = 0;
            com.itextpdf.text.Font ffont = new com.itextpdf.text.Font(
                    com.itextpdf.text.Font.FontFamily.HELVETICA, 9, com.itextpdf.text.Font.NORMAL,
                    BaseColor.DARK_GRAY);

            @Override
            public void onEndPage(PdfWriter w, Document d) {
                PdfContentByte cb = w.getDirectContent();
                Phrase footer = new Phrase(String.valueOf(++pageNo), ffont);
                ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer,
                        (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom(), 0);
            }
        });
        String tit = NLS.bind(Messages.ExhibitionEditDialog_exhibition_name, nameField.getText());
        Paragraph p = new Paragraph(tit,
                FontFactory.getFont(FontFactory.HELVETICA, 14, com.itextpdf.text.Font.BOLD, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(8);
        document.add(p);
        String subtitle = NLS.bind(Messages.ExhibitionEditDialog_image_list, Constants.DFDT.format(new Date()),
                frame ? Messages.ExhibitionEditDialog_image_sizes : Messages.ExhibitionEditDialog_frame_sizes);
        p = new Paragraph(subtitle,
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(14);
        document.add(p);
        p = new Paragraph(descriptionField.getText(),
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(10);
        document.add(p);
        p = new Paragraph(infoField.getText(),
                FontFactory.getFont(FontFactory.HELVETICA, 10, com.itextpdf.text.Font.NORMAL, BaseColor.BLACK));
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(10);
        document.add(p);
        IDbManager db = Core.getCore().getDbManager();
        List<Wall> walls = current.getWall();
        Wall[] sortedWalls = walls.toArray(new Wall[walls.size()]);
        Arrays.sort(sortedWalls, new Comparator<Wall>() {
            public int compare(Wall o1, Wall o2) {
                return o1.getLocation().compareToIgnoreCase(o2.getLocation());
            }
        });
        for (Wall wall : sortedWalls) {
            p = new Paragraph(wall.getLocation(), FontFactory.getFont(FontFactory.HELVETICA, 12,
                    com.itextpdf.text.Font.BOLD, BaseColor.BLACK));
            p.setAlignment(Element.ALIGN_LEFT);
            p.setSpacingAfter(12);
            document.add(p);
            PdfPTable table = new PdfPTable(7);
            // table.setBorderWidth(1);
            // table.setBorderColor(new Color(224, 224, 224));
            // table.setPadding(5);
            // table.setSpacing(0);
            table.setWidths(new int[] { 8, 33, 13, 13, 20, 13, 20 });
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_No, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_title, Element.ALIGN_LEFT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_xpos, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_height, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_size, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader(Messages.ExhibitionEditDialog_dpi, Element.ALIGN_RIGHT));
            table.addCell(createTableHeader("", Element.ALIGN_LEFT)); //$NON-NLS-1$
            // table.endHeaders();
            List<ExhibitImpl> exhibits = new ArrayList<ExhibitImpl>();
            for (String exhibitId : wall.getExhibit()) {
                ExhibitImpl exhibit = db.obtainById(ExhibitImpl.class, exhibitId);
                if (exhibit != null)
                    exhibits.add(exhibit);
            }
            Collections.sort(exhibits, new Comparator<ExhibitImpl>() {
                public int compare(ExhibitImpl e1, ExhibitImpl e2) {
                    return ((Exhibit) e1).getX() - ((Exhibit) e2).getX();
                }
            });
            int no = 1;
            for (ExhibitImpl exhibit : exhibits) {
                int tara = computeTara(frame, exhibit);
                table.addCell(createTableCell(String.valueOf(no++), Element.ALIGN_RIGHT));
                table.addCell(createTableCell(exhibit.getTitle(), Element.ALIGN_LEFT));
                af.setMaximumFractionDigits(2);
                af.setMinimumFractionDigits(2);
                String x = af.format((exhibit.getX() - tara) / 1000d);
                table.addCell(createTableCell(NLS.bind("{0} m", x), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                String y = af.format((exhibit.getY() + tara) / 1000d);
                table.addCell(createTableCell(NLS.bind("{0} m", y), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                af.setMaximumFractionDigits(1);
                af.setMinimumFractionDigits(1);
                String h = af.format((exhibit.getHeight() + 2 * tara) / 10d);
                int width = exhibit.getWidth();
                String w = af.format((width + 2 * tara) / 10d);
                table.addCell(createTableCell(NLS.bind("{0} x {1} cm", w, h), Element.ALIGN_RIGHT)); //$NON-NLS-1$
                AssetImpl asset = dbManager.obtainAsset(exhibit.getAsset());
                if (asset != null) {
                    int pixels = asset.getWidth();
                    double dpi = pixels * 25.4d / width;
                    table.addCell(createTableCell(String.valueOf((int) dpi), Element.ALIGN_RIGHT));
                } else
                    table.addCell(""); //$NON-NLS-1$
                table.addCell(createTableCell(exhibit.getSold() ? Messages.ExhibitionEditDialog_sold : "", //$NON-NLS-1$
                        Element.ALIGN_LEFT));
            }
            document.add(table);
        }
        document.close();
    } catch (DocumentException e) {
        UiActivator.getDefault().logError(Messages.ExhibitionEditDialog_internal_error_writing_pdf, e);
    } catch (IOException e) {
        UiActivator.getDefault().logError(Messages.ExhibitionEditDialog_io_error_writing_pdf, e);
    }
}