Example usage for com.lowagie.text PageSize A4

List of usage examples for com.lowagie.text PageSize A4

Introduction

In this page you can find the example usage for com.lowagie.text PageSize A4.

Prototype

Rectangle A4

To view the source code for com.lowagie.text PageSize A4.

Click Source Link

Document

This is the a4 format

Usage

From source file:org.egov.works.utils.AbstractPDFGenerator.java

License:Open Source License

public AbstractPDFGenerator(final OutputStream out, final String type) {
    this.out = out;
    try {/*ww  w  .j ava  2s  . c  om*/
        if (type != null && "landscape".equalsIgnoreCase(type))
            document = new Document(PageSize.A4.rotate());
        else
            document = new Document();

        PdfWriter.getInstance(document, out);
        document.open();
    } catch (final Exception e) {
        throw new ApplicationRuntimeException("estimate.pdf.error", e);
    }
}

From source file:org.endeavour.mgmt.controller.servlet.CreateProjectPlan.java

License:Open Source License

public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws IOException {
    try {//from   www  .  j a  v  a 2  s . c o  m

        Document theDocument = new Document(PageSize.A4.rotate());
        aResponse.setContentType("application/pdf");
        PdfWriter.getInstance(theDocument, aResponse.getOutputStream());
        theDocument.open();

        String theProjectIdValue = aRequest.getParameter(ProjectPlanMaintenance.PROJECT_ID);
        StringTokenizer theId = new StringTokenizer(theProjectIdValue, ":");
        Integer theProjectId = new Integer(theId.nextToken());
        ProjectPlanMaintenance thePlanMaintenance = new ProjectPlanMaintenance(null);
        List<IPlanElement> thePlanElements = thePlanMaintenance.getProjectPlanReportingData(theProjectId);

        Task theTask = null;
        IPlanElement thePlanElement = null;
        TaskSeries theSeries = new TaskSeries(SCHEDULED);
        int theDataSetIndex = 0;

        Date theStartDate = null;
        Date theEndDate = null;
        String theDescription = null;

        for (int i = 0; i < thePlanElements.size(); i++) {
            thePlanElement = thePlanElements.get(i);

            theTask = new Task(thePlanElement.getElementType() + " : " + thePlanElement.getName(),
                    thePlanElement.getStartDate(), thePlanElement.getEndDate());
            theTask.setPercentComplete(thePlanElement.getProgress() * 0.01);
            theSeries.add(theTask);

            if (i == 0) {
                theStartDate = thePlanElement.getStartDate();
                theEndDate = thePlanElement.getEndDate();
                theDescription = thePlanElement.getElementType() + " : " + thePlanElement.getName();
            }

            theDataSetIndex++;
            // Each page displays up to 25 tasks before creating a new one.
            if (theDataSetIndex == 25) {
                theDataSetIndex = 0;
                this.createReportPage(theDocument, theSeries, theStartDate, theEndDate, theDescription);
                theSeries = new TaskSeries(SCHEDULED);
            }
        }
        this.createReportPage(theDocument, theSeries, theStartDate, theEndDate, theDescription);

        theDocument.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.frameworkset.web.servlet.view.document.AbstractPdfView.java

License:Apache License

/**
 * Create a new document to hold the PDF contents.
 * <p>By default returns an A4 document, but the subclass can specify any
 * Document, possibly parameterized via bean properties defined on the View.
 * @return the newly created iText Document instance
 * @see com.lowagie.text.Document#Document(com.lowagie.text.Rectangle)
 *///from   w w  w  .j a va 2  s  .co  m
protected Document newDocument() {
    return new Document(PageSize.A4);
}

From source file:org.goobi.managedbeans.ProcessBean.java

License:Open Source License

public void generateResultAsPdf() {
    FacesContext facesContext = FacesContextHelper.getCurrentFacesContext();
    if (!facesContext.getResponseComplete()) {

        /*/*from  w  w  w.  ja va2s.c  o m*/
         * -------------------------------- Vorbereiten der Header-Informationen --------------------------------
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.pdf");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\"");
            ServletOutputStream out = response.getOutputStream();
            SearchResultHelper sch = new SearchResultHelper();
            HSSFWorkbook wb = sch.getResult(prepareSearchColumnData(), this.filter, sortList(),
                    this.showClosedProcesses, this.showArchivedProjects);

            List<List<HSSFCell>> rowList = new ArrayList<>();
            HSSFSheet mySheet = wb.getSheetAt(0);
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                List<HSSFCell> row = new ArrayList<>();
                while (cellIter.hasNext()) {
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    row.add(myCell);
                }
                rowList.add(row);
            }
            Document document = new Document();
            Rectangle a4quer = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
            PdfWriter.getInstance(document, out);
            document.setPageSize(a4quer);
            document.open();
            if (rowList.size() > 0) {
                //                    Paragraph p = new Paragraph(rowList.get(0).get(0).toString());
                //                    document.add(p);
                PdfPTable table = new PdfPTable(rowList.get(0).size());
                table.setSpacingBefore(20);

                for (int i = 0; i < rowList.size(); i++) {

                    List<HSSFCell> row = rowList.get(i);
                    table.completeRow();
                    for (int j = 0; j < row.size(); j++) {
                        HSSFCell myCell = row.get(j);
                        String stringCellValue = myCell.toString();
                        table.addCell(stringCellValue);
                    }

                }
                document.add(table);
            }

            document.close();
            out.flush();
            facesContext.responseComplete();

        } catch (Exception e) {
        }
    }
}

From source file:org.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String formattedSvgEncoded = req.getParameter("fsvg");
    String uuid = Utils.getUUID(req);
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String transformto = req.getParameter("transformto");
    String jpdl = req.getParameter("jpdl");
    String gpd = req.getParameter("gpd");
    String bpmn2in = req.getParameter("bpmn2");
    String jsonin = req.getParameter("json");
    String preprocessingData = req.getParameter("pp");
    String respaction = req.getParameter("respaction");
    String pp = req.getParameter("pp");
    String processid = req.getParameter("processid");
    String sourceEnc = req.getParameter("enc");
    String convertServiceTasks = req.getParameter("convertservicetasks");
    String htmlSourceEnc = req.getParameter("htmlenc");

    String formattedSvg = (formattedSvgEncoded == null ? ""
            : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8"));

    String htmlSource = (htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8"));

    if (sourceEnc != null && sourceEnc.equals("true")) {
        bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8");
    }/*from w w  w.jav  a2 s .  co  m*/

    if (profile == null) {
        profile = _profileService.findProfile(req, profileName);
    }

    DroolsFactoryImpl.init();
    BpsimFactoryImpl.init();

    Repository repository = profile.getRepository();

    if (transformto != null && transformto.equals(TO_PDF)) {
        if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {

            try {
                ByteArrayOutputStream pdfBout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout);
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");

                float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\"";
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint);
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint);

                ByteArrayOutputStream imageBout = new ByteArrayOutputStream();
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(imageBout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(imageBout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();

                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");

                resp.getWriter()
                        .write("<object type=\"application/pdf\" " + objStyle
                                + " data=\"data:application/pdf;base64,"
                                + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>");
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        } else {
            storeInRepository(uuid, formattedSvg, transformto, processid, repository);

            try {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/pdf");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
                }

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(bout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        }
    } else if (transformto != null && transformto.equals(TO_PNG)) {
        try {
            if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");
                if (req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) {
                    int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                    int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                    resp.getWriter()
                            .write("<img width=\"" + widthHint + "\" height=\"" + heightHint
                                    + "\" src=\"data:image/png;base64,"
                                    + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                } else {
                    resp.getWriter().write("<img src=\"data:image/png;base64,"
                            + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                }
            } else {
                storeInRepository(uuid, formattedSvg, transformto, processid, repository);
                resp.setContentType("image/png");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\"");
                }

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(resp.getOutputStream());
                t.transcode(input, output);
            }
        } catch (TranscoderException e) {
            resp.sendError(500, e.getMessage());
        }
    } else if (transformto != null && transformto.equals(TO_SVG)) {
        storeInRepository(uuid, formattedSvg, transformto, processid, repository);
    } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) {
        try {
            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\"");
                bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\"");
            }

            Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in);
            def.setTargetNamespace("http://www.omg.org/bpmn20");

            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                // fix the data input associations for converted tasks
                List<RootElement> rootElements = def.getRootElements();
                for (RootElement root : rootElements) {
                    if (root instanceof Process) {
                        updateTaskDataInputs((Process) root, def);
                    }
                }
            }

            // get the xml from Definitions
            ResourceSet rSet = new ResourceSetImpl();
            rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
                    new JBPMBpmn2ResourceFactoryImpl());
            JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet
                    .createResource(URI.createURI("virtual.bpmn2"));
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8");
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION,
                    true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF,
                    JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD);
            bpmn2resource.setEncoding("UTF-8");
            rSet.getResources().add(bpmn2resource);
            bpmn2resource.getContents().add(def);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bpmn2resource.save(outputStream, new HashMap<Object, Object>());
            String revisedXmlModel = outputStream.toString();
            String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            resp.getWriter().print(json);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
        }
    } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) {
        try {
            DroolsFactoryImpl.init();
            BpsimFactoryImpl.init();
            if (preprocessingData == null) {
                preprocessingData = "";
            }
            String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData);
            resp.setContentType("application/xml");
            resp.getWriter().print(processXML);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/xml");
            resp.getWriter().print("");
        }
    } else if (transformto != null && transformto.equals(HTML_TO_PDF)) {
        try {
            resp.setContentType("application/pdf");
            if (processid != null) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
            } else {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
            }

            Document pdfDoc = new Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
            pdfDoc.open();
            pdfDoc.addCreator("jBPM Designer");
            pdfDoc.addSubject("Business Process Documentation");
            pdfDoc.addCreationDate();
            pdfDoc.addTitle("Process Documentation");

            HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
            htmlWorker.parse(new StringReader(htmlSource));
            pdfDoc.close();
        } catch (DocumentException e) {
            resp.sendError(500, e.getMessage());
        }
    }
}

From source file:org.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

protected void storeInRepository(String uuid, String svg, String transformto, String processid,
        Repository repository) {//  www  .  j a  va2s  .c o m
    String assetFullName = "";
    try {
        if (processid != null) {
            Asset<byte[]> processAsset = repository.loadAsset(uuid);
            String assetExt = "";
            String assetFileExt = "";
            if (transformto.equals(TO_PDF)) {
                assetExt = "-pdf";
                assetFileExt = ".pdf";
            }
            if (transformto.equals(TO_PNG)) {
                assetExt = "-image";
                assetFileExt = ".png";
            }
            if (transformto.equals(TO_SVG)) {
                assetExt = "-svg";
                assetFileExt = ".svg";
            }

            if (processid.startsWith(".")) {
                processid = processid.substring(1, processid.length());
            }
            assetFullName = processid + assetExt + assetFileExt;

            repository.deleteAssetFromPath(
                    processAsset.getAssetLocation().replaceAll("\\s", "%20") + "/" + assetFullName);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            if (transformto.equals(TO_PDF)) {

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, outputStream);
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(svg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(bout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();
            } else if (transformto.equals(TO_PNG)) {
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(svg));
                TranscoderOutput output = new TranscoderOutput(outputStream);
                try {
                    t.transcode(input, output);
                } catch (Exception e) {
                    // issue with batik here..do not make a big deal
                    _logger.debug(e.getMessage());
                }
            } else if (transformto.equals(TO_SVG)) {
                OutputStreamWriter outStreamWriter = new OutputStreamWriter(outputStream);
                outStreamWriter.write(svg);
                outStreamWriter.close();
            }
            AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);

            builder.name(processid + assetExt).type(assetFileExt.substring(1))
                    .location(processAsset.getAssetLocation().replaceAll("\\s", "%20"))
                    .version(processAsset.getVersion()).content(outputStream.toByteArray());

            Asset<byte[]> resourceAsset = builder.getAsset();

            repository.createAsset(resourceAsset);
        }
    } catch (Exception e) {
        // just log that error happened
        if (e.getMessage() != null) {
            _logger.error(e.getMessage());
        } else {
            _logger.error(e.getClass().toString() + " " + assetFullName);
        }
        e.printStackTrace();
    }
}

From source file:org.jivesoftware.openfire.archive.ConversationUtils.java

License:Open Source License

private ByteArrayOutputStream buildPDFContent(Conversation conversation, Map<String, Font> colorMap) {
    Font roomEvent = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.ITALIC, new Color(0xFF, 0x00, 0xFF));

    try {/*from w w w  .  j ava2s .  co m*/
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener());
        document.open();

        Paragraph p = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.title", MonitoringConstants.NAME),
                FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
        document.add(p);
        document.add(Chunk.NEWLINE);

        ConversationInfo coninfo = new ConversationUtils().getConversationInfo(conversation.getConversationID(),
                false);

        String participantsDetail;
        if (coninfo.getAllParticipants() == null) {
            participantsDetail = coninfo.getParticipant1() + ", " + coninfo.getParticipant2();
        } else {
            participantsDetail = String.valueOf(coninfo.getAllParticipants().length);
        }

        Paragraph chapterTitle = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.participants", MonitoringConstants.NAME)
                        + " " + participantsDetail,
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));

        document.add(chapterTitle);

        Paragraph startDate = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.startdate", MonitoringConstants.NAME) + " "
                        + coninfo.getDate(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(startDate);

        Paragraph duration = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.duration", MonitoringConstants.NAME) + " "
                        + coninfo.getDuration(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(duration);

        Paragraph messageCount = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.messagecount", MonitoringConstants.NAME)
                        + " " + conversation.getMessageCount(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(messageCount);
        document.add(Chunk.NEWLINE);

        Paragraph messageParagraph;

        for (ArchivedMessage message : conversation.getMessages()) {
            String time = JiveGlobals.formatTime(message.getSentDate());
            String from = message.getFromJID().getNode();
            if (conversation.getRoom() != null) {
                from = message.getToJID().getResource();
            }
            String body = message.getBody();
            String prefix;
            if (!message.isRoomEvent()) {
                prefix = "[" + time + "] " + from + ":  ";
                Font font = colorMap.get(message.getFromJID().toString());
                if (font == null) {
                    font = colorMap.get(message.getFromJID().toBareJID());
                }
                if (font == null) {
                    font = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.BOLD, Color.BLACK);
                }
                messageParagraph = new Paragraph(new Chunk(prefix, font));
            } else {
                prefix = "[" + time + "] ";
                messageParagraph = new Paragraph(new Chunk(prefix, roomEvent));
            }
            messageParagraph.add(body);
            messageParagraph.add(" ");
            document.add(messageParagraph);
        }

        document.close();
        return baos;
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage(), e);
        return null;
    }
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java

License:Open Source License

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[],
        Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {

    try {//from w  w w. java2  s  .com
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();

        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - "
                    + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName,
                    FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void handouts(String file) {
    try {/*from w  ww.j ava2  s. co m*/
        File src = new File(selectedFile);

        File dest = new File(file);

        int pages = 4;

        float x1 = 30f;
        float x2 = 280f;
        float x3 = 320f;
        float x4 = 565f;

        float[] y1 = new float[pages];
        float[] y2 = new float[pages];

        float height = (778f - (20f * (pages - 1))) / pages;
        y1[0] = 812f;
        y2[0] = 812f - height;

        for (int i = 1; i < pages; i++) {
            y1[i] = y2[i - 1] - 20f;
            y2[i] = y1[i] - height;
        }

        // we create a reader for a certain document
        PdfReader reader = new PdfReader(src.getAbsolutePath());
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();

        // step 1: creation of a document-object
        Document document = new Document(PageSize.A4);
        // step 2: we create a writer that listens to the document
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3: we open the document
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfImportedPage page;
        int rotation;
        int i = 0;
        int p = 0;
        // step 4: we add content
        while (i < n) {
            i++;
            Rectangle rect = reader.getPageSizeWithRotation(i);
            float factorx = (x2 - x1) / rect.width();
            float factory = (y1[p] - y2[p]) / rect.height();
            float factor = (factorx < factory ? factorx : factory);
            float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.width() * factor) / 2f);
            float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.height() * factor) / 2f);
            page = writer.getImportedPage(reader, i);
            rotation = reader.getPageRotation(i);
            if (rotation == 90 || rotation == 270) {
                cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.height() * factor);
            } else {
                cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
            }
            cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
            cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
            for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
                cb.moveTo(x3, l);
                cb.lineTo(x4, l);
            }
            cb.rectangle(x1 + dx, y2[p] + dy, rect.width() * factor, rect.height() * factor);
            cb.stroke();

            p++;
            if (p == pages) {
                p = 0;
                document.newPage();
            }
        }
        // step 5: we close the document
        document.close();
    } catch (Exception e) {

        System.err.println(e.getMessage());
    }
}

From source file:org.kuali.kfs.gl.report.TransactionReport.java

License:Open Source License

/**
 * Generates transaction report//from  w ww  .ja  v  a2 s. c o m
 * 
 * @param errorSortedList list of error'd transactions
 * @param reportErrors map containing transactions and the errors associated with each transaction
 * @param reportSummary list of summary objects
 * @param runDate date report is run
 * @param title title of report
 * @param fileprefix file prefix of report file
 * @param destinationDirectory destination of where report file will reside
 */
public void generateReport(List<Transaction> errorSortedList, Map<Transaction, List<Message>> reportErrors,
        List<Summary> reportSummary, Date runDate, String title, String fileprefix,
        String destinationDirectory) {
    LOG.debug("generateReport() started");

    Font headerFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD);
    Font textFont = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL);

    Document document = new Document(PageSize.A4.rotate());

    PageHelper helper = new PageHelper();
    helper.runDate = runDate;
    helper.headerFont = headerFont;
    helper.title = title;

    try {
        DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);

        String filename = destinationDirectory + "/" + fileprefix + "_";
        filename = filename + dateTimeService.toDateTimeStringForFilename(runDate);
        filename = filename + ".pdf";
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        writer.setPageEvent(helper);

        document.open();
        appendReport(document, headerFont, textFont, errorSortedList, reportErrors, reportSummary, runDate);
    } catch (DocumentException de) {
        LOG.error("generateReport() Error creating PDF report", de);
        throw new RuntimeException("Report Generation Failed: " + de.getMessage());
    } catch (FileNotFoundException fnfe) {
        LOG.error("generateReport() Error writing PDF report", fnfe);
        throw new RuntimeException("Report Generation Failed: Error writing to file " + fnfe.getMessage());
    } finally {
        if ((document != null) && document.isOpen()) {
            document.close();
        }
    }
}