Example usage for com.lowagie.text.pdf BaseFont HELVETICA

List of usage examples for com.lowagie.text.pdf BaseFont HELVETICA

Introduction

In this page you can find the example usage for com.lowagie.text.pdf BaseFont HELVETICA.

Prototype

String HELVETICA

To view the source code for com.lowagie.text.pdf BaseFont HELVETICA.

Click Source Link

Document

This is a possible value of a base 14 type 1 font

Usage

From source file:com.moss.pdf.template.core.Renderer.java

License:Open Source License

public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception {

    PdfReader reader = new PdfReader(in);

    Document document = new Document(reader.getPageSizeWithRotation(1));

    PdfWriter writer = PdfWriter.getInstance(document, out);

    document.open();/*from   w w  w. ja  v  a  2 s.com*/

    for (int i = 1; i <= reader.getNumberOfPages(); i++) {

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage customPage = writer.getImportedPage(reader, i);

        /*
         * add the page to our new document, turning this page to its 
         * original rotation
         */
        int pageRotation = reader.getPageRotation(i);

        if (pageRotation > 0) {

            System.out.println("page rotation found: " + pageRotation);

            double angle = -((2 * Math.PI) * pageRotation / 360);
            //         double angle = -(Math.PI / 2);

            cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle),
                    (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x
                    document.top() + document.topMargin() // y
            );
        } else {
            cb.addTemplate(customPage, 0f, 0f);
        }

        Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>();

        for (PropertyMapping field : fields) {

            if (field.getPageNumber() != i) {
                continue;
            }

            /*
             * Only builtin fonts are supported at the moment
             */
            BaseFont font;
            int fontSize;
            int alignment;
            String text;
            float x, y;
            float rotation;

            {
                font = fonts.get(field.getFontName());

                if (font == null) {

                    FontName e = field.getFontName();
                    String name = null;

                    if (FontName.COURIER == e) {
                        name = BaseFont.COURIER;
                    } else if (FontName.COURIER_BOLD == e) {
                        name = BaseFont.COURIER_BOLD;
                    } else if (FontName.COURIER_BOLD_OBLIQUE == e) {
                        name = BaseFont.COURIER_BOLDOBLIQUE;
                    } else if (FontName.COURIER_OBLIQUE == e) {
                        name = BaseFont.COURIER_OBLIQUE;
                    } else if (FontName.HELVETICA == e) {
                        name = BaseFont.HELVETICA;
                    } else if (FontName.HELVETICA_BOLD == e) {
                        name = BaseFont.HELVETICA_BOLD;
                    } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_BOLDOBLIQUE;
                    } else if (FontName.HELVETICA_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_OBLIQUE;
                    } else if (FontName.TIMES_BOLD == e) {
                        name = BaseFont.TIMES_BOLD;
                    } else if (FontName.TIMES_BOLD_ITALIC == e) {
                        name = BaseFont.TIMES_BOLDITALIC;
                    } else if (FontName.TIMES_ITALIC == e) {
                        name = BaseFont.TIMES_ITALIC;
                    } else if (FontName.TIMES_ROMAN == e) {
                        name = BaseFont.TIMES_ROMAN;
                    }

                    if (name == null) {
                        throw new RuntimeException("Unknown font type: " + e);
                    }

                    font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                    fonts.put(field.getFontName(), font);
                }

                fontSize = field.getFontSize();

                if (TextAlignment.LEFT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_LEFT;
                } else if (TextAlignment.CENTER == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_CENTER;
                } else if (TextAlignment.RIGHT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_RIGHT;
                } else {
                    alignment = PdfContentByte.ALIGN_LEFT;
                }

                Object value = p.eval(field.getExpr());

                if (value == null) {
                    text = "";
                } else {
                    text = value.toString();
                }

                x = field.getX() * POINTS_IN_A_CM;
                y = field.getY() * POINTS_IN_A_CM;

                rotation = 0;
            }

            cb.beginText();

            cb.setFontAndSize(font, fontSize);

            cb.showTextAligned(alignment, text, x, y, rotation);

            cb.endText();
        }

        document.newPage();
    }

    reader.close();
    document.close();
}

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

License:Open Source License

/**
 * Obtain base font for PDF processing/*from   w  w  w  .  j  a  va 2s . c  o m*/
 */
private static BaseFont getBaseFont() throws DocumentException, IOException {
    String fontName = Config.HOME_DIR + "/lib/unicode.ttf";
    String fontEncoding = BaseFont.IDENTITY_H;

    if (!new File(fontName).exists()) {
        log.warn("Unicode TTF font not found: {}", fontName);
        fontName = BaseFont.HELVETICA;
        fontEncoding = BaseFont.WINANSI;
    }

    return BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED);
}

From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java

License:Apache License

/**
 * Adds a text in the given pdf file./*w  ww . jav a  2 s .c  o  m*/
 * @param pdfFileName
 * @param text
 * @param x
 * @param y
 * @param rotation
 * @param page
 * @throws Exception
 */
public void addText(String pdfFileName, String text, int x, int y, int rotation, int page) throws Exception {
    // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java
    // 1. copy
    File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf");
    copyFile(new File(pdfFileName), tmpPDFFile);
    // 2. add text
    // we create a reader for a certain document
    PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath());
    // we create a stamper that will copy the document to a new file
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName));
    // adding content to each page
    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
    over = stamp.getOverContent(page);
    over.beginText();
    over.setFontAndSize(bf, 32);
    over.setTextMatrix(30, 30);
    over.setColorFill(java.awt.Color.RED);
    over.showTextAligned(Element.ALIGN_LEFT, text, x, y, rotation);
    over.endText();
    // closing PdfStamper will generate the new PDF file
    stamp.close();
}

From source file:com.qcadoo.report.api.FontUtils.java

License:Open Source License

/**
 * Prepare fonts.//from   www. java  2 s. com
 * 
 * @throws DocumentException
 * @throws IOException
 */
public static synchronized void prepare() throws DocumentException, IOException {
    if (dejavuBold10Dark == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Pdf fonts initialization");
        }
        try {
            FontFactory.register("/fonts/dejaVu/DejaVuSans.ttf");
            dejavu = BaseFont.createFont("/fonts/dejaVu/DejaVuSans.ttf", BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
        } catch (ExceptionConverter e) {
            LOG.warn("Font not found, using embedded font helvetica");
            dejavu = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        }
        dejavuBold70Light = new Font(dejavu, 70);
        dejavuBold70Light.setStyle(Font.BOLD);
        dejavuBold70Light.setColor(ColorUtils.getLightColor());

        dejavuBold70Dark = new Font(dejavu, 70);
        dejavuBold70Dark.setStyle(Font.BOLD);
        dejavuBold70Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold19Light = new Font(dejavu, 19);
        dejavuBold19Light.setStyle(Font.BOLD);
        dejavuBold19Light.setColor(ColorUtils.getLightColor());

        dejavuBold19Dark = new Font(dejavu, 19);
        dejavuBold19Dark.setStyle(Font.BOLD);
        dejavuBold19Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold14Dark = new Font(dejavu, 14);
        dejavuBold14Dark.setStyle(Font.BOLD);
        dejavuBold14Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold17Light = new Font(dejavu, 17);
        dejavuBold17Light.setStyle(Font.BOLD);
        dejavuBold17Light.setColor(ColorUtils.getLightColor());

        dejavuBold14Light = new Font(dejavu, 17);
        dejavuBold14Light.setStyle(Font.BOLD);
        dejavuBold14Light.setColor(ColorUtils.getLightColor());

        dejavuBold17Dark = new Font(dejavu, 17);
        dejavuBold17Dark.setStyle(Font.BOLD);
        dejavuBold17Dark.setColor(ColorUtils.getDarkColor());

        dejavuRegular9Light = new Font(dejavu, 9);
        dejavuRegular9Light.setColor(ColorUtils.getLightColor());

        dejavuRegular9Dark = new Font(dejavu, 9);
        dejavuRegular9Dark.setColor(ColorUtils.getDarkColor());

        dejavuRegular7Dark = new Font(dejavu, 7);
        dejavuRegular7Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold9Dark = new Font(dejavu, 9);
        dejavuBold9Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold9Dark.setStyle(Font.BOLD);

        dejavuBold11Dark = new Font(dejavu, 11);
        dejavuBold11Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold11Dark.setStyle(Font.BOLD);

        dejavuBold11Light = new Font(dejavu, 11);
        dejavuBold11Light.setColor(ColorUtils.getLightColor());
        dejavuBold11Light.setStyle(Font.BOLD);

        dejavuRegular10Dark = new Font(dejavu, 10);
        dejavuRegular10Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold10Dark = new Font(dejavu, 10);
        dejavuBold10Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold10Dark.setStyle(Font.BOLD);

        dejavuRegular7Light = new Font(dejavu, 7);
        dejavuRegular7Light.setColor(ColorUtils.getLightColor());

        dejavuBold7Dark = new Font(dejavu, 7);
        dejavuBold7Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold7Dark.setStyle(Font.BOLD);

        dejavuBold8Dark = new Font(dejavu, 8);
        dejavuBold8Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold8Dark.setStyle(Font.BOLD);

    }
}

From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java

License:Open Source License

/**
 * Add pages numbers to a PDF//w  w  w  .  ja  va2 s .  c  o  m
 *
 * @author Scott Buttler
 * Adapted from the PDF Pro plugin with full approval from the author
 *
 * @sample
 * // Add pages numbers to a PDF
 * var unNumberedFile = plugins.file.showFileOpenDialog();
 * if (unNumberedFile) {
 *    var data = plugins.file.readFile(unNumberedFile);
 *    pageNumberedPdf = %%elementName%%.numberPages(data, 12, 520, 30, 'Courier', '#ff0033');
 * }
 *
 * @param data the PDF
 *
 * @return the PDF with numbered pages
 *
 * @throws Exception
 */
public byte[] js_numberPages(byte[] data) throws Exception {
    return js_numberPages(data, 10, 520, 30, BaseFont.HELVETICA, "#000000"); //$NON-NLS-1$
}

From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java

License:Open Source License

/**
 * Add text over every page at a 45 degree angle
 *
 * @author Scott Buttler/*from w w w  .j a  v  a 2  s .c o  m*/
 * Adapted from the PDF Pro plugin with full approval from the author
 *
 * @sample
 * // Add text over every page at a 45 degree angle\m
 * var pdf = plugins.file.showFileOpenDialog();
 * if (pdf) {
 *    var data = plugins.file.readFile(pdf);
 *    modifiedPdf = %%elementName%%.overlayText(data, 'DRAFT', 230, 430, true, 32, 'Helvetica', '#33ff33');
 * }
 *
 * @param data the PDF
 * @param text the text to use for the overlay
 *
 * @return the PDF with added overlay
 *
 * @throws Exception
 */
public byte[] js_overlayText(byte[] data, String text) throws Exception {
    return js_overlayText(data, text, 230, 430, true, 32, BaseFont.HELVETICA, "#000000"); //$NON-NLS-1$
}

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

License:Open Source License

/**
 * Create a PDF file based on the contents of the graph
 *///  w  ww  .j a va2  s. c o  m
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.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file.// w  w  w  .ja v  a 2  s.  c  o m
 *
 * @param streamOfPDFFiles - a list of inputStreams
 * @param outputStream - an instance of outputStream
 * @param paginate - a boolean
 * @throws AkuraAppException - The exception details that occurred when processing
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate)
        throws AkuraAppException {

    final int fontSize = 8, leftRightAlignment = 8;
    final int min = 0;
    final int max = 5;
    final int size = 300;
    final int xAxis = -150;
    final int pageHeight = 550;
    final int pageHieghtfromBottom = 16;
    final int pageRecHeight = 580;
    final int recHeightFromBottom = 14;
    Document document = new Document(PageSize.A4);
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the output stream
        PdfWriter writer = null;
        BaseFont bf = null;
        try {
            writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                if (currentPageNumber != 2) {
                    document.newPage();
                }
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                if (currentPageNumber == 1) {
                    cb.addTemplate(page, 0, xAxis);
                } else if (currentPageNumber != 2) {
                    cb.addTemplate(page, 0, 0);
                }

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, fontSize);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size,
                            max, min);
                    cb.newlineText();
                    cb.endText();

                    if (currentPageNumber != 2) {
                        int pageNo = currentPageNumber;
                        if (currentPageNumber != 1) {
                            pageNo = currentPageNumber - 1;
                        }

                        // write the page number inside a rectangle.
                        cb.fillStroke();
                        cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight,
                                leftRightAlignment);
                        cb.beginText();
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight,
                                pageHieghtfromBottom, 0);
                        cb.endText();
                        cb.stroke();
                    }
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();

        document.close();

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java

License:Open Source License

/**
 * This method is called by the struts-framework if the submit-button is pressed.
 * It creates a PDF-File and puts in into the output-stream of the response.
 *//*from   w  ww  .  ja v a  2 s  .  c o  m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CreateSubscriberListForm myForm = (CreateSubscriberListForm) form;
    boolean bSortByName;

    if (myForm.getSortBy().equals(myForm.SORTBYPN))
        bSortByName = false;
    else
        bSortByName = true;

    //create Collection for the results...
    Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID());
    Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList());
    Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID());

    Iterator cSubscriberListIT = cSubscriberList.iterator();
    Collection cSubscriberResultList = new ArrayList();

    while (cSubscriberListIT.hasNext()) {
        User CurUser = (User) cSubscriberListIT.next();
        String UserPNR = CurUser.getPersonalNumber();

        Iterator cExamResultsIT = cExamResults.iterator();
        ExamResult curExamResult = null;
        String ResultUserPNR = null;
        while (cExamResultsIT.hasNext()) {
            curExamResult = (ExamResult) cExamResultsIT.next();

            ResultUserPNR = curExamResult.getUserPersonalNumber();
            if (UserPNR.equals(ResultUserPNR))
                break;
        }

        if (UserPNR.equals(ResultUserPNR)) {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser,
                        "" + curExamResult.getResult());
                cSubscriberResultList.add(URS);
            }
        } else {
            if (bSortByName) {
                UserResultSortByName URS = new UserResultSortByName(CurUser, "-");
                cSubscriberResultList.add(URS);
            } else {
                UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-");
                cSubscriberResultList.add(URS);
            }
        }

    }

    //sort List
    Collections.sort((List) cSubscriberResultList);

    BaseFont bf;
    //36pt = 0.5inch
    Document document = new Document(PageSize.A4, 36, 36, 72, 72);

    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e);
        //2do: add ErrorMessage and return to inputFormular!
        return mapping.findForward("GeneralFailure");
    }

    //calculate the number of cols and their width
    int cols = 0;
    ArrayList alWidth = new ArrayList();
    float boldItalicFactor = 1.2f;
    if (myForm.getShowNumber())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowPersonalNumber())
        alWidth.add(new Float(
                boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowName())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowEmail())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE)));

    if (myForm.getShowResult())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddInfoField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE)));

    if (myForm.getAddSignField())
        alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE)));

    cols = alWidth.size();

    float totalWidth = 0;
    //calculate the whole length
    Iterator alIterator = alWidth.iterator();
    for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue())
        ;

    //calculate relativ width for the table
    float[] width = new float[cols];
    alIterator = alWidth.iterator();
    int i = 0;
    while (alIterator.hasNext()) {
        float pixLength = ((Float) alIterator.next()).floatValue();
        //alWidthRelativ.add( new Float( pixLength/totalWidth ) );
        width[i] = pixLength / totalWidth;
        i++;
    }

    //needed for the shrink (enlarge?)
    float shrinkFactor;

    try {
        //1st: set correct outputstream
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

        //1.5st: set content-stuff
        response.setContentType("application/pdf");

        //2nd: set EventManager for PageEvents to Helper
        writer.setPageEvent(
                new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight()));

        //3rd: open document for editing the content
        document.open();

        //4th: add content
        Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD));
        document.add(pInfoText);

        //PdfPTable( cols )
        PdfPTable table = new PdfPTable(width);

        float documentWidth = document.right() - document.left();
        if (documentWidth < totalWidth) {
            table.setTotalWidth(documentWidth);
            shrinkFactor = documentWidth / totalWidth;
        } else {
            table.setTotalWidth(totalWidth);
            shrinkFactor = 1;
        }
        table.setLockedWidth(true);

        Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC);
        Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL);

        if (myForm.getShowNumber())
            table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont));
        if (myForm.getShowPersonalNumber())
            table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont));
        if (myForm.getShowName())
            table.addCell(new Phrase(TABLEHEADER_NAME, headerFont));
        if (myForm.getShowEmail())
            table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont));
        if (myForm.getShowResult())
            table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont));
        if (myForm.getAddInfoField())
            table.addCell(new Phrase(TABLEHEADER_INFO, headerFont));
        if (myForm.getAddSignField())
            table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont));

        //fill table
        Iterator iSRL = cSubscriberResultList.iterator();
        int counter = 1;
        while (iSRL.hasNext()) {
            UserResult curResult = (UserResult) iSRL.next();

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            if (myForm.getShowNumber())
                table.addCell(new Phrase("" + counter++, cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            if (myForm.getShowPersonalNumber())
                table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont));

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            if (myForm.getShowName())
                table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont));
            if (myForm.getShowEmail())
                table.addCell(new Phrase(curResult.getEmailAddress(), cellFont));
            if (myForm.getShowResult())
                table.addCell(new Phrase(curResult.getResult(), cellFont));
            if (myForm.getAddInfoField())
                table.addCell(new Phrase("", cellFont));
            if (myForm.getAddSignField())
                table.addCell(new Phrase("", cellFont));
        }

        //set how many rows are header...
        table.setHeaderRows(1);

        document.add(table);

        //5th: close document, write the output to the stream...
        document.close();
    } catch (Exception de) {
        Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de);
    }

    //we dont need to return a forward, because we write directly to the outputstream!
    return null;
}

From source file:de.tr1.cooperator.manager.web.CreateSubscriberListActionHelper.java

License:Open Source License

/**
 * The first thing to do when the document is opened, is to define the BaseFont,
 * get the Direct Content object and create the template that will hold the final
 * number of pages./*from   w  w  w.  ja  v  a  2s. c  o  m*/
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb = writer.getDirectContent();

        // initialization of the header table
        tHeader = new PdfPTable(2);
        Phrase p = new Phrase();

        tHeader.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        tHeader.addCell(sHeaderLeft);

        tHeader.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        tHeader.addCell(sHeaderRight);

        template = cb.createTemplate(50, 50);
    } catch (DocumentException de) {
    } catch (IOException ioe) {
    }
}