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.openkm.util.DocConverter.java

License:Open Source License

/**
 * Convert SRC to PDF/*from w  ww  . j ava2s  . c o  m*/
 */
public void src2pdf(File input, File output, String lang)
        throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from SRC to PDF **");
    FileOutputStream fos = null;
    FileInputStream fis = null;

    try {
        fos = new FileOutputStream(output);
        fis = new FileInputStream(input);

        // Make syntax highlight
        String source = IOUtils.toString(fis);
        JaSHi jashi = new JaSHi(source, lang);
        // jashi.EnableLineNumbers(1);
        String parsed = jashi.ParseCode();

        // Make conversion to PDF
        Document doc = new Document(PageSize.A4.rotate());
        PdfWriter.getInstance(doc, fos);
        doc.open();
        HTMLWorker html = new HTMLWorker(doc);
        html.parse(new StringReader(parsed));
        doc.close();
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.openkm.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion//from w  ww  .ja v  a 2 s.c  om
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        // int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                // doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                // ++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:com.openkm.util.PDFUtils.java

License:Open Source License

/**
 * Generate sample PDF//from   ww w.j a va  2s.c o  m
 */
public static void generateSample(int paragraphs, OutputStream os) throws DocumentException {
    LoremIpsum li = new LoremIpsum();
    Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
    PdfWriter.getInstance(doc, os);
    doc.open();

    for (int i = 0; i < paragraphs; i++) {
        doc.add(new Paragraph(li.getParagraphs()));
    }

    doc.close();
}

From source file:com.orange.atk.compModel.PDFGenerator.java

License:Apache License

/**
 * @see com.orange.atk.results.logger.documentGenerator.DocumentGenerator#dumpInStream(boolean, interpreter.logger.DocumentLogger)
 *//*from w w w .  j av a 2  s. c  o  m*/

public void dumpInStream(boolean isParseErrorHappened, /*DocumentLogger dl,*/ org.w3c.dom.Document xmlDoc,
        Model model3) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;

    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("ScreenShot report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Reference directory: " + model3.getRefDirectory());
    pSum.add(Chunk.NEWLINE);
    pSum.add("Test directory: " + model3.getTestDirectory());
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMMMM dd, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.add(Chunk.NEWLINE);
    if (model3.getNbFail() > 0) {
        pSum.add(model3.getNbFail() + "/" + model3.getNbImages() + " images didn't succeed the test.");
    } else {
        pSum.add("All images (" + model3.getNbImages() + ") have succeed this comparaison.");
    }
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

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

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("ScreenShots");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    NodeList imgs = xmlDoc.getElementsByTagName("img");
    for (int i = 0; i < imgs.getLength(); i++) {
        org.w3c.dom.Element eImg = (org.w3c.dom.Element) imgs.item(i);
        if (eImg.getElementsByTagName("Pass").item(0).getTextContent().equals(Model.FAIL)) {

            org.w3c.dom.Element eRef = (org.w3c.dom.Element) eImg.getElementsByTagName("Ref").item(0);
            org.w3c.dom.Element eTest = (org.w3c.dom.Element) eImg.getElementsByTagName("Test").item(0);
            Paragraph pScreen = new Paragraph(eTest.getAttributes().getNamedItem("name").getNodeValue() + " "
                    + eImg.getElementsByTagName("Pass").item(0).getTextContent());
            Section section31 = chapter3.addSection(pScreen);
            PdfPTable scTable = null;
            scTable = new PdfPTable(2);
            scTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            scTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            scTable.getDefaultCell().setPadding(5);
            if (new File(eRef.getTextContent()).exists()) {
                Image refImg;
                try {
                    refImg = Image.getInstance(eRef.getTextContent());
                    refImg.scaleToFit(310, 260);
                    refImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(refImg);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (new File(eTest.getTextContent()).exists()) {
                Image testImg;
                try {
                    BufferedImage bi = ImageIO.read(new File(eTest.getTextContent()));
                    Graphics2D g2d = (Graphics2D) bi.getGraphics();
                    g2d.setStroke(new BasicStroke(1.5f));
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));

                    Boolean2D dif = model3.getCouplesComparaison().get(i).getDifWithMask();
                    //               if (squarable){
                    g2d.setColor(Color.red);
                    int w = bi.getWidth();
                    int h = bi.getHeight();
                    //TODO: Gurvan, Maybe we need to have the list of masks in the report?
                    Mask mask = model3.getCouplesComparaison().get(i).getMaskSum();
                    //g2d.drawRect(0, 0, mask.getWidth()*2*sampleWidth, mask.getHeight()*2*sampleHeight);
                    for (int x = 0; x < mask.getWidth(); x++) {

                        for (int y = 0; y < mask.getHeight(); y++) {

                            if (mask.getCell(x, y)) {
                                g2d.setColor(Color.blue);
                                ////Logger.getLogger(this.getClass() ).debug("grise");
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }

                            if (!dif.get(x, y)) {
                                g2d.setColor(Color.green);
                                g2d.fillRect(x * 2 * Mask.getCELL_HALF_SIZE(), y * 2 * Mask.getCELL_HALF_SIZE(),
                                        2 * Mask.getCELL_HALF_SIZE(), 2 * Mask.getCELL_HALF_SIZE());
                            }
                        }
                    }
                    testImg = Image.getInstance(bi, null);
                    testImg.scaleToFit(310, 260);
                    testImg.setAlignment(Element.ALIGN_BASELINE);
                    scTable.addCell(testImg);
                    section31.add(Chunk.NEWLINE);
                    section31.add(scTable);
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (DOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            section31.add(new Paragraph("Reference screenshot description : "
                    + eImg.getElementsByTagName("RefDescription").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31
                    .add(new Paragraph("Mask : " + eImg.getElementsByTagName("Mask").item(0).getTextContent()));
            section31.add(Chunk.NEWLINE);

            section31.add(new Paragraph(
                    "Comment : " + eImg.getElementsByTagName("Comment").item(0).getTextContent()));
            section31.add(new Paragraph(Chunk.NEXTPAGE));

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

    // step 5: we close the document
    document.close();
}

From source file:com.orange.atk.results.logger.documentGenerator.PDFGenerator.java

License:Apache License

/**
 * @see com.orange.atk.results.logger.documentGenerator.DocumentGenerator#dumpInStream(boolean,
 *      com.orange.atk.results.logger.log.DocumentLogger)
 *//*from   www  .  jav  a 2 s .  c o m*/
public void dumpInStream(boolean isParseErrorHappened, DocumentLogger dl) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;
    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    // step 4: we add a paragraph to the document
    List<Message> msgLogged = dl.getMsgsLogged();
    Paragraph pLoggedMsg = new Paragraph();
    // logged messages
    for (int i = 0; i < msgLogged.size(); i++) {
        Message msg = msgLogged.get(i);
        SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ssSSS");
        String dateString = formatter.format(msg.getTimestamp());
        switch (msg.getType()) {
        case Message.INFO_MSG:
            pLoggedMsg.add("[" + dateString + "] " + msg.getMessage());
            break;
        case Message.WARN_MSG:
            pLoggedMsg.add("[" + dateString + "] WARN : " + msg.getMessage() + " at line : " + msg.getLine());
            break;
        case Message.ERROR_MSG:
            pLoggedMsg.add("[" + dateString + "] ERROR : " + msg.getMessage() + " at line : " + msg.getLine());
            break;
        default:
            break;

        }
        pLoggedMsg.add(Chunk.NEWLINE);
    }

    Paragraph pLastLogguedLines = new Paragraph();
    int startIndex = msgLogged.size() > 5 ? msgLogged.size() - 5 : 0;
    for (int i = startIndex; i < msgLogged.size(); i++) {
        Message m = msgLogged.get(i);
        switch (m.getType()) {
        case Message.INFO_MSG:
            pLastLogguedLines.add("INFO : " + m.getMessage());
            break;
        case Message.WARN_MSG:
            pLastLogguedLines.add("WARN : " + m.getMessage());
            break;
        case Message.ERROR_MSG:
            pLastLogguedLines.add("ERROR : " + m.getMessage());
            break;
        default:
            break;

        }
        pLastLogguedLines.add(Chunk.NEWLINE);
    }
    // l.setIndentationLeft(40);
    // Min/Max/Ave values
    /*
     * PdfPTable table = new PdfPTable(4); table.addCell("");
     * table.addCell("Min"); table.addCell("Max"); table.addCell("Avg");
     * 
     * 
     * table.addCell("Battery in  %"); table.addCell(String.valueOf(dl
     * .getMinValueFromList(dl.getplt("BATTERY"))));
     * table.addCell(String.valueOf(dl
     * .getMaxValueFromList(dl.getplt("BATTERY"))));
     * table.addCell(String.valueOf(dl
     * .getAveValueFromList(dl.getplt("BATTERY"))));
     * table.addCell("Storage in bytes"); table.addCell(String.valueOf(dl
     * .getMinValueFromList(dl.getplt("Storage"))));
     * table.addCell(String.valueOf(dl
     * .getMaxValueFromList(dl.getplt("Storage"))));
     * table.addCell(String.valueOf(dl
     * .getAveValueFromList(dl.getplt("Storage"))));
     */
    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("Execution report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

    Chunk c11 = new Chunk("Executive summary");
    c11.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c11.setFont(FONT_PAR_TITLE);
    Paragraph title12 = new Paragraph(c11);
    Section section12 = chapter1.addSection(title12);
    Paragraph pExecSum = new Paragraph();
    // pExecSum.add("Value : ");
    // pExecSum.add(Chunk.NEWLINE);
    // pExecSum.add(table);
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.add("Last logged lines : ");
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.add(pLastLogguedLines);
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.setIndentationLeft(20);

    section12.add(pExecSum);

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

    // Chapter 2 : Log information
    Chunk c2 = new Chunk("Log information");
    c2.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c2.setFont(FONT_PAR_TITLE);
    Paragraph title2 = new Paragraph(c2);
    title2.setAlignment("CENTER");
    title2.setLeading(20);
    Chapter chapter2 = new Chapter(title2, 1);
    chapter2.setNumberDepth(0);

    Section section2 = chapter2.addSection("Log");
    // Add log information
    section2.add(pLoggedMsg);
    section2.add(Chunk.NEWLINE);

    // section2.add(table);
    try {
        document.add(chapter2);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("Graphics");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    // add current graph
    Map<String, PlotList> mapint = dl.getMapint();
    Set<String> cles = mapint.keySet();
    Iterator<String> it = cles.iterator();
    while (it.hasNext()) {
        String cle = (String) it.next();
        Paragraph pCPUimg = new Paragraph(cle);
        Section section31 = chapter3.addSection(pCPUimg);
        if (new File(dl.getPNGpath(cle)).exists()) {
            Image jpg1 = null;
            try {
                jpg1 = Image.getInstance(dl.getPNGpath(cle));
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (jpg1 == null) {
                Logger.getLogger(this.getClass()).warn("Error when Creating image jpg1 is null");
                return;
            }
            // jpg1.setRotationDegrees(270);
            jpg1.scalePercent(75);
            jpg1.setAlignment(Element.ALIGN_CENTER);
            section31.add(jpg1);
            PlotList plotlist = mapint.get(cle);
            DecimalFormat df = new DecimalFormat("#,###.##");

            if (plotlist.getType() == PlotList.TYPE_SUM) {
                section31.add(new Paragraph("Total : " + df.format(plotlist.getTotal() / plotlist.getScale())
                        + " " + plotlist.getunit()));
            } else { // PlotList.TYPE_AVG
                section31.add(new Paragraph("Average : "
                        + df.format(plotlist.getAverage() / plotlist.getScale()) + " " + plotlist.getunit()));
            }

        }
        section31.add(new Paragraph(Chunk.NEXTPAGE));
    }

    /*
     * // Section 3.1 : CPU data Paragraph pCPUimg = new
     * Paragraph("CPU data"); Section section31 =
     * chapter3.addSection(pCPUimg); if (new
     * File(dl.getPNGpath("CPU")).exists()) { Image jpg1 = null; try { jpg1
     * = Image.getInstance(dl.getPNGpath("CPU")); } catch
     * (BadElementException e) { e.printStackTrace(); } catch
     * (MalformedURLException e) { e.printStackTrace(); } catch (IOException
     * e) { e.printStackTrace(); } //jpg1.setRotationDegrees(270);
     * jpg1.scalePercent(75); jpg1.setAlignment(Element.ALIGN_CENTER);
     * section31.add(jpg1); } section31.add(new Paragraph(Chunk.NEXTPAGE));
     * 
     * // Section 3.2 : BAT data Paragraph pBATimg = new
     * Paragraph("Battery data"); Section section32 =
     * chapter3.addSection(pBATimg); if (new
     * File(dl.getPNGpath("BATTERY")).exists()) { Image jpg2 = null; try {
     * jpg2 = Image.getInstance(dl.getPNGpath("BATTERY")); } catch
     * (BadElementException e) { e.printStackTrace(); } catch
     * (MalformedURLException e) { e.printStackTrace(); } catch (IOException
     * e) { e.printStackTrace(); } //jpg2.setRotationDegrees(270);
     * jpg2.scalePercent(75); jpg2.setAlignment(Element.ALIGN_CENTER);
     * section32.add(jpg2); } section32.add(new Paragraph(Chunk.NEXTPAGE));
     * 
     * // Section 3.3 : MEM data Paragraph pMEMimg = new
     * Paragraph("Memory data"); Section section33 =
     * chapter3.addSection(pMEMimg); if (new
     * File(dl.getPNGpath("MEMORY")).exists()) {
     * 
     * Image jpg3 = null; try { jpg3 =
     * Image.getInstance(dl.getPNGpath("MEMORY")); } catch
     * (BadElementException e) { e.printStackTrace(); } catch
     * (MalformedURLException e) { e.printStackTrace(); } catch (IOException
     * e) { e.printStackTrace(); } //jpg3.setRotationDegrees(270);
     * jpg3.scalePercent(75); jpg3.setAlignment(Element.ALIGN_CENTER);
     * section33.add(jpg3); } section33.add(new Paragraph(Chunk.NEXTPAGE));
     * 
     * // Section 3.4 : STO data Paragraph pSTOimg = new
     * Paragraph("Storage data"); Section section34 =
     * chapter3.addSection(pSTOimg); if (new
     * File(dl.getPNGpath("Storage")).exists()) {
     * 
     * Image jpg4 = null; try { jpg4 =
     * Image.getInstance(dl.getPNGpath("Storage")); } catch
     * (BadElementException e) { e.printStackTrace(); } catch
     * (MalformedURLException e) { e.printStackTrace(); } catch (IOException
     * e) { e.printStackTrace(); } //jpg4.setRotationDegrees(270);
     * jpg4.scalePercent(75); jpg4.setAlignment(Element.ALIGN_CENTER);
     * section34.add(jpg4); }
     * 
     * 
     * // Section 3.5 : Network connection //Paragraph pNetworkimg = new
     * Paragraph("Network QoS data"); //Section section35 =
     * chapter3.addSection(pNetworkimg); // if (new
     * File(dl.getNetworkPNGfile()).exists()) {
     * 
     * // Image jpg5 = null; // try { // jpg5 =
     * Image.getInstance(dl.getNetworkPNGfile()); // } catch
     * (BadElementException e) { // e.printStackTrace(); // } catch
     * (MalformedURLException e) { // e.printStackTrace(); // } catch
     * (IOException e) { // e.printStackTrace(); // }
     * //jpg4.setRotationDegrees(270); // jpg5.scalePercent(75); //
     * jpg5.setAlignment(Element.ALIGN_CENTER); // section35.add(jpg5); //}
     */
    try {
        document.add(chapter3);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    // if (isTableEnabled) {
    // // Add tables filled with measurement
    // // Chapter 4 : Measurement tables
    // Chunk c4 = new Chunk("Statistics tables");
    // c4.setBackground(new Color(0xFF, 0x66, 0x00), 200, 3f, 200f, 3f);
    // c4.setFont(FontFactory.getFont(BaseFont.HELVETICA,
    // BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16));
    // Paragraph title4 = new Paragraph(c4);
    // title4.setAlignment("CENTER");
    // title4.setLeading(20);
    // Chapter chapter4 = new Chapter(title4, 1);
    // chapter4.setNumberDepth(0);
    //
    // // Section 4.1 : Battery value
    // Paragraph titleSection41 = new Paragraph("Battery value");
    // Section section41 = chapter4.addSection(titleSection41);
    // Paragraph pBatList = new Paragraph();
    // pBatList.add(Chunk.NEWLINE);
    // pBatList.add(createPDFTableFromList(dl
    // .getList(DocumentLogger.BATTERY), "Battery"));
    // pBatList.setAlignment("CENTER");
    // section41.add(pBatList);
    //
    // // Section 4.2 : CPU value
    // Paragraph titleSection42 = new Paragraph("CPU value");
    // Section section42 = chapter4.addSection(titleSection42);
    // Paragraph pCPUList = new Paragraph();
    // pCPUList.add(Chunk.NEWLINE);
    // pCPUList.add(createPDFTableFromList(dl.getList(DocumentLogger.CPU),
    // "CPU"));
    // pCPUList.setAlignment("CENTER");
    // section42.add(pCPUList);
    //
    // // Section 4.3 : Memory value
    // Paragraph titleSection43 = new Paragraph("Memory value");
    // Section section43 = chapter4.addSection(titleSection43);
    // Paragraph pMemList = new Paragraph();
    // pMemList.add(Chunk.NEWLINE);
    // pMemList.add(createPDFTableFromList(dl
    // .getList(DocumentLogger.MEMORY), "Memory"));
    // pMemList.setAlignment("CENTER");
    // section43.add(pMemList);
    //
    // // Section 4.4 : Storage value
    // Paragraph titleSection44 = new Paragraph("Storage value");
    // Section section44 = chapter4.addSection(titleSection44);
    // Paragraph pStoList = new Paragraph();
    // pStoList.add(Chunk.NEWLINE);
    // pStoList.add(createPDFTableFromList(dl
    // .getList(DocumentLogger.STORAGE), "Storage"));
    // pStoList.setAlignment("CENTER");
    // section44.add(pStoList);
    //
    // try {
    // document.add(chapter4);
    // } catch (DocumentException e) {
    // e.printStackTrace();
    // }
    // }

    // step 5: we close the document
    document.close();
    createHTMLFile(dl);
}

From source file:com.orange.atk.results.logger.documentGenerator.PDFGenerator.java

License:Apache License

public void dumpInStreamactionlogger(boolean isParseErrorHappened, ActionsLogger actionlog, DocumentLogger dl) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;/*  ww  w.j a va 2 s.c o m*/
    Vector VectAction = actionlog.getActions();
    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    // step 4: we add a paragraph to the document
    Paragraph pLoggedMsg = new Paragraph();
    // logged messages

    for (int i = 0; i < VectAction.size(); i++) {
        Action action = (Action) VectAction.get(i);
        SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ssSSS");
        SimpleDateFormat spf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss SSS");
        String dateString = spf.format(action.getStartTime());
        pLoggedMsg.add("[" + dateString + "]  : " + action.getActionName());

        pLoggedMsg.add(Chunk.NEWLINE);

    }

    Paragraph pLastLogguedLines = new Paragraph();
    int startIndex = VectAction.size() > 5 ? VectAction.size() - 5 : 0;
    for (int i = startIndex; i < VectAction.size(); i++) {
        Action action = (Action) VectAction.get(i);
        // SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ssSSS");
        SimpleDateFormat spf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss SSS");
        String dateString = spf.format(action.getStartTime());
        pLastLogguedLines.add("[" + dateString + "]  : " + action.getActionName());

        pLastLogguedLines.add(Chunk.NEWLINE);

    }

    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("Execution report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

    Chunk c11 = new Chunk("Executive summary");
    c11.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c11.setFont(FONT_PAR_TITLE);
    Paragraph title12 = new Paragraph(c11);
    Section section12 = chapter1.addSection(title12);
    Paragraph pExecSum = new Paragraph();
    // pExecSum.add("Value : ");
    // pExecSum.add(Chunk.NEWLINE);
    // pExecSum.add(table);
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.add("Last logged lines : ");
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.add(pLastLogguedLines);
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.setIndentationLeft(20);

    section12.add(pExecSum);

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

    // Chapter 2 : Log information
    Chunk c2 = new Chunk("Log information");
    c2.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c2.setFont(FONT_PAR_TITLE);
    Paragraph title2 = new Paragraph(c2);
    title2.setAlignment("CENTER");
    title2.setLeading(20);
    Chapter chapter2 = new Chapter(title2, 1);
    chapter2.setNumberDepth(0);

    Section section2 = chapter2.addSection("Log");
    // Add log information
    section2.add(pLoggedMsg);
    section2.add(Chunk.NEWLINE);

    // section2.add(table);
    try {
        document.add(chapter2);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("Graphics");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    // add current graph
    Map<String, PlotList> mapint = dl.getMapint();
    Set<String> cles = mapint.keySet();
    Iterator<String> it = cles.iterator();
    while (it.hasNext()) {
        String cle = (String) it.next();
        Paragraph pCPUimg = new Paragraph(cle);
        Section section31 = chapter3.addSection(pCPUimg);
        if (new File(dl.getPNGpath(cle)).exists()) {
            Image jpg1 = null;
            try {
                jpg1 = Image.getInstance(dl.getPNGpath(cle));
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (jpg1 == null) {
                Logger.getLogger(this.getClass()).warn("Error when Creating image jpg1 is null");
                return;
            }
            // jpg1.setRotationDegrees(270);
            jpg1.scalePercent(75);
            jpg1.setAlignment(Element.ALIGN_CENTER);
            section31.add(jpg1);
        }
        section31.add(new Paragraph(Chunk.NEXTPAGE));
    }

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

    document.close();
    createHTMLFileactionlog(actionlog, dl);
}

From source file:com.preparatic.archivos.PdfGenerator.java

License:Apache License

/**
  * Genera un pdf para las preguntas y otro para las soluciones.
  * /*from  w ww .java 2 s  .  c  om*/
  * @throws Exception
  */
 public String guardarPDF() throws Exception {

     // Abrir documentos
     docpregs = new Document();
     docsols = new Document();

     String pregsFilename = FactoriaArchivo.pdfTestFilename(test.getTipoTest(), test.getIdBloqueTematicaAnho(),
             test.getIdTest());
     PdfWriter writerPregs = PdfWriter.getInstance(docpregs,
             FactoriaArchivo.pdfTest(test.getTipoTest(), test.getIdBloqueTematicaAnho(), test.getIdTest()));
     TestFooter footerPregs = new TestFooter(test.getTitulo()); //mod_AZ_2018-02-04
     writerPregs.setPageEvent(footerPregs);

     PdfWriter.getInstance(docsols,
             FactoriaArchivo.pdfSol(test.getTipoTest(), test.getIdBloqueTematicaAnho(), test.getIdTest()));

     docpregs.open();

     docsols.open();
     docpregs.setMargins(80, 80, 72, 36);
     docsols.setMargins(80, 80, 36, 36);

     // Aadir logo
     Image gif = Image.getInstance(ConfigProperties.getProperty("files.rootDir") + "/images/logo-alpha.png"); //mod_AZE_2018-02-04 (logo con fondo blanco)

     gif.setAlignment(Image.LEFT);
     gif.scaleAbsolute(148, 46); //mod_AZE_2018-02-04 (para que entre bien el logo nuevo)
     docpregs.add(gif);
     docsols.add(gif);

     ponerTitulo(docpregs, docsols);

     // Adimos las preguntas al documento de preguntas
     docpregs.add(listaPreguntas);

     /*
      * Aadimos las respuestas, en varias columnas al documento de
      * respuestas.
      */
     MultiColumnText multiColumnTextSoluciones = new MultiColumnText();
     multiColumnTextSoluciones.addRegularColumns(docsols.left(), docsols.right(), 20f,
             Integer.parseInt(ConfigProperties.getProperty("tests.solucion.columnas")));
     multiColumnTextSoluciones.addElement(listaSoluciones);
     docsols.add(multiColumnTextSoluciones);

     // Cerramos los documentos
     docpregs.close();
     docsols.close();

     return pregsFilename;
 }

From source file:com.prime.location.billing.InvoicedBillingManager.java

/**
 * Print invoice/*from ww  w.j a  va  2s .  c  om*/
 */
public void printInvoice() {
    try { //catch better your exceptions, this is just an example
        FacesContext context = FacesContext.getCurrentInstance();

        Document pdf = new Document(PageSize.A4, 5f, 5f, 75f, 45f);

        String fileName = "PDFFile";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(pdf, baos);
        TableHeader event = new TableHeader();
        event.setHeader("Header Here");
        writer.setPageEvent(event);

        if (!pdf.isOpen()) {
            pdf.open();
        }

        PdfPCell cell;

        PdfPTable header = new PdfPTable(new float[] { 1, 2, 1 });
        cell = new PdfPCell(new Paragraph("INVOICE",
                FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC, Color.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);
        header.setTotalWidth(527);
        header.setLockedWidth(true);

        cell = new PdfPCell(new Phrase("Agency: " + selectedAgency.getDescription()));
        cell.setColspan(2);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);

        cell = new PdfPCell(new Phrase("Invoice#: " + selectedInvoice.getId()));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Date: " + DateUtility.dateTimeFormat(selectedInvoice.getInvoiceDate())));
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        pdf.add(header);

        PdfPTable table = new PdfPTable(new float[] { 1, 3, 2, 1 });
        table.setSpacingBefore(15f);

        table.setTotalWidth(527);
        table.setLockedWidth(true);
        //table.setWidths(new int[]{3, 1, 1});

        table.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);

        table.addCell("Date");
        table.addCell("Name");
        table.addCell("Service");
        table.addCell("Rate");

        table.getDefaultCell().setBackgroundColor(null);

        cell = new PdfPCell(new Phrase("Total(US$): "));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setColspan(3);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(selectedInvoice.getAmount())));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        // There are three special rows
        table.setHeaderRows(2);
        // One of them is a footer
        table.setFooterRows(1);
        Font f = FontFactory.getFont(FontFactory.HELVETICA, 10);
        //add remaining
        for (AgencyBilling billing : selectedInvoice.getBillings()) {
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.getDefaultCell().setIndent(2);
            table.getDefaultCell().setFixedHeight(20);

            table.addCell(new Phrase(DateUtility.dateFormat(billing.getBillingDate()), f));
            table.addCell(new Phrase(billing.getPerson().getName(), f));
            table.addCell(new Phrase(billing.getTariff().getTariffType().getDescription(), f));
            cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(billing.getRate()), f));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            table.addCell(cell);

        }

        pdf.add(table);

        writer.getAcroForm().setNeedAppearances(true);

        //document.add(new Phrase(TEXT));
        //Keep modifying your pdf file (add pages and more)
        pdf.close();

        writePDFToResponse(context.getExternalContext(), baos, fileName);

        context.responseComplete();

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

From source file:com.pureinfo.srm.patent.action.PatentPrintPdfAction.java

License:Open Source License

/**
 * @see com.pureinfo.ark.interaction.ActionBase#executeAction()
 *///from w  w  w .  j a  va  2 s.c om
public ActionForward executeAction() throws PureException {
    int nYear = request.getRequiredInt("year", "");

    Rectangle rectPageSize = new Rectangle(PageSize.A4);
    rectPageSize.setBackgroundColor(Color.WHITE);
    rectPageSize.setBorderColor(Color.BLACK);
    rectPageSize = rectPageSize.rotate();
    Document doc = new Document(rectPageSize, 10, 10, 10, 10);
    doc.addTitle(nYear + "");
    doc.addAuthor("PureInfo");
    try {
        BaseFont bfontTitle = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontTitle = new Font(bfontTitle, 18, Font.NORMAL);
        Paragraph paraTitle = new Paragraph(nYear + "",
                fontTitle);
        paraTitle.setAlignment(ElementTags.ALIGN_CENTER);

        BaseFont bfontContent = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontContent = new Font(bfontContent, 10, Font.NORMAL);

        FileFactory fileFactory = FileFactory.getInstance();
        String sPath = fileFactory.lookupPathConfigByFlag(FileFactory.FLAG_DOWNLOADTEMP, true).getLocalPath();

        FileUtil.insurePathExists(sPath);
        PdfWriter.getInstance(doc, new FileOutputStream(new File(sPath, "patent.pdf")));

        doc.open();
        doc.add(paraTitle);
        doc.add(new Paragraph("   "));

        String[] arrTitles = new String[] { "", "", "", "", "", "",
                "", "", "" };
        PdfPTable pTable = new PdfPTable(arrTitles.length);
        pTable.setWidths(new int[] { 5, 10, 9, 9, 20, 15, 12, 10, 10 });

        for (int i = 0; i < arrTitles.length; i++) {
            PdfPCell pCell = new PdfPCell();
            Paragraph para = new Paragraph(arrTitles[i], fontContent);
            para.setAlignment(ElementTags.ALIGN_CENTER);

            pCell.addElement(para);
            pTable.addCell(pCell);
        }

        /**
         * 
         */
        IPatentMgr mgr = (IPatentMgr) ArkContentHelper.getContentMgrOf(Patent.class);
        List patents = mgr.findAllAuthorizedOf(nYear);
        int i = 0;
        for (Iterator iter = patents.iterator(); iter.hasNext(); i++) {
            Patent patent = (Patent) iter.next();
            this.addPatentCell(pTable, String.valueOf(i + 1), fontContent);
            this.addPatentCell(pTable, patent.getPatentSid(), fontContent);
            this.addPatentCell(pTable, ForceConstants.DATE_FORMAT.format(patent.getApplyDate()), fontContent);
            this.addPatentCell(pTable, patent.getWarrantDate() == null ? ""
                    : ForceConstants.DATE_FORMAT.format(patent.getWarrantDate()), fontContent);
            this.addPatentCell(pTable, patent.getName(), fontContent);
            this.addPatentCell(pTable, patent.getAllAuthosName(), fontContent);
            this.addPatentCell(pTable, patent.getRightPerson(), fontContent);
            this.addPatentCell(pTable, getCollegeName(patent), fontContent);
            this.addPatentCell(pTable, patent.getPatentTypeName(), fontContent);
        }

        doc.add(pTable);
        doc.close();

    } catch (DocumentException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace(System.err);
    } catch (IOException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace(System.err);
    }

    List list = new ArrayList();
    list.add(new Pair("/download/patent.pdf", ""));
    request.setAttribute("forward", list);
    return mapping.findForward("success");
}

From source file:com.qcadoo.mes.workPlans.controller.WorkPlansController.java

License:Open Source License

private void printImageToPdf(final Entity attachment, HttpServletResponse response) {
    Document document = new Document();
    try {//from  w ww. j  a v  a  2 s . c o  m
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();

        document.setPageSize(PageSize.A4);
        pdfHelper.addMetaData(document);
        pdfHelper.addImage(document, attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT));
        document.close();
    } catch (Exception e) {
        LOG.error("Problem with printing document - " + e.getMessage());
        document.close();
        e.printStackTrace();
    }

}