Example usage for com.itextpdf.text.pdf PdfWriter setInitialLeading

List of usage examples for com.itextpdf.text.pdf PdfWriter setInitialLeading

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter setInitialLeading.

Prototype

public void setInitialLeading(final float leading) throws DocumentException 

Source Link

Document

Sets the initial leading for the PDF document.

Usage

From source file:classes.utils.crearPDF_Depreciacion.java

public String writePDF(String datos, Scene scene)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (TextField) scene.lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();

    StringTokenizer st = new StringTokenizer(datos, "_");

    principal = st.nextToken();/*from www. ja  va 2 s  .c om*/
    salvageV = st.nextToken();
    period = st.nextToken();
    tax = st.nextToken();
    periodSalvage = st.nextToken();
    category = st.nextToken();
    data = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_depreciation.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nDEPRECIACION");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);

    //System.out.println(getClass().getResource("images/logo_report.png"));
    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    Image image1 = Image.getInstance(project + "/" + project + "_DEP_TY.png");

    image1.scaleToFit(300, 300);

    //image.setAlignment(Chunk.ALIGN_RIGHT);
    image1.setAlignment(Chunk.ALIGN_CENTER);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_3 = new Paragraph();
    paragraph_3.setFont(new Font(FontFactory.getFont("Courier", 11, Font.BOLD, BaseColor.BLACK)));
    paragraph_3.add("\n " + data);
    paragraph_3.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_5 = new Paragraph();
    paragraph_5.setFont(new Font(FontFactory.getFont("Courier", 6, Font.BOLD, BaseColor.BLUE)));
    paragraph_5.add("\n\nP   DEPRECIATON RATE  ANNUAL DEPRECIATON  CUMMULATIVE DEPRECIATON  VALUE IN LEDGERS ");
    paragraph_5.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 9, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Nombre del Evaluador: \n Principal: " + principal + " \n Salvag Value: " + salvageV
            + " \n Numero de Periodos: " + period + "\n Tax: " + tax + " \n Salvage Period: " + periodSalvage
            + "\n Categoria: " + category);
    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_6 = new Paragraph();
    paragraph_6.setFont(new Font(FontFactory.getFont("Courier", 15, Font.BOLD, BaseColor.GRAY)));
    paragraph_6.add("\n GRAFICAS\n");
    paragraph_6.setAlignment(Paragraph.ALIGN_CENTER);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);
    document.add(paragraph_5);
    document.add(paragraph_3);
    document.add(paragraph_6);
    Image image2 = Image.getInstance(project + "/" + project + "_DEP_DR.png");
    Image image3 = Image.getInstance(project + "/" + project + "_DEP_AD.png");
    Image image4 = Image.getInstance(project + "/" + project + "_DEP_ACD.png");
    Image image5 = Image.getInstance(project + "/" + project + "_DEP_LV.png");
    document.add(image2);
    document.add(image3);
    document.add(image4);
    document.add(image5);
    document.add(image1);
    document.add(paragraph_2);
    document.close();
    return null;

}

From source file:classes.utils.createPDF_checkList.java

public String writePDF(Scene scene, String datos)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (javafx.scene.control.TextField) scene
            .lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();
    StringTokenizer st = new StringTokenizer(datos, "*");

    dato1 = st.nextToken();//from ww  w.  ja  v  a2 s . c om
    dato2 = st.nextToken();
    dato3 = st.nextToken();
    dato4 = st.nextToken();
    dato5 = st.nextToken();
    dato6 = st.nextToken();
    dato7 = st.nextToken();
    dato8 = st.nextToken();
    dato9 = st.nextToken();
    dato10 = st.nextToken();
    dato11 = st.nextToken();
    dato12 = st.nextToken();
    dato13 = st.nextToken();
    dato14 = st.nextToken();
    dato15 = st.nextToken();
    dato16 = st.nextToken();
    dato17 = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_CheckList.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nCHECK LIST");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);

    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    //image.setAlignment(Chunk.ALIGN_RIGHT);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 6, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Strategy---Alignment What specific organization strategy does this project align with?"
            + "     " + dato1 + "\n" + "Driver---What business problem does the project solve?" + "     "
            + dato2 + "\n" + "Success Metrics---How will measure success?" + "     " + dato3 + "\n"
            + "Sponsorship---Who is the project sponsor?" + "     " + dato4 + "\n"
            + "Risk---What is the impact of not doing this project?" + "     " + dato5 + "\n"
            + "Risk---What is the project risk to our organization?" + "     " + dato6 + "\n"
            + "Risk---Where does the proposed project fit in our risk profile?" + "     " + dato7 + "\n"
            + "Benefits, value---What is the value of the project organization?" + "     " + dato8 + "\n"
            + "Benefits, value---When will the project shows results?" + "     " + dato9 + "\n"
            + "Objectives---What are the project objectives?" + "     " + dato10 + "\n"
            + "Organization Culture---Is our organization culture right for this type of project?" + "     "
            + dato11 + "\n" + "Resources---Will internal resources be available for this project?" + "     "
            + dato12 + "\n" + "Approach---Will we build or buy?" + "     " + dato13 + "\n"
            + "Schedule---How long will this project take?" + "     " + dato14 + "\n"
            + "Schedule---Is the timeline realistic?" + "     " + dato15 + "\n"
            + "Training/Resources---Will staff training be required?" + "     " + dato16 + "\n"
            + "Finance/Portfolio---What is the estimated cost of the project?" + "     " + dato17 + "\n");
    /*+ "Portfolio---Is this a new initiative or path of an existing initiative?"+"     "+dato18+"\n"
    + "Portfolio---How does this project interact with current projects?"+"     "+dato19+"\n"
    + "Technology---Is the technology available or new?"+"     "+dato20+"");
    */

    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);

    document.add(paragraph_2);
    document.close();
    return "pdf Creado";

}

From source file:classes.utils.createPDF_NetPresent.java

public String writePDF(Scene scene, String datos)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (javafx.scene.control.TextField) scene
            .lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();
    StringTokenizer st = new StringTokenizer(datos, "_");

    period = st.nextToken();//from www  .  j  av a2  s .  c  om
    principal = st.nextToken();
    interestRate = st.nextToken();
    tax = st.nextToken();
    salvageV = st.nextToken();
    periodSalvage = st.nextToken();
    data = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_NetPresentValue.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nNET PRESENT VALUE");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);

    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    Image image1 = Image.getInstance(project + "/" + project + "_NPV_CCF.png");

    image1.scaleToFit(300, 300);

    //image.setAlignment(Chunk.ALIGN_RIGHT);
    image1.setAlignment(Chunk.ALIGN_CENTER);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_3 = new Paragraph();
    paragraph_3.setFont(new Font(FontFactory.getFont("Courier", 11, Font.BOLD, BaseColor.BLACK)));
    paragraph_3.add("\n " + data);
    paragraph_3.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_5 = new Paragraph();
    paragraph_5.setFont(new Font(FontFactory.getFont("Courier", 10, Font.BOLD, BaseColor.BLUE)));
    paragraph_5.add("\n\nP   OUTFLOW   INFLOW   NET CASH FLOW   CUMULATIVE CASH ");
    paragraph_5.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 9, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Nombre del Evaluador: \nPeriods: " + period + "\n Principal: " + principal
            + " \n Interest Rate%: " + interestRate + " \n Tax Rate %: " + tax + "\n Salvage Value: " + salvageV
            + " \n Period SV: " + periodSalvage);
    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_6 = new Paragraph();
    paragraph_6.setFont(new Font(FontFactory.getFont("Courier", 15, Font.BOLD, BaseColor.GRAY)));
    paragraph_6.add("\n GRAFICAS\n");
    paragraph_6.setAlignment(Paragraph.ALIGN_CENTER);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);
    document.add(paragraph_5);
    document.add(paragraph_3);
    document.add(paragraph_6);
    document.add(image1);
    Image image2 = Image.getInstance(project + "/" + project + "_NPV_NCF.png");
    document.add(image2);
    document.add(paragraph_2);
    document.close();
    return null;

}

From source file:classes.utils.createPDF_PayBack.java

public String writePDF(Scene scene, String datos)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {

    javafx.scene.control.TextField projectName = (javafx.scene.control.TextField) scene
            .lookup(CNodeID.TEXTFIELD_PROJECT_NAME);
    String project = projectName.getText();

    StringTokenizer st = new StringTokenizer(datos, "_");

    period = st.nextToken();//from  w  w w .  ja v  a  2s.com
    principal = st.nextToken();
    interestRate = st.nextToken();
    data = st.nextToken();

    Document document = new Document(PageSize.LETTER, 80, 80, 50, 50);
    FileOutputStream salida = new FileOutputStream(project + "_PayBackPeriod.pdf");
    PdfWriter writer = PdfWriter.getInstance(document, salida);
    writer.setInitialLeading(0);

    Paragraph paragraph = new Paragraph();
    paragraph.setFont(new Font(FontFactory.getFont("Courier", 20, Font.BOLDITALIC, BaseColor.RED)));
    paragraph.add("\n\n\nPAYBACK PERIOD");
    paragraph.setAlignment(Paragraph.ALIGN_CENTER);
    // TODO: Change absolute to relative
    //Image image = Image.getInstance("/home/isaac/IdeaProjects/ProjectEvaluation/src/images/logo_report.png");

    //image.scaleToFit(150, 150);

    Image image1 = Image.getInstance(project + "/" + project + "_PBP_CCF.png");

    image1.scaleToFit(300, 300);

    //image.setAlignment(Chunk.ALIGN_RIGHT);
    image1.setAlignment(Chunk.ALIGN_CENTER);

    Paragraph paragraph_2 = new Paragraph();
    paragraph_2.setFont(new Font(FontFactory.getFont("Courier", 12, Font.BOLD, BaseColor.BLUE)));
    paragraph_2.add(
            "\n\n\n\n\n\n\n\n\n\n\nADMINISTRACION Y EVALUACION DE PROYECTOS\n\n SERGIO VALDES TORRES A01365520\n ERIK MARTIN A01365096\nISAAC SECUNDINO A01361162\n IVAN CABRER A01184937");
    paragraph_2.setAlignment(Paragraph.ALIGN_RIGHT);

    Paragraph paragraph_3 = new Paragraph();
    paragraph_3.setFont(new Font(FontFactory.getFont("Courier", 11, Font.BOLD, BaseColor.BLACK)));
    paragraph_3.add("\n " + data);
    paragraph_3.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_5 = new Paragraph();
    paragraph_5.setFont(new Font(FontFactory.getFont("Courier", 10, Font.BOLD, BaseColor.BLUE)));
    paragraph_5.add("\n\nP   OUTFLOW  INFLOW  CUMMULATIVE CASH... ");
    paragraph_5.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_4 = new Paragraph();
    paragraph_4.setFont(new Font(FontFactory.getFont("Courier", 9, Font.BOLD, BaseColor.BLACK)));
    paragraph_4.add("Nombre del Evaluador: \n Principal: " + principal + " \n Numero de Periodos: " + period
            + "\nInterest Rate %" + interestRate);
    paragraph_4.setAlignment(Paragraph.ALIGN_LEFT);

    Paragraph paragraph_6 = new Paragraph();
    paragraph_6.setFont(new Font(FontFactory.getFont("Courier", 15, Font.BOLD, BaseColor.GRAY)));
    paragraph_6.add("\n GRAFICAS\n");
    paragraph_6.setAlignment(Paragraph.ALIGN_CENTER);

    document.open();
    //document.add(image);

    document.add(paragraph);

    document.add(paragraph_4);
    document.add(paragraph_5);
    document.add(paragraph_3);
    document.add(paragraph_6);
    Image image2 = Image.getInstance(project + "/" + project + "_PBP_NCF.png");
    document.add(image1);
    document.add(image2);
    document.add(paragraph_2);
    document.close();
    return null;

}

From source file:com.algoboss.erp.util.report.PDFExporter2.java

License:Apache License

public void export(FacesContext context, String cssstring, String htmlstring, String filename)
        throws IOException {
    try {/*from  www. j ava2 s.com*/
        InputStream is = new ByteArrayInputStream(htmlstring.getBytes());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, baos);

        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);

        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        String[] cssstringArray = cssstring.split(";");
        FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context2 = (ServletContext) aFacesContext.getExternalContext().getContext();
        String realPath = context2.getRealPath("/");
        System.out.println(realPath);
        System.out.println(context2.getContextPath());
        //System.out.println(context2.getResource(""));  
        System.out.println(aFacesContext.getExternalContext().getContextName());
        System.out.println(aFacesContext.getExternalContext().getRequestContextPath()
                + aFacesContext.getExternalContext().getRequestServletPath());
        //System.out.println(aFacesContext.getExternalContext().getRequestServletPath());
        //System.out.println(aFacesContext.getExternalContext().getRequestPathInfo());
        //System.out.println(aFacesContext.getExternalContext().getRequestScheme());
        //System.out.println(aFacesContext.getExternalContext().getRequestScheme());
        //System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
        for (int i = 0; i < cssstringArray.length; i++) {
            String cssHref = cssstringArray[i];
            try {
                URL url = new URL(aFacesContext.getExternalContext().getRequestScheme(),
                        aFacesContext.getExternalContext().getRequestServerName(),
                        aFacesContext.getExternalContext().getRequestServerPort(), cssHref);
                InputStream csspathtest = url.openStream();
                CssFile cssfiletest = XMLWorkerHelper.getCSS(csspathtest);
                cssResolver.addCss(cssfiletest);
            } catch (IOException ex) {
                Logger.getLogger(PDFExporter2.class.getName()).log(Level.SEVERE, null, ex);
            }
            //String realPath2 = context2.getRealPath(cssHref);

            //InputStream csspathtest2 = aFacesContext.getExternalContext().getResourceAsStream(realPath2);
            //System.out.println(cssfiletest);
        }

        Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser p = new XMLParser(worker);
        p.parse(is, Charset.forName("iso-8859-1"));//new FileInputStream("results/demo2/walden.html"));

        // step
        document.close();

        // post back...
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-disposition", "inline;filename=\"" + filename + "\";");
        response.setContentLength(baos.size());
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
        context.responseComplete();

    } catch (IOException e) {
        throw new IOException(e.getMessage());
    } catch (Exception ex) {
        Logger.getLogger(PDFExporter2.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.apcb.utils.utils.PdfCreator.java

public static String createPdf(String fileName, String innerHTML, Document document) throws Exception {

    log.info("Creando HTML nombre: " + fileName);
    File fileHTML = new File(fileName);
    fileHTML.getParentFile().mkdirs();//from  w  w w .  jav a2 s .  c om
    PrintWriter writerHTML = new PrintWriter(fileHTML, "UTF-8");
    writerHTML.println(innerHTML);
    writerHTML.flush();
    writerHTML.close();
    log.info("Creado HTML ruta: " + fileHTML.getAbsolutePath());

    log.info("Creando PDF nombre: " + fileName + ".pdf");
    File filePDF = new File(fileName + ".pdf");

    filePDF.getParentFile().mkdirs();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName + ".pdf"));
    writer.setInitialLeading(12);
    document.open();
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(fileHTML));
    document.close();

    log.info("Creado PDF ruta: " + filePDF.getAbsolutePath());
    log.info("filePDF.getName() " + filePDF.getName());
    return filePDF.getName();
}

From source file:com.pdfs.generadorDevolucionReport.java

public boolean generarReporteDev(List<Devolucion> listaDevo, String nombre) {
    try {//w  ww.j av a 2 s .  c o m

        FileOutputStream archivoPdf = null;

        System.out.println("nombre documento: " + nombre);

        File archivo = new File(nombre);
        System.out.println("Se creo el archivo");

        archivoPdf = new FileOutputStream(archivo);

        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter pw = PdfWriter.getInstance(documento, archivoPdf);
        pw.setInitialLeading(20);

        // abrir el documento
        documento.open();
        System.out.println("Se abrio el documento");

        Paragraph p = new Paragraph("RELACION DE DEVOLUCIONES DE CUENTAS", tituloN1);
        p.setAlignment(Chunk.ALIGN_CENTER);
        documento.add(p);

        documento.close();

        return true;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(generadorDevolucionReport.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (DocumentException ex) {
        Logger.getLogger(generadorDevolucionReport.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:com.pdfs.GeneradorVisitas.java

public boolean generarVisitas(List<DatosVisitaDomiciliaria> creditos, String nombre) {
    FileOutputStream ficheroPdf = null;
    //rutaimg = rutafirma;
    try {/*from w  w w . j  a v  a  2s. c  o  m*/
        System.out.println("nombre  " + nombre);
        System.out.println("ruta " + rutaimg);

        File nombrearchivo = new File(nombre);
        LogSistema.guardarlog("ruta " + nombrearchivo.getAbsolutePath());

        ficheroPdf = new FileOutputStream(nombrearchivo);
        LogSistema.guardarlog("descriptor " + ficheroPdf.getFD().valid());

        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter pw = PdfWriter.getInstance(documento, ficheroPdf);
        pw.setInitialLeading(20);
        // Se abre el documento.
        documento.open();
        System.out.println("ABRIO EL DOCUMENTO");

        String prod;
        int cont = 0;
        LogSistema.guardarlog("al generar " + creditos.size());
        for (DatosVisitaDomiciliaria ct : creditos) {
            prod = ct.getProducto().toUpperCase();
            if (prod.contains("EXPRESS")) {
                System.out.println("ENTRO A CT EXPRESS");
                if (cont == 0) {
                    addCreditosExpress(ct);
                    cont++;
                } else {
                    documento.newPage();
                    addCreditosExpress(ct);
                }

                //sofom 
            } else if (prod.compareTo("A_LINEA CREDITO TELMEX PF 50") == 0
                    || prod.compareTo("A_LINEA CREDITO TELMEX PM 50") == 0
                    || prod.compareTo("EX LINEA CREDITO TELMEX PF") == 0
                    || prod.compareTo("EX LINEA CREDITO TELMEX PM") == 0
                    || prod.compareTo("A_LINEA CREDITO TELMEX PERSONAL 38") == 0
                    || prod.compareTo("EX LINEA CREDITO TELMEX PERSONAL 38") == 0
                    || prod.compareTo("A_LINEA CREDITO TELNOR PERSONAL 38") == 0) {
                if (cont == 0) {
                    addCreditosTelmexSOFOM(ct);
                    cont++;
                } else {
                    documento.newPage();
                    addCreditosTelmexSOFOM(ct);
                }
                //linea telmex
            } else if (prod.compareTo("LINEA CREDITO TELMEX PF") == 0
                    || prod.compareTo("LINEA CREDITO TELMEX PM") == 0
                    || prod.compareTo("EXLINEA CREDITO TELMEX PF") == 0
                    || prod.compareTo("EXLINEA CREDITO TELMEX PM") == 0
                    || prod.compareTo("LINEA CREDITO TELNOR PF") == 0
                    || prod.compareTo("EX LINEA CREDITO TELNOR PF") == 0
                    || prod.compareTo("EXLINEA CREDITO TELNOR PM") == 0
                    || prod.compareTo("A_LINEA CREDITO TELNOR PF 50") == 0
                    || prod.compareTo("A_LINEA CREDITO TELNOR PM 50") == 0
                    || prod.compareTo("LINEA CREDITO TELNOR PM") == 0
                    || prod.compareTo("A_EX LINEA CREDITO TELNOR PF 50") == 0
                    || prod.compareTo("A_EXLINEA CREDITO TELNOR PM 50") == 0) {
                if (cont == 0) {
                    addCreditosTelmex(ct);
                    cont++;
                } else {
                    documento.newPage();
                    addCreditosTelmex(ct);
                }
            }
        }

        documento.close();

        return true;

    } catch (FileNotFoundException ex) {
        LogSistema.guardarlog(ex.getMessage() + " " + new Date());
        return false;
    } catch (DocumentException ex) {
        LogSistema.guardarlog(ex.getMessage() + " " + new Date());
        return false;
    } catch (IOException ex) {
        LogSistema.guardarlog(ex.getMessage() + " " + new Date());
        return false;
    } finally {
        try {
            ficheroPdf.close();
        } catch (IOException ex) {
            LogSistema.guardarlog(ex.getMessage() + " " + new Date());
            return false;
        }
    }

}

From source file:com.pdi.util.PdfGenerator.java

public static void generarPresupuesto(String lugar, Date fecha, float cantidad, String tipo, Cliente cliente,
        float precio, Aliado aliado, String path) {

    try {/*from   www . j ava2 s  .c  o  m*/

        NEGRITA_12_VERDE.setColor(145, 189, 57);

        long miliSemana = System.currentTimeMillis() + (86400 * 7 * 1000);
        Date vtoPresup = new Date(miliSemana);
        float precioPers = precio / cantidad;
        int precioTotalInt = Math.round(precio);
        int precioPersInt = Math.round(precioPers);
        int cantPersonasInt = Math.round(cantidad);

        //Referencia al objeto Doc
        Document document = new Document(PageSize.A4, //Dimensiones
                36, //margIzq
                36, //margDer
                36, //margenSup
                36); // margenInf

        //Creamos el archivo fisico
        FileOutputStream salida = new FileOutputStream(path);

        //Referencia e inicializacion del objeto que "escribe" el PDF
        PdfWriter writer = PdfWriter.getInstance(document, salida);
        writer.setInitialLeading(0);

        //Imagen Logo
        Image logoPDI = Image.getInstance("Logo PDI.png");
        logoPDI.scaleToFit(215, 205);
        logoPDI.setAlignment(Chunk.ALIGN_LEFT);
        //image.setAbsolutePosition(200, 200);

        //Imagen QR
        Image qr = Image.getInstance("QR PDI.png");
        qr.scaleToFit(211, 165);
        qr.setAbsolutePosition(295, PageSize.A4.getHeight() - 390);

        //Parrafo info evento
        Paragraph infoEvento = new Paragraph();
        infoEvento.add(new Chunk("Informacin del Evento", NEGRITA_SUB_12));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.add(negritaNormal("Solicitante: ", cliente.toString()));
        infoEvento.add(negritaNormal("Evento: ", tipo));
        infoEvento.add(negritaNormal("Cantidad de personas: ", Integer.toString(cantPersonasInt)));
        infoEvento.add(negritaNormal("Fecha: ", General.formatoFecha.format(fecha)));
        infoEvento.add(negritaNormal("Lugar:  ", lugar));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Modalidad del Servicio
        Paragraph modalidadServicio = new Paragraph();
        modalidadServicio.add(new Chunk("Modalidad Servicio Integral", NEGRITA_SUB_12));
        modalidadServicio.add(Chunk.NEWLINE);
        modalidadServicio.add(new Chunk("Nuestro servicio incluye la totalidad de lo referido a"
                + " los elementos necesarios para el despacho de bebidas: Barras, Bartenders,"
                + " Artculos de Coctelera, Insumos de calidad para los tragos y Mucha Buena Onda."
                + " Con esta modalidad aseguramos la expedicin de "
                + "los tragos desde las 00hs hasta las 05hs, para que se desentiendan del asunto "
                + "y disfruten al mximo.", NORMAL_12));
        modalidadServicio.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Ver Carta
        Paragraph verCarta = new Paragraph();
        verCarta.add(negritaNormal("\u2022 Carta de Tragos: ", "Ver archivo adjunto."));
        verCarta.setIndentationLeft(20);
        verCarta.add(Chunk.NEWLINE);
        verCarta.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Titulo Info Contratacion
        Paragraph infoContratacionTitulo = new Paragraph();
        infoContratacionTitulo.add(new Chunk("Informacin de Contratacin", NEGRITA_SUB_12));
        infoContratacionTitulo.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Inf de Contratacion
        Paragraph infoContratacion = new Paragraph();
        infoContratacion.add(negritaNormal("\u2022 Mtodo de contratacin y reserva de la fecha: ",
                "A travs de contrato firmado por ambas partes. "));
        Phrase lineaCosto = new Phrase();
        lineaCosto.add(new Chunk("\u2022 Costo: ", NEGRITA_12));
        lineaCosto.add(new Chunk("$" + Integer.toString(precioPersInt) + " ", NEGRITA_14));
        lineaCosto.add(new Chunk("por persona ", NEGRITA_12));
        lineaCosto.add(new Chunk("(Total: $" + Integer.toString(precioTotalInt) + ")", NEGRITA_14));
        infoContratacion.add(lineaCosto);
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.add(negritaNormal("\u2022 Forma de Pago : ",
                "50% al momento de la firma del contrato y 50% como mximo una semana antes del evento. "));
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.setIndentationLeft(20);
        infoContratacion.setFirstLineIndent(0);
        infoContratacion.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Despedida
        Paragraph despedida = new Paragraph();
        despedida.add(new Phrase("Quedamos al aguardo de tus comentarios,", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(new Phrase("Muchas Gracias.", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(Chunk.NEWLINE);
        despedida.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Firma
        Paragraph firma = new Paragraph();
        firma.add(new Phrase("Piel de Iguana Tragos.-", NEGRITA_CUR_14));
        firma.add(Chunk.NEWLINE);
        firma.add(new Phrase("Cel.: 3462-15337860", NEGRITA_12_VERDE));
        firma.setAlignment(Paragraph.ALIGN_RIGHT);

        float llxLink = 279;
        float llyLink = PageSize.A4.getHeight() - 145;
        float anchoLink = 199;
        float altoLink = 16;

        //Link al facebook
        URL urlPDI = new URL("https://www.facebook.com/pieldeiguanatragos.vt");
        PdfAction irAlFace = new PdfAction(urlPDI);
        Rectangle linkLocation = new Rectangle(llxLink, llyLink, llxLink + anchoLink, llyLink + altoLink);
        PdfAnnotation link = PdfAnnotation.createLink(writer, linkLocation, PdfAnnotation.HIGHLIGHT_NONE,
                irAlFace);
        link.setBorder(new PdfBorderArray(0, 0, 0));
        writer.addAnnotation(link);

        //Espacios Vacios
        Paragraph dosEspacios = new Paragraph();
        dosEspacios.add(Chunk.NEWLINE);
        dosEspacios.add(Chunk.NEWLINE);

        //Hay que abrir el Documento, llenarlo con los elemntos creados
        //en el orden que queremos y cerrarlo
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        ColumnText ct = new ColumnText(cb);
        Phrase recuadro = new Phrase();
        recuadro.add(new Chunk("Piel de Iguana Tragos", NEGRITA_SUB_14));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Servicio de tragos para eventos", NEGRITA_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("\"Piel de Iguana, para que tu noche nica sea inigualable.\"", NORMAL_CUR_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        Image logoFB = Image.getInstance("Icono FB.png");
        logoFB.scaleToFit(13, 13);
        recuadro.add(new Chunk(logoFB, 0, -3));
        recuadro.add(new Chunk("/pieldeiguanatragos.vt  -> Click Aqu!", NORMAL_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Vencimiento del Prepuesto " + General.formatoFecha.format(vtoPresup),
                NORMAL_SUB_12));

        float llx = 279;
        float lly = PageSize.A4.getHeight() - 185;
        float ancho = 228;
        float alto = 150;

        ct.setSimpleColumn(recuadro, //Texto
                llx, //punta inf izquierda (x)
                lly, //punta inf izquierda (y) PageSize.A4.getHeight() - 185
                llx + ancho, //ancho del cuadro
                lly + alto, // alto del cuadro
                15, //espaciado
                Element.ALIGN_LEFT // Alineacion
        );

        ct.go();

        document.add(logoPDI);
        document.add(qr);
        document.add(dosEspacios);
        document.add(infoEvento);
        document.add(modalidadServicio);
        document.add(verCarta);
        document.add(infoContratacionTitulo);
        document.add(infoContratacion);
        document.add(despedida);
        document.add(firma);
        document.close();
        System.out.println("Archivo creado");
        int rta = JOptionPane.showConfirmDialog(VentanaMaestra.eventosCurrent,
                "Se guard el presupesto en:\n" + path + "\nDesea abrirlo?", "Presupuesto guardado",
                JOptionPane.YES_NO_OPTION);

        if (rta == JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
                try {
                    File myFile = new File(path);
                    Desktop.getDesktop().open(myFile);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                            "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                            "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                        "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                        "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
            }

        }

    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (DocumentException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (IOException ex) {
        System.out.println("Error: " + ex.toString());
    }

}

From source file:com.semfapp.adamdilger.semf.Pdf.java

License:Open Source License

private void createPDFNew(String filePath, String htmlString, @Nullable ArrayList<ImageFile> images) {

    File file = null;//from   w ww. j a v a2 s.  c  o  m
    try {
        file = new File(filePath);

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        // step 4

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssFile cssFile = XMLWorkerHelper.getCSS(activity.getAssets().open("styles.css"));
        cssResolver.addCss(cssFile);

        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // Pipelines

        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        Drawable d = activity.getResources().getDrawable(R.drawable.logo_icon);
        Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapData = stream.toByteArray();

        Image image = Image.getInstance(bitmapData);
        image.setAbsolutePosition(35, 763);
        image.scalePercent(12);
        document.add(image);

        p.parse(new ByteArrayInputStream(htmlString.getBytes(StandardCharsets.UTF_8)));

        if (images != null) {
            System.out.println("Adding IMage");

            for (int x = 0; x < images.size(); x++) {
                Image cursor = images.get(x).getImage();

                float ratio = cursor.getPlainHeight() / cursor.getPlainWidth();

                float imgWidth = document.getPageSize().getWidth() - 100;
                float imgHeight = document.getPageSize().getHeight() - 100;

                cursor.scaleToFit(new Rectangle(imgWidth, imgHeight));

                document.add(cursor);
            }
        }

        // step 5
        document.close();

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