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

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

Introduction

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

Prototype

public void setStrictImageSequence(boolean strictImageSequence) 

Source Link

Document

Use this method to set the image sequence, so that it follows the text in strict order (or not).

Usage

From source file:knop.psfj.exporter.PDFExporter.java

License:Open Source License

/**
 * Fill report.//w  w  w.  j a  va 2 s  .  com
 *
 * @param report the report
 * @param writer the writer
 * @param bead the bead
 * @param id the id
 */
public static void fillReport(Document report, PdfWriter writer, BeadFrame bead, int id) {

    Microscope microscope = bead.getSource().getMicroscope();
    ReportSections rs = new ReportSections();

    writer.setStrictImageSequence(true);

    try {
        /*
         * report.add(rs.bigTitle("Bead " + id));
         * report.add(rs.littleNote(microscope.date)); /*
         * report.add(rs.title("Profile view:")); ImagePlus img; try { img =
         * svg.getPanelView(pp.getImagePlus(), SideViewGenerator.MAX_METHOD,
         * true, true, 5, false, null, 0); } catch (NullPointerException e)
         * { e.printStackTrace(); return; } float zoom2scaleTo256pxMax =
         * 25600 / Math.max(img.getWidth(), img.getHeight());
         * report.add(rs.imagePlus(img, zoom2scaleTo256pxMax));
         * 
         * report.add(rs.title("Microscope infos:"));
         * report.add(rs.paragraph(microscope.getMicroscopeHeader()));
         */

        id = bead.getId();
        String suffix = "";
        if (bead.isValid() == false)
            suffix = " (Rejected)";

        if (bead.isValid() && bead.getInvalidityReason() != null) {
            suffix = " (Rejected from the pair analysis)";
        }

        // Image logo = loadImage("knoplablogo.png");

        // report.add();
        // currentDocument.add(rs.littleNote(FileUtils.getTodayDate()));

        double[] resolutions = bead.getResolutions();

        // the resolutions extracted from the Bead Spread function are
        // assigned to
        // individual variables
        String resolutionX = microscope.formatDouble(bead.getResolution(0));
        String resolutionY = microscope.formatDouble(bead.getResolution(1));
        String resolutionZ = microscope.formatDouble(bead.getResolution(2));

        // the corrected resolution are calculated by the Microscope Object
        // (it holds
        // all the experiment data).
        String correctedResolutionX = microscope.formatDouble(bead.getCorrectionResolution(Microscope.X));
        String correctedResolutionY = microscope.formatDouble(bead.getCorrectionResolution(Microscope.Y));
        String correctedResolutionZ = microscope.formatDouble(bead.getCorrectionResolution(Microscope.Z));

        String asymmetry = MathUtils.roundToString(bead.getAsymetry(), 3);

        String theta = MathUtils.roundToString(bead.getThetaInDegrees(), 1) + MathUtils.DEGREE_SYMBOL;

        String[][] content = { { "FWHM", "min", "max", "z", "Asymmetry", "Theta" },
                { "Non corrected", resolutionX, resolutionY, resolutionZ, asymmetry, theta },

                { "Corrected", correctedResolutionX, correctedResolutionY, correctedResolutionZ, "", ""

                },
                { "Theoretical", microscope.formatDouble(microscope.getXYTheoreticalResolution()),
                        microscope.formatDouble(microscope.getXYTheoreticalResolution()),
                        microscope.formatDouble(microscope.getZTheoreticalResolution()), "", "" } };

        Paragraph header = new Paragraph();

        Image sideView = rs.imagePlus(bead.getSideViewImage(), 100);
        sideView.setAlignment(Image.ALIGN_RIGHT | Image.TEXTWRAP);
        report.add(sideView);
        String microscopeId = bead.getSource().getMicroscope().getIdentifier();
        if (microscopeId.equals("") == false)
            microscopeId = String.format(" ( %s )", microscopeId);
        String date = "Date : " + FileUtils.getTodayDate();
        String origin = String.format("\n Origin : %s %s\n Frame size : %d pixels\n",
                bead.getSource().getImageName(), microscopeId, bead.getWidth());
        String shift;
        String correspondingBead = "\nCorresponding bead : " + ((bead.getAlterEgo() == null) ? "Not found"
                : "Number " + bead.getAlterEgo().getId() + " in "
                        + bead.getAlterEgo().getSource().getImageName());
        String coordinates = "\nCoordinates : " + microscope.formatDouble(bead.getFovX()) + " (x), "
                + microscope.formatDouble(bead.getFovY()) + " (y), "
                + microscope.formatDouble(bead.getCentroidZ() * microscope.getCalibration().pixelDepth)
                + " (z)";
        String rejectionReason = (bead.getInvalidityReason() == null ? ""
                : "\nReason of rejection : " + bead.getInvalidityReason());

        if (bead.getAlterEgo() != null) {
            shift = "\nShift : ";
            shift += microscope.formatDouble(bead.getDeltaX());
            shift += " x " + microscope.formatDouble(bead.getDeltaY());
            shift += " x " + microscope.formatDouble(bead.getDeltaZ());
        } else {
            shift = "";
        }

        report.add(rs.title("Bead " + id + suffix));
        report.add(rs.paragraph(date + origin + coordinates + correspondingBead + shift + rejectionReason));
        // report.add(rs.subtitle("Resolution table:"));

        report.add(rs.table(content, 100));

        int height = 130;

        ImagePlus xPlot;
        ImagePlus yPlot;

        if (bead instanceof BeadFrame2D) {
            BeadFrame2D bead2D = (BeadFrame2D) bead;
            xPlot = new ImagePlus("", bead2D.getOverlayWithTheoretical());
            yPlot = xPlot;
            report.add(rs.subtitle("XY profile & fitting parameters : "));
            report.add(rs.littleNote("(red : the orignal data, green : the fit, yellow : the two merged)",
                    Paragraph.ALIGN_LEFT));

        } else {
            xPlot = bead.getXplot().getImagePlus();
            yPlot = bead.getYplot().getImagePlus();
            report.add(rs.subtitle("X profile & fitting parameters:"));
        }

        Image image = rs.imagePlus(xPlot, height);
        image.setAlignment(Image.ALIGN_LEFT | Image.TEXTWRAP);
        report.add(image);
        report.add(rs.paragraph(bead.getXParams()));

        if (bead instanceof BeadFrame2D == false) {
            report.add(rs.subtitle("Y profile & fitting parameters:"));
            image = rs.imagePlus(yPlot, height);
            image.setAlignment(Image.ALIGN_LEFT | Image.TEXTWRAP);
            report.add(image);
            report.add(rs.paragraph(bead.getYParams()));
        }
        report.add(rs.subtitle("Z profile & fitting parameters:"));
        image = rs.imagePlus(bead.getZplot().getImagePlus(), height);
        image.setAlignment(Image.ALIGN_LEFT | Image.TEXTWRAP);
        report.add(image);
        report.add(rs.paragraph(bead.getZParams()));

        if (!microscope.sampleInfos.equals("") || !microscope.comments.equals(""))
            report.newPage();

        if (!microscope.sampleInfos.equals("")) {
            report.add(rs.title("Sample infos:"));
            report.add(rs.paragraph(microscope.sampleInfos));
        }

        if (!microscope.comments.equals("")) {
            report.add(rs.title("Comments:"));
            report.add(rs.paragraph(microscope.comments));
        }

        // logo.setAlignment(Image.ALIGN_RIGHT | Image.TEXTWRAP);
        // logo.scalePercent(10);

        // currentDocument.add(logo);

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

    System.gc();

}

From source file:org.oscarehr.web.reports.ocan.IndividualNeedRatingOverTimeReportGenerator.java

License:Open Source License

public void generateReport(OutputStream os) throws Exception {
    Document d = new Document(PageSize.A4.rotate());
    d.setMargins(20, 20, 20, 20);//from www. j  av a  2  s  .  co  m
    PdfWriter writer = PdfWriter.getInstance(d, os);
    writer.setStrictImageSequence(true);
    d.open();

    //header
    Paragraph p = new Paragraph("Individual Need Rating Over Time", titleFont);
    p.setAlignment(Element.ALIGN_CENTER);
    d.add(p);
    d.add(Chunk.NEWLINE);

    //purpose
    Paragraph purpose = new Paragraph();
    purpose.add(new Chunk("Purpose of Report:", boldText));
    purpose.add(new Phrase(
            "The purpose of this report is to show change over time in a specific Need Rating for an individual Consumer. It adds up the number of needs across all Domains grouped by Need Rating (e.g. Unmet Needs, Met Needs, No Needs, Unknown) for all selected OCANs that were conducted with the Consumer and displays the results in an individual need rating line graph. Each line graph that is displayed compares the Consumer and the Staff's perspective. The staff may share this report with their Consumer as well.",
            normalText));
    d.add(purpose);
    d.add(Chunk.NEWLINE);

    //report parameters
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(makeCell(createFieldNameAndValuePhrase("Consumer Name:", reportBean.getConsumerName()),
            Element.ALIGN_LEFT));
    table.addCell(makeCell(
            createFieldNameAndValuePhrase("Report Date:", dateFormatter.format(reportBean.getReportDate())),
            Element.ALIGN_RIGHT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Staff Name:", reportBean.getStaffName()),
            Element.ALIGN_LEFT));
    table.addCell("");
    d.add(table);
    d.add(Chunk.NEWLINE);

    int height = 260;

    if (reportBean.isShowUnmetNeeds()) {
        d.add(Image.getInstance(reportBean.getUnmetNeedsChart()
                .createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, height), null));
    }

    if (reportBean.isShowMetNeeds()) {
        d.add(Image.getInstance(reportBean.getMetNeedsChart()
                .createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, height), null));
    }

    if (reportBean.isShowNoNeeds()) {
        d.add(Image.getInstance(reportBean.getNoNeedsChart()
                .createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, height), null));
    }
    if (reportBean.isShowUnknownNeeds()) {
        d.add(Image.getInstance(reportBean.getUnknownNeedsChart()
                .createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, height), null));
    }

    d.close();
}

From source file:org.oscarehr.web.reports.ocan.NeedRatingOverTimeReportGenerator.java

License:Open Source License

public void generateReport(OutputStream os) throws Exception {
    Document d = new Document(PageSize.A4.rotate());
    d.setMargins(20, 20, 20, 20);//  ww w  .j  a v a  2 s  .  com
    PdfWriter writer = PdfWriter.getInstance(d, os);
    writer.setStrictImageSequence(true);
    d.open();

    //header
    Paragraph p = new Paragraph("Needs Over Time (Consumer and Staff)", titleFont);
    p.setAlignment(Element.ALIGN_CENTER);
    d.add(p);
    d.add(Chunk.NEWLINE);

    //purpose
    Paragraph purpose = new Paragraph();
    purpose.add(new Chunk("Purpose of Report:", boldText));
    purpose.add(new Phrase(
            "The purpose of this report is to show change over time in a specific Need Rating for an individual Consumer. It adds up the number of needs across all Domains grouped by Need Rating (e.g. Unmet Needs, Met Needs, No Needs, Unknown) for all selected OCANs that were conducted with the Consumer and displays the results in an individual need rating line graph. Each line graph that is displayed compares the Consumer and the Staff's perspective. The staff may share this report with their Consumer as well.",
            normalText));
    d.add(purpose);
    d.add(Chunk.NEWLINE);

    //report parameters
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(
            makeCell(createFieldNameAndValuePhrase("Consumer Name:", getConsumerName()), Element.ALIGN_LEFT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Report Date:", dateFormatter.format(getReportDate())),
            Element.ALIGN_RIGHT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Staff Name:", getStaffName()), Element.ALIGN_LEFT));
    table.addCell("");
    d.add(table);
    d.add(Chunk.NEWLINE);

    //loop here...groups of 3
    int loopNo = 1;
    List<OcanNeedRatingOverTimeSummaryOfNeedsBean> summaryBeanList = new ArrayList<OcanNeedRatingOverTimeSummaryOfNeedsBean>();
    summaryBeanList.addAll(this.summaryOfNeedsBeanList);

    while (true) {
        if (summaryBeanList.size() == 0) {
            break;
        }
        List<OcanNeedRatingOverTimeSummaryOfNeedsBean> currentBeanList = new ArrayList<OcanNeedRatingOverTimeSummaryOfNeedsBean>();
        for (int x = 0; x < 3; x++) {
            if (summaryBeanList.size() == 0) {
                break;
            }
            currentBeanList.add(summaryBeanList.remove(0));
        }

        //summary of needs
        PdfPTable summaryOfNeedsTable = null;
        if (currentBeanList.size() == 1) {
            summaryOfNeedsTable = new PdfPTable(3);
            summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
            summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f });
        }
        if (currentBeanList.size() == 2) {
            summaryOfNeedsTable = new PdfPTable(6);
            summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
            summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
        }
        if (currentBeanList.size() == 3) {
            summaryOfNeedsTable = new PdfPTable(9);
            summaryOfNeedsTable.setWidthPercentage(100f);
            summaryOfNeedsTable
                    .setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
        }
        summaryOfNeedsTable.setHorizontalAlignment(Element.ALIGN_LEFT);
        summaryOfNeedsTable.setHeaderRows(3);

        addSummaryOfNeedsHeader(summaryOfNeedsTable, currentBeanList, loopNo);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Unmet Needs", "unmet", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Met Needs", "met", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "No Needs", "no", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Unknown Needs", "unknown", currentBeanList);

        d.add(summaryOfNeedsTable);
        d.add(Chunk.NEWLINE);

        if (summaryBeanList.size() == 0) {
            break;
        }
        loopNo++;
    }

    //BREAKDOWN OF SUMMARY OF NEEDS

    //loop here...groups of 3
    loopNo = 1;
    List<OcanNeedRatingOverTimeNeedBreakdownBean> breakdownBeanList = new ArrayList<OcanNeedRatingOverTimeNeedBreakdownBean>();
    breakdownBeanList.addAll(this.needBreakdownListByOCAN);
    OcanNeedRatingOverTimeNeedBreakdownBean lastBreakDownBean = null;
    while (true) {
        if (breakdownBeanList.size() == 0) {
            break;
        }
        List<OcanNeedRatingOverTimeNeedBreakdownBean> currentBeanList = new ArrayList<OcanNeedRatingOverTimeNeedBreakdownBean>();
        for (int x = 0; x < 3; x++) {
            if (breakdownBeanList.size() == 0) {
                break;
            }
            currentBeanList.add(breakdownBeanList.remove(0));
        }

        //summary of needs
        PdfPTable summaryOfNeedsTable = null;
        if (currentBeanList.size() == 1) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(3);
                summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(4);
                summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f });
            }
        }
        if (currentBeanList.size() == 2) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(6);
                summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(7);
                summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
                summaryOfNeedsTable
                        .setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            }
        }
        if (currentBeanList.size() == 3) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(9);
                summaryOfNeedsTable.setWidthPercentage(100f);
                summaryOfNeedsTable.setWidths(
                        new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(10);
                summaryOfNeedsTable.setWidthPercentage(100f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f,
                        0.12f, 0.024f, 0.12f, 0.12f });
            }
        }
        summaryOfNeedsTable.setHorizontalAlignment(Element.ALIGN_LEFT);

        addSummaryOfNeedsDomainHeader(summaryOfNeedsTable, currentBeanList, loopNo);
        for (int x = 0; x < domains.size(); x++) {
            addSummaryOfNeedsDomainRow(summaryOfNeedsTable, x, getDomains(), currentBeanList,
                    lastBreakDownBean);
        }

        d.add(summaryOfNeedsTable);
        d.add(Chunk.NEWLINE);

        if (breakdownBeanList.size() == 0) {
            break;
        }
        if (currentBeanList.size() == 3) {
            lastBreakDownBean = currentBeanList.get(2);
        }
        loopNo++;
    }

    JFreeChart chart = generateNeedsOverTimeChart();
    BufferedImage image = chart.createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, 350);
    Image image2 = Image.getInstance(image, null);
    d.add(image2);

    d.close();
}

From source file:org.oscarehr.web.reports.ocan.SummaryOfActionsAndCommentsReportGenerator.java

License:Open Source License

public void generateReport(OutputStream os) throws Exception {
    Document d = new Document(PageSize.A4.rotate());
    d.setMargins(20, 20, 20, 20);/* w  w  w  .ja  va 2s.c om*/
    PdfWriter writer = PdfWriter.getInstance(d, os);
    writer.setStrictImageSequence(true);
    d.open();

    //header
    Paragraph p = new Paragraph("Summary of Actions and Comments", titleFont);
    p.setAlignment(Element.ALIGN_CENTER);
    d.add(p);
    d.add(Chunk.NEWLINE);

    //purpose
    Paragraph purpose = new Paragraph();
    purpose.add(new Chunk("Purpose of Report:", boldText));
    purpose.add(new Phrase(
            "This report displays a summary of Actions and Comments (both for the Consumer and the Staff) that were recorded in the selected OCANs for an individual Consumer. The report lists all the Actions and Comments associated to OCANs and Domains that were chosen by the Staff to be displayed. The Actions also list who is responsible for the Action and the Review Date for the Action. The Domains are categorized by need rating within within the current OCAN as well as displaying the need ratings from the previous OCANs. In the case of different need ratings by the Consumer and the Mental Health Worker, the higher need rating determines the category. The need ratings from highest to lowest are Unmet Needs, Met Needs, No Needs, and Unknown. The need rating given by the Consumer and the Staff are also displayed next to the Comments for each OCAN. This information can be passed along to other organizations if requested.",
            normalText));
    d.add(purpose);
    d.add(Chunk.NEWLINE);

    //report parameters
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(
            makeCell(createFieldNameAndValuePhrase("Consumer Name:", getConsumerName()), Element.ALIGN_LEFT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Report Date:", dateFormatter.format(getReportDate())),
            Element.ALIGN_RIGHT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Staff Name:", getStaffName()), Element.ALIGN_LEFT));
    table.addCell("");
    d.add(table);
    d.add(Chunk.NEWLINE);

    if (reportBean == null) {
        d.close();
        return;
    }

    List<SummaryOfActionsAndCommentsDomainBean> unMetCategory = reportBean.getUnmetNeeds();
    List<SummaryOfActionsAndCommentsDomainBean> metCategory = reportBean.getMetNeeds();
    List<SummaryOfActionsAndCommentsDomainBean> noCategory = reportBean.getNoNeeds();
    List<SummaryOfActionsAndCommentsDomainBean> unknownCategory = reportBean.getUnknown();

    PdfPTable unmetTable = null;
    if (unMetCategory.size() > 0) {
        unmetTable = createNeedHeader("Unmet Needs");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : unMetCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(unmetTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(unmetTable, ocanBean);
            }
        }
    }
    if (unmetTable != null) {
        d.add(unmetTable);
        d.add(Chunk.NEWLINE);
    }

    PdfPTable metTable = null;
    if (metCategory.size() > 0) {
        metTable = createNeedHeader("Met Needs");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : metCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(metTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(metTable, ocanBean);
            }
        }
    }
    if (metTable != null) {
        d.add(metTable);
        d.add(Chunk.NEWLINE);
    }

    PdfPTable noTable = null;
    if (noCategory.size() > 0) {
        noTable = createNeedHeader("No Needs");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : noCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(noTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(noTable, ocanBean);
            }
        }
    }
    if (noTable != null) {
        d.add(noTable);
        d.add(Chunk.NEWLINE);
    }

    PdfPTable unknownTable = null;
    if (unknownCategory.size() > 0) {
        unknownTable = createNeedHeader("Unknown");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : unknownCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(unknownTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(unknownTable, ocanBean);
            }
        }
    }
    if (unknownTable != null) {
        d.add(unknownTable);
    }

    d.close();
}

From source file:org.sigmah.server.report.renderer.itext.PdfReportRenderer.java

License:Open Source License

@Override
protected DocWriter createWriter(Document document, OutputStream os) throws DocumentException {
    PdfWriter writer = PdfWriter.getInstance(document, os);
    writer.setStrictImageSequence(true);

    return writer;
}

From source file:org.sipfoundry.faxrx.FaxProcessor.java

License:Open Source License

private File tiff2Pdf(File tiffFile) {
    Pattern pattern = Pattern.compile("(.*).tiff");
    Matcher matcher = pattern.matcher(tiffFile.getName());
    boolean matchFound = matcher.find();

    // check if tiffFile is actually a TIFF file, just in case
    if (matchFound) {
        // located at default tmp-file directory
        File pdfFile = new File(System.getProperty("java.io.tmpdir"), matcher.group(1) + ".pdf");
        try {// w  w  w. j  a  v a 2  s .  co  m
            // read TIFF file
            RandomAccessFileOrArray tiff = new RandomAccessFileOrArray(tiffFile.getAbsolutePath());

            // get number of pages of TIFF file
            int pages = TiffImage.getNumberOfPages(tiff);

            // create PDF file
            Document pdf = new Document(PageSize.LETTER, 0, 0, 0, 0);

            PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(pdfFile));
            writer.setStrictImageSequence(true);

            // open PDF filex
            pdf.open();

            PdfContentByte contentByte = writer.getDirectContent();

            // write PDF file page by page
            for (int page = 1; page <= pages; page++) {
                Image temp = TiffImage.getTiffImage(tiff, page);
                temp.scalePercent(7200f / temp.getDpiX(), 7200f / temp.getDpiY());
                pdf.setPageSize(new Rectangle(temp.getScaledWidth(), temp.getScaledHeight()));
                temp.setAbsolutePosition(0, 0);
                contentByte.addImage(temp);
                pdf.newPage();
            }
            // close PDF file
            pdf.close();
        } catch (Exception e) {
            LOG.error("faxrx::tiff2Pdf error " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return pdfFile;
    }

    else {
        return null;
    }
}

From source file:org.sonarqube.report.extendedpdf.OverviewPDFReporter.java

License:Open Source License

@Override
public ByteArrayOutputStream getReport()
        throws DocumentException, IOException, org.dom4j.DocumentException, ReportException {
    // Capture and save screenshots of the required widgets
    captureScreenshots();/*from w  ww.  j  av  a  2s .  co  m*/

    // Creation of documents
    Document mainDocument = new Document(PageSize.LETTER, 50, 50, 75, 50);
    ExtendedToc tocDocument = new ExtendedToc();
    Document frontPageDocument = new Document(PageSize.LETTER, 50, 50, 75, 50);

    ByteArrayOutputStream mainDocumentBaos = new ByteArrayOutputStream();
    ByteArrayOutputStream frontPageDocumentBaos = new ByteArrayOutputStream();

    PdfWriter mainDocumentWriter = PdfWriter.getInstance(mainDocument, mainDocumentBaos);
    PdfWriter frontPageDocumentWriter = PdfWriter.getInstance(frontPageDocument, frontPageDocumentBaos);

    mainDocumentWriter.setStrictImageSequence(true);
    frontPageDocumentWriter.setStrictImageSequence(true);

    // Events for TOC, header and page numbers
    ExtendedEvents events = new ExtendedEvents(tocDocument, new ExtendedHeader(this.getProject()));
    mainDocumentWriter.setPageEvent(events);

    mainDocument.open();
    tocDocument.getTocDocument().open();
    frontPageDocument.open();

    Logger.info("Generating Overview PDF report...");
    printFrontPage(frontPageDocument, frontPageDocumentWriter);
    printTocTitle(tocDocument);
    printPdfBody(mainDocument);

    mainDocument.close();
    tocDocument.getTocDocument().close();
    frontPageDocument.close();

    // Get Readers
    PdfReader mainDocumentReader = new PdfReader(mainDocumentBaos.toByteArray());
    PdfReader tocDocumentReader = new PdfReader(tocDocument.getTocOutputStream().toByteArray());
    PdfReader frontPageDocumentReader = new PdfReader(frontPageDocumentBaos.toByteArray());

    // New document
    Document documentWithToc = new Document(tocDocumentReader.getPageSizeWithRotation(1));
    ByteArrayOutputStream finalBaos = new ByteArrayOutputStream();
    PdfCopy copy = new PdfCopy(documentWithToc, finalBaos);

    documentWithToc.open();
    copy.addPage(copy.getImportedPage(frontPageDocumentReader, 1));
    for (int i = 1; i <= tocDocumentReader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(tocDocumentReader, i));
    }
    for (int i = 1; i <= mainDocumentReader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(mainDocumentReader, i));
    }
    documentWithToc.close();

    // Return the final document (with TOC)
    return finalBaos;
}

From source file:org.tpspencer.tal.mvc.document.DocumentWriterImpl.java

License:Apache License

/**
 * Call to start a new document./*from w w w.j  ava 2s.co  m*/
 * 
 * @param fileName The filename to write into
 * @param resources The resources to output
 * @throws Exception Any IO or underlying exceptions
 */
public DocumentWriterImpl(String fileName, String resources) throws Exception {
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    writer.setStrictImageSequence(true);
    document.open();

    this.resources = ResourceBundle.getBundle(resources);
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createPresentationSlidesDeck(File file) {
    // step 1: creation of a document-object
    final Document document = new Document(PageSize.LETTER.rotate());

    try {/*from   www . jav a 2  s  .  c o m*/
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        final float pageWidth = document.getPageSize().getWidth();
        final float pageHeight = document.getPageSize().getHeight();
        final float fillWidth = pageWidth - 70;
        final float fillHeight = pageHeight - 70;

        if (DEBUG.Enabled) {
            System.out.println("\n---------------------------------");
            System.out.println("PDF DOCUMENT: pageSize " + document.getPageSize());
            System.out.println("fillWidth=" + fillWidth + " fillHeight=" + fillHeight);
        }
        int currentIndex = VUE.getActivePathway().getIndex();
        VUE.getActivePathway().setIndex(-1);
        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            if (DEBUG.Enabled)
                Log.debug("\n\nHANDLING DECK ENTRY " + entry);
            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            final PdfTemplate template = PdfTemplate.createTemplate(writer, fillWidth, fillHeight);
            final PdfGraphics2D graphics = (PdfGraphics2D) template.createGraphics(fillWidth, fillHeight,
                    getFontMapper(), false, 60.0f);
            final DrawContext dc = new DrawContext(graphics, 1.0);
            //                 //final DrawContext dc = new DrawContext(graphics, scale);
            //final DrawContext dc = new DrawContext(graphics, toDraw); // ideally, should use this
            dc.setClipOptimized(false);
            dc.setInteractive(false); // should be un-needed
            dc.setPrintQuality();

            // We set dc.focused to the node, which is needed for portals so they know to render contents in their clip-region.
            // Normally a portal knows to do this because it's the focal (dc.focal), but in this case, the dc.focal could,
            // at best, be the slide.  The current code actually uses NO focal in creating the DrawContext above,
            // and I'm not changing that just now as that would require lots of regression testing of printing.  SMF 6/24/10
            dc.focused = entry.node;

            if (DEBUG.Enabled) {
                Log.debug("DRAWING INTO " + dc + " g=" + graphics + " clip="
                        + tufts.Util.fmt(graphics.getClip()));
                if (DEBUG.PDF) {
                    dc.g.setColor(Color.green);
                    dc.g.fillRect(-Short.MAX_VALUE / 2, -Short.MAX_VALUE / 2, Short.MAX_VALUE, Short.MAX_VALUE);
                }
            }

            try {
                if (DEBUG.Enabled)
                    dc.clearDebug();
                toDraw.drawFit(dc, 0);
            } catch (Throwable t) {
                Log.error("exception drawing " + toDraw, t);
            }

            try {

                if (DEBUG.Enabled)
                    Log.debug("painted " + DrawContext.getDebug() + " to " + dc);

                if (DEBUG.PDF) {
                    final String dcDesc = dc.toString()
                            + String.format(" scale=%.1f%%", dc.g.getTransform().getScaleX() * 100);
                    dc.setRawDrawing();
                    dc.g.setColor(Color.red);
                    dc.g.setFont(VueConstants.FixedSmallFont);
                    dc.g.drawString(dcDesc, 10, fillHeight - 27);
                    dc.g.drawString(entry.toString(), 10, fillHeight - 16);
                    dc.g.drawString(toDraw.toString(), 10, fillHeight - 5);
                }

                // the graphics dispose appears to be very important -- we've seen completely intermittant
                // problems with generating many page PDF documents, which would be well explained by
                // java or internal itext buffers running out of memory.
                graphics.dispose();

                document.add(Image.getInstance(template));
                document.newPage();
            } catch (Throwable t) {
                Log.error("exception finishing " + toDraw + " in " + dc, t);
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
        if (DEBUG.Enabled)
            Log.debug("PROCESSED ALL ENTRIES");

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

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