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

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

Introduction

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

Prototype

boolean NOT_EMBEDDED

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

Click Source Link

Document

if the font doesn't have to be embedded

Usage

From source file:com.moss.check.us.CheckPdfRenderer.java

License:Open Source License

public void render(CheckModel model, OutputStream out) throws Exception {

    Document document = new Document();
    document.setPageSize(new Rectangle(PAGE_WIDTH, PAGE_HEIGHT));

    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();/*w w  w  .j a  va 2 s . com*/

    PdfContentByte cb = writer.getDirectContent();

    Check check = new Check();
    check.defaultFont = BaseFont.createFont("Helvetica", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.defaultFontSize = 8;
    check.defaultFontLeading = 10;
    check.largeFontSize = 9;
    check.largeFontLeading = 12;
    check.fixedWidthFont = createFixedFont();
    check.fixedWidthFontSize = 8;
    check.voidFont = BaseFont.createFont("Helvetica-Bold", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    check.voidFontSize = 14;
    check.micrFont = createMicrFont();
    check.micrFontSize = 12;
    check.model = model;
    check.x = 0;
    check.y = 0;
    check.renderMode = CheckRenderMode.CHECK;

    check.render(cb);

    if (StubPrintMode.CHECK_DUPLICATE == model.stubPrintMode) {
        check.renderMode = CheckRenderMode.STUB;
        check.y = document.top() - (8.2f * POINTS_IN_A_CM);
        check.render(cb);
    } else if (StubPrintMode.CUSTOM == model.stubPrintMode) {
        PdfReader reader = new PdfReader(model.customStubPdf);
        PdfImportedPage customPage = writer.getImportedPage(reader, 1);
        cb.addTemplate(customPage, 0f, 0f);
    } else {
        throw new RuntimeException("Unknown stub print mode: " + model.stubPrintMode);
    }

    document.close();
}

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 va  2 s.  c o m

    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.pureinfo.srm.patent.action.PatentPrintPdfAction.java

License:Open Source License

/**
 * @see com.pureinfo.ark.interaction.ActionBase#executeAction()
 *//*  w  w w  . j  a va2  s .c o m*/
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.t2.compassionMeditation.ViewSessionsActivity.java

License:Open Source License

/**
 * Create a PDF file based on the contents of the graph
 *///from   w  w w .j a  v a 2 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.vinhteam.flyingsaucer.cli.Main.java

public static void htmlToPdf(String html, String pdfFile) {
    try {/*w  ww  .  ja  v a2 s . c om*/

        OutputStream pdfOut = new FileOutputStream(pdfFile);

        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver resolver = renderer.getFontResolver();

        Main main = new Main();
        File fontFile = main.getFileFont();
        try {
            resolver.addFont(fontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        renderer.setDocumentFromString(html);
        renderer.layout();

        renderer.createPDF(pdfOut);

        pdfOut.close();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file.// ww  w.  jav  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  www. j  a  v a 2s. com
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./* ww  w.  ja v a  2 s . c om*/
 * @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) {
    }
}

From source file:demo.dwr.simple.UploadDownload.java

License:Apache License

/**
 * Generates a PDF file with the given text
 * http://itext.ugent.be/itext-in-action/
 * @return A PDF file as a byte array/*from w ww . ja  v  a 2s.c  o  m*/
 */
public FileTransfer downloadPdfFile(String contents) throws Exception {
    if (contents == null || contents.length() == 0) {
        contents = "[BLANK]";
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    // ?itext-asian
    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    // ?WINDOW c:\windows\Fonts\xxx.ttf
    // ?classpath: /src/main/resources/fonts/simsong.ttf

    Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents, fontChinese));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
}

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

@Override
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //inicializar documento: tamano de pagina, orientacion, margenes
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);
    doc.setPageSize(PageSize.LETTER.rotate());
    doc.setMargins(30, 30, 30, 40);/*  w ww  .  java 2  s.  c o m*/

    doc.open();

    //crear fonts por defecto
    tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD);
    tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL);

    //definir pie de pagina del lado izquierdo
    String footerText = this.getFooter(); //read it from config.xml or web.xml
    String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm");

    //crear template (objeto interno de IText) y manejador de evento 
    //para imprimir el pie de pagina
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb = docWriter.getDirectContent();
    tpl = cb.createTemplate(20, 14);
    docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate));

    //titulo - lo lee de config.xml por defecto
    reportTitle = getReportTitle();
    Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD));
    t.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.add(t);

    //logo
    img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false));
    img.scalePercent(100);
    float imgY = doc.top() - img.getHeight();
    float imgX = doc.left();
    img.setAbsolutePosition(imgX, imgY);
    doc.add(img);

    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));

    //for each master record print a master/detail section
    MasterDetailReader dataobj = (MasterDetailReader) data;
    Recordset master = dataobj.getRecordset("master");
    master.top();
    while (master.next()) {
        //blank line
        doc.add(new Paragraph(" "));

        //print master section
        doc.add(getGroupMaster(master));

        //print detail section
        doc.add(getGroupDetail(master, dataobj.getDetail(master)));

    }

    //print grand total
    doc.add(new Paragraph(" "));

    doc.close();
    docWriter.close();

}