Example usage for com.lowagie.text.pdf PdfWriter getInstance

List of usage examples for com.lowagie.text.pdf PdfWriter getInstance

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getInstance.

Prototype


public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

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  a  2  s  . com*/

    // 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.stratelia.webactiv.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

static public void buildPdf(String name, AlmanachSessionController almanach, String mode)
        throws AlmanachRuntimeException {
    try {/*from w w  w .  j a va 2 s  . com*/
        SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_ENTER_METHOD");

        String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(),
                almanach.getComponentId()) + name;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor(almanach.getSettings().getString("author", ""));
        document.addSubject(almanach.getSettings().getString("subject", ""));
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        try {
            Calendar currentDay = Calendar.getInstance();
            currentDay.setTime(almanach.getCurrentDay());
            String sHeader = almanach.getString("events");
            if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) {
                sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH));
            }
            sHeader += " " + currentDay.get(Calendar.YEAR);
            HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
            footer.setAlignment(Element.ALIGN_CENTER);

            document.setHeader(header);
            document.setFooter(footer);

            createFirstPage(almanach, document);
            document.newPage();

            Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
            Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " "
                    + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " "
                    + currentDay.get(Calendar.YEAR), titleFont);
            Chapter chapter = new Chapter(cTitle, 1);

            // Collection<EventDetail> events =
            // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY));
            AlmanachCalendarView almanachView;
            if (PDF_YEAR_EVENTSONLY.equals(mode)) {
                almanachView = almanach.getYearlyAlmanachCalendarView();
            } else {
                almanachView = almanach.getMonthlyAlmanachCalendarView();
            }

            List<DisplayableEventOccurrence> occurrences = almanachView.getEvents();
            generateAlmanach(chapter, almanach, occurrences, mode);

            document.add(chapter);
        } catch (Exception ex) {
            throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                    "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex);
        }

        document.close();
        SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_EXIT_METHOD");

    } catch (Exception e) {
        throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e);
    }

}

From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java

License:Open Source License

/**
 * Method declaration/* w  ww.ja v a2s .  com*/
 * @param name
 * @param completePubList
 * @param langue
 * @throws NewsEditoException
 * @see
 */
public static void generatePubList(String name, Collection<CompletePublication> completePubList, String langue)
        throws NewsEditoException {
    SilverTrace.info("NewsEdito", "PdfGenerator.generatePubList", "NewsEdito.MSG_ENTRY_METHOD",
            "Pdf name = " + name);
    try {
        CompletePublication first = completePubList.iterator().next();
        String fileName = FileRepositoryManager.getTemporaryPath(
                first.getPublicationDetail().getPK().getSpace(),
                first.getPublicationDetail().getPK().getComponentName()) + name;
        ResourceLocator message = new ResourceLocator(
                "com.stratelia.webactiv.newsEdito.multilang.newsEditoBundle", langue);
        // creation of the document with a certain size and certain margins
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor("Generateur de PDF Silverpeas");
        document.addSubject("Compilation de publications Silverpeas");
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        createFirstPage(document, langue);

        HeaderFooter header = new HeaderFooter(new Phrase(message.getString("publicationCompilation")), false);
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));

        footer.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);
        document.setFooter(footer);

        document.newPage();

        Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
        Paragraph cTitle = new Paragraph(message.getString("listPublication"), titleFont);
        Chapter chapter = new Chapter(cTitle, 1);

        Iterator<CompletePublication> i = completePubList.iterator();
        CompletePublication complete = null;
        while (i.hasNext()) {
            complete = i.next();

            addPublication(chapter, complete);
        }

        document.add(chapter);

        document.close();
    } catch (Exception e) {
        throw new NewsEditoException("PdfGenerator.generatePubList", NewsEditoException.WARNING,
                "NewsEdito.EX_PROBLEM_TO_GENERATE_PUBLI_LIST", e);
    }
}

From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java

License:Open Source License

/**
 * Method declaration/*  w  ww .  j  ava2 s.  c o  m*/
 * @param name
 * @param archiveDetail
 * @param publicationBm
 * @param langue
 * @throws NewsEditoException
 * @see
 */
public static void generateArchive(String name, NodeDetail archiveDetail, PublicationBm publicationBm,
        String langue) throws NewsEditoException {
    SilverTrace.info("NewsEdito", "PdfGenerator.generateArchive", "NewsEdito.MSG_ENTRY_METHOD",
            "Pdf name = " + name);
    try {
        String fileName = FileRepositoryManager.getTemporaryPath(archiveDetail.getNodePK().getSpace(),
                archiveDetail.getNodePK().getComponentName()) + name;
        // creation of the document with a certain size and certain margins
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor("Generateur de PDF Silverpeas");
        document.addSubject("Journal Silverpeas : " + archiveDetail.getName());
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        createFirstPage(document, langue);

        // we define a header and a footer
        String descriptionArchive = archiveDetail.getDescription();
        if (descriptionArchive == null)
            descriptionArchive = " ";

        HeaderFooter header = new HeaderFooter(new Phrase(archiveDetail.getName() + " : " + descriptionArchive),
                false);
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));

        footer.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);
        document.setFooter(footer);

        document.newPage();

        PdfGenerator.addEditorial(document, archiveDetail, publicationBm, langue);
        PdfGenerator.addMasterTable(document, archiveDetail, publicationBm);

        document.close();
    } catch (Exception e) {
        throw new NewsEditoException("PdfGenerator.generateArchive", NewsEditoException.WARNING,
                "NewsEdito.EX_PROBLEM_TO_GENERATE_ARCHIVE", e);
    }

}

From source file:com.t2.compassionMeditation.ViewSessionsActivity.java

License:Open Source License

/**
 * Create a PDF file based on the contents of the graph
 *//* www.j a v a 2s.c om*/
void CreatePdf() {

    // Run the export on a separate thread.
    new Thread(new Runnable() {
        @Override
        public void run() {

            Document document = new Document();
            try {
                Date calendar = Calendar.getInstance().getTime();
                mResultsFileName = "BioZenResults_";
                mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-"
                        + calendar.getDate() + "_";
                mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-"
                        + calendar.getSeconds() + ".pdf";

                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(android.os.Environment.getExternalStorageDirectory()
                                + java.io.File.separator + mResultsFileName));
                document.open();
                PdfContentByte contentByte = writer.getDirectContent();
                BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                // Note top of PDF = 900
                float chartWidth = 332;
                float chartHeight = 45;

                float spaceHeight = chartHeight + 30;
                int horizontalPos = 180;
                float verticalPos = 780;

                // Write document header
                contentByte.beginText();
                contentByte.setFontAndSize(baseFont, 20);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER,
                        "Generated on: " + calendar.toLocaleString(), 300, 770, 0);
                contentByte.endText();

                contentByte.setLineWidth(1f);
                verticalPos -= spaceHeight;
                long startTime = startCal.getTimeInMillis();
                long endTime = endCal.getTimeInMillis();

                float maxChartValue = 0;
                float chartYAvg;

                BioSession tmpSession = sessionItems.get(0);
                int maxKeys = tmpSession.keyItemNames.length;

                // Loop through all of the the keys
                for (int key = 0; key < maxKeys; key++) {

                    //Draw a border rect
                    contentByte.setRGBColorStrokeF(0, 0, 0);
                    contentByte.setLineWidth(1f);
                    contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight);
                    contentByte.stroke();

                    // Write band name
                    contentByte.beginText();
                    contentByte.setFontAndSize(baseFont, 12);
                    BioSession tmpSession1 = sessionItems.get(0);
                    contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170,
                            (verticalPos + (chartHeight / 2)) - 5, 0);
                    contentByte.endText();

                    maxChartValue = 0;
                    // First find the max Y
                    for (BioSession session : sessionItems) {
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            if (chartYAvg > maxChartValue)
                                maxChartValue = chartYAvg;
                        }
                    }

                    float lastY = -1;
                    float xIncrement = 0;
                    if (sessionItems.size() > 0) {
                        xIncrement = chartWidth / sessionItems.size();
                    }

                    float yIncrement = 0;
                    if (maxChartValue > 0) {
                        yIncrement = chartHeight / maxChartValue;
                    }

                    float highValue = 0;
                    int highTime = 0;
                    float highY = 0;
                    float highX = 0;
                    int lowTime = 0;
                    float lowY = 100;
                    float lowX = chartWidth;
                    float lowValue = maxChartValue;

                    int lCount = 0;
                    String keyName = "";

                    ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>();

                    // Loop through the session points of this key
                    String rawYValues = "";
                    for (BioSession session : sessionItems) {
                        keyName = session.keyItemNames[key];
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            rawYValues += chartYAvg + ", ";
                            if (lastY < 0)
                                lastY = (float) chartYAvg;

                            contentByte.setLineWidth(3f);
                            contentByte.setRGBColorStrokeF(255, 0, 0);

                            float graphXFrom = horizontalPos + (lCount * xIncrement);
                            float graphYFrom = verticalPos + (lastY * yIncrement);
                            float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement));
                            float graphYTo = verticalPos + (chartYAvg * yIncrement);
                            //                     Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]");
                            // Draw the actual graph
                            contentByte.moveTo(graphXFrom, graphYFrom);
                            contentByte.lineTo(graphXTo, graphYTo);
                            contentByte.stroke();

                            //Add regression Item
                            ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement)));

                            if (chartYAvg > highValue) {
                                highValue = chartYAvg;
                                highY = graphYTo;
                                highX = graphXTo;
                                highTime = (int) (session.time / 1000);
                            }

                            if (chartYAvg < lowValue) {
                                lowValue = chartYAvg;
                                lowY = graphYTo;
                                lowX = graphXTo;
                                lowTime = (int) (session.time / 1000);
                            }

                            lCount++;
                            lastY = (float) chartYAvg;

                        } // End if (session.time >= startTime && session.time <= endTime )
                    } // End for (BioSession session : sessionItems)            

                    //Draw high low dates
                    if (highY != 0 && lowY != 0) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
                        String hDate = dateFormat.format(new Date((long) highTime * 1000L));
                        String lDate = dateFormat.format(new Date((long) lowTime * 1000L));
                        contentByte.beginText();
                        contentByte.setFontAndSize(baseFont, 8);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0);
                        contentByte.endText();
                    }

                    //Draw Regression Line
                    RegressionResult regression = calculateRegression(ritems);
                    contentByte.saveState();
                    contentByte.setRGBColorStrokeF(0, 0, 250);
                    contentByte.setLineDash(3, 3, 0);
                    contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept);
                    contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept)
                            + (float) (regression.slope * (chartWidth / xIncrement))));
                    contentByte.stroke();
                    contentByte.restoreState();
                    contentByte.setRGBColorStrokeF(0, 0, 0);

                    //               Log.e(TAG, keyName + ": [" + rawYValues + "]");
                    // Get ready for the next key (and series of database points )
                    verticalPos -= spaceHeight;

                    if (verticalPos < 30) {
                        document.newPage();
                        verticalPos = 780 - spaceHeight;
                    }

                } // End for (int key = 0; key < maxKeys; key++)

                //document.add(new Paragraph("You can also write stuff directly tot he document like this!"));
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
                Log.e(TAG, de.toString());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
                Log.e(TAG, ioe.toString());
            } catch (Exception e) {
                System.err.println(e.getMessage());
                Log.e(TAG, e.toString());
            }

            // step 5: we close the document
            document.close();
            fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS);

        }
    }).start();

}

From source file:com.toolkit.util.pdf.ITextRenderer.java

License:Open Source License

/**
 * <B>NOTE:</B> Caller is responsible for cleaning up the OutputStream if
 * something goes wrong./*from www  .ja v  a  2  s. c o  m*/
 * 
 * @param os
 *            OutputStream
 * @param finish
 *            boolean
 * @throws DocumentException
 */
public void createPDF(final OutputStream os, final boolean finish) throws DocumentException {
    List pages = _root.getLayer().getPages();

    RenderingContext c = newRenderingContext();
    PageBox firstPage = (PageBox) pages.get(0);
    com.lowagie.text.Rectangle firstPageSize = new com.lowagie.text.Rectangle(0, 0,
            firstPage.getWidth(c) / _dotsPerPoint, firstPage.getHeight(c) / _dotsPerPoint);

    com.lowagie.text.Document doc = new com.lowagie.text.Document(firstPageSize, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(doc, os);
    if (_pdfEncryption != null) {
        // writer.setEncryption(true, _pdfEncryption.getUserPassword(),
        // _pdfEncryption.getOwnerPassword(),
        // _pdfEncryption.getAllowedPrivileges());
    }
    doc.open();

    if (!finish) {
        _pdfDoc = doc;
        _writer = writer;
    }

    writePDF(pages, c, firstPageSize, doc, writer);

    if (finish) {
        doc.close();
    }
}

From source file:com.trollworks.gcs.character.CharacterSheet.java

License:Open Source License

/**
 * @param file The file to save to.//from   ww  w .  j  a v a2  s  . c o m
 * @return <code>true</code> on success.
 */
public boolean saveAsPDF(File file) {
    HashSet<Row> changed = expandAllContainers();
    try {
        PrintManager settings = mCharacter.getPageSettings();
        PageFormat format = settings != null ? settings.createPageFormat() : createDefaultPageFormat();
        Paper paper = format.getPaper();
        float width = (float) paper.getWidth();
        float height = (float) paper.getHeight();

        adjustToPageSetupChanges(true);
        setPrinting(true);

        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(
                new com.lowagie.text.Rectangle(width, height));
        try (FileOutputStream out = new FileOutputStream(file)) {
            PdfWriter writer = PdfWriter.getInstance(pdfDoc, out);
            int pageNum = 0;
            PdfContentByte cb;

            pdfDoc.open();
            cb = writer.getDirectContent();
            while (true) {
                PdfTemplate template = cb.createTemplate(width, height);
                Graphics2D g2d = template.createGraphics(width, height, new DefaultFontMapper());

                if (print(g2d, format, pageNum) == NO_SUCH_PAGE) {
                    g2d.dispose();
                    break;
                }
                if (pageNum != 0) {
                    pdfDoc.newPage();
                }
                g2d.setClip(0, 0, (int) width, (int) height);
                print(g2d, format, pageNum++);
                g2d.dispose();
                cb.addTemplate(template, 0, 0);
            }
            pdfDoc.close();
        }
        return true;
    } catch (Exception exception) {
        return false;
    } finally {
        setPrinting(false);
        closeContainers(changed);
    }
}

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

/**
 * Representacin impresa PDF// w  w  w. ja  va 2  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:com.umlet.control.io.GenPdf.java

License:Open Source License

public void createPdfToStream(OutputStream ostream, DiagramHandler handler) {
    try {//from   w  w w. j  a v a  2 s . c om
        // We get the Rectangle of our DrawPanel
        java.awt.Rectangle bounds = handler.getDrawPanel().getContentBounds(Constants.PRINTPADDING);
        // and create an iText specific Rectangle from (0,0) to (width,height) in which we draw the diagram
        Rectangle drawSpace = new Rectangle((float) bounds.getWidth(), (float) bounds.getHeight());

        // Create document in which we write the pdf
        Document document = new Document(drawSpace);
        PdfWriter writer = PdfWriter.getInstance(document, ostream);
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D graphics2d = cb.createGraphics(drawSpace.getWidth(), drawSpace.getHeight());

        // We shift the diagram to the upper left corner, so we shift it by (minX,minY) of the contextBounds
        Dimension trans = new Dimension((int) bounds.getMinX(), (int) bounds.getMinY());
        graphics2d.translate(-trans.getWidth(), -trans.getHeight());

        handler.getDrawPanel().paintEntitiesIntoGraphics2D(graphics2d);

        graphics2d.dispose();
        document.close();

    } catch (Exception e) {
        System.out.println("UMLet: Error: Exception in outputPdf: " + e);
    }
}

From source file:com.unicornlabs.kabouter.reporting.PowerReport.java

License:Apache License

public static void GeneratePowerReport(Date startDate, Date endDate) {
    try {/*  w  w  w . j av a2 s  .  c om*/
        Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName());
        ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        File outputFile = new File("PowerReport.pdf");
        outputFile.createNewFile();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();

        document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString()));

        document.newPage();

        DecimalFormat df = new DecimalFormat("#.###");

        for (String deviceId : powerLogDeviceIds) {
            ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate);
            double total = 0;
            double max = 0;
            Date maxTime = startDate;
            double average = 0;
            XYSeries series = new XYSeries(deviceId);
            XYDataset dataset = new XYSeriesCollection(series);

            for (Powerlog log : powerlogs) {
                total += log.getPower();
                if (log.getPower() > max) {
                    max = log.getPower();
                    maxTime = log.getId().getLogtime();
                }
                series.add(log.getId().getLogtime().getTime(), log.getPower());
            }

            average = total / powerlogs.size();

            document.add(new Paragraph("\nDevice: " + deviceId));
            document.add(new Paragraph("Average Power Usage: " + df.format(average)));
            document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString()));
            document.add(new Paragraph("Total Power Usage: " + df.format(total)));
            //Create a custom date axis to display dates on the X axis
            DateAxis dateAxis = new DateAxis("Date");
            //Make the labels vertical
            dateAxis.setVerticalTickLabels(true);

            //Create the power axis
            NumberAxis powerAxis = new NumberAxis("Power");

            //Set both axes to auto range for their values
            powerAxis.setAutoRange(true);
            dateAxis.setAutoRange(true);

            //Create the tooltip generator
            StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance());

            //Set the renderer
            StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg,
                    null);

            //Create the plot
            XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer);

            //Create the chart
            JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true);

            PdfContentByte pcb = writer.getDirectContent();
            PdfTemplate tp = pcb.createTemplate(480, 360);
            Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper());
            Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360);
            myChart.draw(g2d, r2d);
            g2d.dispose();
            pcb.addTemplate(tp, 0, 0);

            document.newPage();
        }

        document.close();

        JOptionPane.showMessageDialog(null, "Report Generated.");

        Desktop.getDesktop().open(outputFile);
    } catch (FileNotFoundException fnfe) {
        JOptionPane.showMessageDialog(null,
                "Unable To Open File For Writing, Make Sure It Is Not Currently Open");
    } catch (IOException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}